git.delta.rocks / unique-network / refs/commits / 2e0d1a668d33

difftreelog

source

pallets/refungible/src/erc.rs31.7 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	types::Property as PropertyStruct, weight,31};32use frame_support::{BoundedBTreeMap, BoundedVec};33use pallet_common::{34	CollectionHandle, CollectionPropertyPermissions,35	erc::{CommonEvmHandler, CollectionCall, static_property::key},36};37use pallet_evm::{account::CrossAccountId, PrecompileHandle};38use pallet_evm_coder_substrate::{call, dispatch_to_evm};39use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};40use sp_core::H160;41use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};42use up_data_structs::{43	CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,44	PropertyKeyPermission, PropertyPermission, TokenId,45};4647use crate::{48	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,49	TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,50};5152pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5354/// @title A contract that allows to set and delete token properties and change token property permissions.55#[solidity_interface(name = TokenProperties)]56impl<T: Config> RefungibleHandle<T> {57	/// @notice Set permissions for token property.58	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.59	/// @param key Property key.60	/// @param isMutable Permission to mutate property.61	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.62	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.63	fn set_token_property_permission(64		&mut self,65		caller: caller,66		key: string,67		is_mutable: bool,68		collection_admin: bool,69		token_owner: bool,70	) -> Result<()> {71		let caller = T::CrossAccountId::from_eth(caller);72		<Pallet<T>>::set_token_property_permissions(73			self,74			&caller,75			vec![PropertyKeyPermission {76				key: <Vec<u8>>::from(key)77					.try_into()78					.map_err(|_| "too long key")?,79				permission: PropertyPermission {80					mutable: is_mutable,81					collection_admin,82					token_owner,83				},84			}],85		)86		.map_err(dispatch_to_evm::<T>)87	}8889	/// @notice Set token property value.90	/// @dev Throws error if `msg.sender` has no permission to edit the property.91	/// @param tokenId ID of the token.92	/// @param key Property key.93	/// @param value Property value.94	#[solidity(hide)]95	fn set_property(96		&mut self,97		caller: caller,98		token_id: uint256,99		key: string,100		value: bytes,101	) -> Result<()> {102		let caller = T::CrossAccountId::from_eth(caller);103		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;104		let key = <Vec<u8>>::from(key)105			.try_into()106			.map_err(|_| "key too long")?;107		let value = value.0.try_into().map_err(|_| "value too long")?;108109		let nesting_budget = self110			.recorder111			.weight_calls_budget(<StructureWeight<T>>::find_parent());112113		<Pallet<T>>::set_token_property(114			self,115			&caller,116			TokenId(token_id),117			Property { key, value },118			&nesting_budget,119		)120		.map_err(dispatch_to_evm::<T>)121	}122123	/// @notice Set token properties value.124	/// @dev Throws error if `msg.sender` has no permission to edit the property.125	/// @param tokenId ID of the token.126	/// @param properties settable properties127	fn set_properties(128		&mut self,129		caller: caller,130		token_id: uint256,131		properties: Vec<PropertyStruct>,132	) -> Result<()> {133		let caller = T::CrossAccountId::from_eth(caller);134		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;135136		let nesting_budget = self137			.recorder138			.weight_calls_budget(<StructureWeight<T>>::find_parent());139140		let properties = properties141			.into_iter()142			.map(|PropertyStruct { key, value }| {143				let key = <Vec<u8>>::from(key)144					.try_into()145					.map_err(|_| "key too large")?;146147				let value = value.0.try_into().map_err(|_| "value too large")?;148149				Ok(Property { key, value })150			})151			.collect::<Result<Vec<_>>>()?;152153		<Pallet<T>>::set_token_properties(154			self,155			&caller,156			TokenId(token_id),157			properties.into_iter(),158			<Pallet<T>>::token_exists(&self, TokenId(token_id)),159			&nesting_budget,160		)161		.map_err(dispatch_to_evm::<T>)162	}163164	/// @notice Delete token property value.165	/// @dev Throws error if `msg.sender` has no permission to edit the property.166	/// @param tokenId ID of the token.167	/// @param key Property key.168	#[solidity(hide)]169	fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {170		let caller = T::CrossAccountId::from_eth(caller);171		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;172		let key = <Vec<u8>>::from(key)173			.try_into()174			.map_err(|_| "key too long")?;175176		let nesting_budget = self177			.recorder178			.weight_calls_budget(<StructureWeight<T>>::find_parent());179180		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)181			.map_err(dispatch_to_evm::<T>)182	}183184	/// @notice Delete token properties value.185	/// @dev Throws error if `msg.sender` has no permission to edit the property.186	/// @param tokenId ID of the token.187	/// @param keys Properties key.188	fn delete_properties(189		&mut self,190		token_id: uint256,191		caller: caller,192		keys: Vec<string>,193	) -> 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 keys = keys197			.into_iter()198			.map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))199			.collect::<Result<Vec<_>>>()?;200201		let nesting_budget = self202			.recorder203			.weight_calls_budget(<StructureWeight<T>>::find_parent());204205		<Pallet<T>>::delete_token_properties(206			self,207			&caller,208			TokenId(token_id),209			keys.into_iter(),210			&nesting_budget,211		)212		.map_err(dispatch_to_evm::<T>)213	}214215	/// @notice Get token property value.216	/// @dev Throws error if key not found217	/// @param tokenId ID of the token.218	/// @param key Property key.219	/// @return Property value bytes220	fn property(&self, token_id: uint256, key: string) -> Result<bytes> {221		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;222		let key = <Vec<u8>>::from(key)223			.try_into()224			.map_err(|_| "key too long")?;225226		let props = <TokenProperties<T>>::get((self.id, token_id));227		let prop = props.get(&key).ok_or("key not found")?;228229		Ok(prop.to_vec().into())230	}231}232233#[derive(ToLog)]234pub enum ERC721Events {235	/// @dev This event emits when NFTs are created (`from` == 0) and destroyed236	///  (`to` == 0). Exception: during contract creation, any number of RFTs237	///  may be created and assigned without emitting Transfer.238	Transfer {239		#[indexed]240		from: address,241		#[indexed]242		to: address,243		#[indexed]244		token_id: uint256,245	},246	/// @dev Not supported247	Approval {248		#[indexed]249		owner: address,250		#[indexed]251		approved: address,252		#[indexed]253		token_id: uint256,254	},255	/// @dev Not supported256	#[allow(dead_code)]257	ApprovalForAll {258		#[indexed]259		owner: address,260		#[indexed]261		operator: address,262		approved: bool,263	},264}265266#[derive(ToLog)]267pub enum ERC721UniqueMintableEvents {268	/// @dev Not supported269	#[allow(dead_code)]270	MintingFinished {},271}272273#[solidity_interface(name = ERC721Metadata)]274impl<T: Config> RefungibleHandle<T>275where276	T::AccountId: From<[u8; 32]>,277{278	/// @notice A descriptive name for a collection of NFTs in this contract279	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`280	#[solidity(hide, rename_selector = "name")]281	fn name_proxy(&self) -> Result<string> {282		self.name()283	}284285	/// @notice An abbreviated name for NFTs in this contract286	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`287	#[solidity(hide, rename_selector = "symbol")]288	fn symbol_proxy(&self) -> Result<string> {289		self.symbol()290	}291292	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.293	///294	/// @dev If the token has a `url` property and it is not empty, it is returned.295	///  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`.296	///  If the collection property `baseURI` is empty or absent, return "" (empty string)297	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix298	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).299	///300	/// @return token's const_metadata301	#[solidity(rename_selector = "tokenURI")]302	fn token_uri(&self, token_id: uint256) -> Result<string> {303		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;304305		match get_token_property(self, token_id_u32, &key::url()).as_deref() {306			Err(_) | Ok("") => (),307			Ok(url) => {308				return Ok(url.into());309			}310		};311312		let base_uri =313			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())314				.map(BoundedVec::into_inner)315				.map(string::from_utf8)316				.transpose()317				.map_err(|e| {318					Error::Revert(alloc::format!(319						"Can not convert value \"baseURI\" to string with error \"{}\"",320						e321					))322				})?;323324		let base_uri = match base_uri.as_deref() {325			None | Some("") => {326				return Ok("".into());327			}328			Some(base_uri) => base_uri.into(),329		};330331		Ok(332			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {333				Err(_) | Ok("") => base_uri,334				Ok(suffix) => base_uri + suffix,335			},336		)337	}338}339340/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension341/// @dev See https://eips.ethereum.org/EIPS/eip-721342#[solidity_interface(name = ERC721Enumerable)]343impl<T: Config> RefungibleHandle<T> {344	/// @notice Enumerate valid RFTs345	/// @param index A counter less than `totalSupply()`346	/// @return The token identifier for the `index`th NFT,347	///  (sort order not specified)348	fn token_by_index(&self, index: uint256) -> Result<uint256> {349		Ok(index)350	}351352	/// Not implemented353	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {354		// TODO: Not implemetable355		Err("not implemented".into())356	}357358	/// @notice Count RFTs tracked by this contract359	/// @return A count of valid RFTs tracked by this contract, where each one of360	///  them has an assigned and queryable owner not equal to the zero address361	fn total_supply(&self) -> Result<uint256> {362		self.consume_store_reads(1)?;363		Ok(<Pallet<T>>::total_supply(self).into())364	}365}366367/// @title ERC-721 Non-Fungible Token Standard368/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md369#[solidity_interface(name = ERC721, events(ERC721Events))]370impl<T: Config> RefungibleHandle<T> {371	/// @notice Count all RFTs assigned to an owner372	/// @dev RFTs assigned to the zero address are considered invalid, and this373	///  function throws for queries about the zero address.374	/// @param owner An address for whom to query the balance375	/// @return The number of RFTs owned by `owner`, possibly zero376	fn balance_of(&self, owner: address) -> Result<uint256> {377		self.consume_store_reads(1)?;378		let owner = T::CrossAccountId::from_eth(owner);379		let balance = <AccountBalance<T>>::get((self.id, owner));380		Ok(balance.into())381	}382383	/// @notice Find the owner of an RFT384	/// @dev RFTs assigned to zero address are considered invalid, and queries385	///  about them do throw.386	///  Returns special 0xffffffffffffffffffffffffffffffffffffffff address for387	///  the tokens that are partially owned.388	/// @param tokenId The identifier for an RFT389	/// @return The address of the owner of the RFT390	fn owner_of(&self, token_id: uint256) -> Result<address> {391		self.consume_store_reads(2)?;392		let token = token_id.try_into()?;393		let owner = <Pallet<T>>::token_owner(self.id, token);394		Ok(owner395			.map(|address| *address.as_eth())396			.unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))397	}398399	/// @dev Not implemented400	fn safe_transfer_from_with_data(401		&mut self,402		_from: address,403		_to: address,404		_token_id: uint256,405		_data: bytes,406	) -> Result<void> {407		// TODO: Not implemetable408		Err("not implemented".into())409	}410411	/// @dev Not implemented412	fn safe_transfer_from(413		&mut self,414		_from: address,415		_to: address,416		_token_id: uint256,417	) -> Result<void> {418		// TODO: Not implemetable419		Err("not implemented".into())420	}421422	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE423	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE424	///  THEY MAY BE PERMANENTLY LOST425	/// @dev Throws unless `msg.sender` is the current owner or an authorized426	///  operator for this RFT. Throws if `from` is not the current owner. Throws427	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.428	///  Throws if RFT pieces have multiple owners.429	/// @param from The current owner of the NFT430	/// @param to The new owner431	/// @param tokenId The NFT to transfer432	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]433	fn transfer_from(434		&mut self,435		caller: caller,436		from: address,437		to: address,438		token_id: uint256,439	) -> Result<void> {440		let caller = T::CrossAccountId::from_eth(caller);441		let from = T::CrossAccountId::from_eth(from);442		let to = T::CrossAccountId::from_eth(to);443		let token = token_id.try_into()?;444		let budget = self445			.recorder446			.weight_calls_budget(<StructureWeight<T>>::find_parent());447448		let balance = balance(&self, token, &from)?;449		ensure_single_owner(&self, token, balance)?;450451		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)452			.map_err(dispatch_to_evm::<T>)?;453454		Ok(())455	}456457	/// @dev Not implemented458	fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {459		Err("not implemented".into())460	}461462	/// @dev Not implemented463	fn set_approval_for_all(464		&mut self,465		_caller: caller,466		_operator: address,467		_approved: bool,468	) -> Result<void> {469		// TODO: Not implemetable470		Err("not implemented".into())471	}472473	/// @dev Not implemented474	fn get_approved(&self, _token_id: uint256) -> Result<address> {475		// TODO: Not implemetable476		Err("not implemented".into())477	}478479	/// @dev Not implemented480	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {481		// TODO: Not implemetable482		Err("not implemented".into())483	}484}485486/// Returns amount of pieces of `token` that `owner` have487pub fn balance<T: Config>(488	collection: &RefungibleHandle<T>,489	token: TokenId,490	owner: &T::CrossAccountId,491) -> Result<u128> {492	collection.consume_store_reads(1)?;493	let balance = <Balance<T>>::get((collection.id, token, &owner));494	Ok(balance)495}496497/// Throws if `owner_balance` is lower than total amount of `token` pieces498pub fn ensure_single_owner<T: Config>(499	collection: &RefungibleHandle<T>,500	token: TokenId,501	owner_balance: u128,502) -> Result<()> {503	collection.consume_store_reads(1)?;504	let total_supply = <TotalSupply<T>>::get((collection.id, token));505	if total_supply != owner_balance {506		return Err("token has multiple owners".into());507	}508	Ok(())509}510511/// @title ERC721 Token that can be irreversibly burned (destroyed).512#[solidity_interface(name = ERC721Burnable)]513impl<T: Config> RefungibleHandle<T> {514	/// @notice Burns a specific ERC721 token.515	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized516	///  operator of the current owner.517	/// @param tokenId The RFT to approve518	#[weight(<SelfWeightOf<T>>::burn_item_fully())]519	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {520		let caller = T::CrossAccountId::from_eth(caller);521		let token = token_id.try_into()?;522523		let balance = balance(&self, token, &caller)?;524		ensure_single_owner(&self, token, balance)?;525526		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;527		Ok(())528	}529}530531/// @title ERC721 minting logic.532#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]533impl<T: Config> RefungibleHandle<T> {534	fn minting_finished(&self) -> Result<bool> {535		Ok(false)536	}537538	/// @notice Function to mint token.539	/// @param to The new owner540	/// @return uint256 The id of the newly minted token541	#[weight(<SelfWeightOf<T>>::create_item())]542	fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {543		let token_id: uint256 = <TokensMinted<T>>::get(self.id)544			.checked_add(1)545			.ok_or("item id overflow")?546			.into();547		self.mint_check_id(caller, to, token_id)?;548		Ok(token_id)549	}550551	/// @notice Function to mint token.552	/// @dev `tokenId` should be obtained with `nextTokenId` method,553	///  unlike standard, you can't specify it manually554	/// @param to The new owner555	/// @param tokenId ID of the minted RFT556	#[solidity(hide, rename_selector = "mint")]557	#[weight(<SelfWeightOf<T>>::create_item())]558	fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {559		let caller = T::CrossAccountId::from_eth(caller);560		let to = T::CrossAccountId::from_eth(to);561		let token_id: u32 = token_id.try_into()?;562		let budget = self563			.recorder564			.weight_calls_budget(<StructureWeight<T>>::find_parent());565566		if <TokensMinted<T>>::get(self.id)567			.checked_add(1)568			.ok_or("item id overflow")?569			!= token_id570		{571			return Err("item id should be next".into());572		}573574		let users = [(to.clone(), 1)]575			.into_iter()576			.collect::<BTreeMap<_, _>>()577			.try_into()578			.unwrap();579		<Pallet<T>>::create_item(580			self,581			&caller,582			CreateItemData::<T::CrossAccountId> {583				users,584				properties: CollectionPropertiesVec::default(),585			},586			&budget,587		)588		.map_err(dispatch_to_evm::<T>)?;589590		Ok(true)591	}592593	/// @notice Function to mint token with the given tokenUri.594	/// @param to The new owner595	/// @param tokenUri Token URI that would be stored in the NFT properties596	/// @return uint256 The id of the newly minted token597	#[solidity(rename_selector = "mintWithTokenURI")]598	#[weight(<SelfWeightOf<T>>::create_item())]599	fn mint_with_token_uri(600		&mut self,601		caller: caller,602		to: address,603		token_uri: string,604	) -> Result<uint256> {605		let token_id: uint256 = <TokensMinted<T>>::get(self.id)606			.checked_add(1)607			.ok_or("item id overflow")?608			.into();609		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;610		Ok(token_id)611	}612613	/// @notice Function to mint token with the given tokenUri.614	/// @dev `tokenId` should be obtained with `nextTokenId` method,615	///  unlike standard, you can't specify it manually616	/// @param to The new owner617	/// @param tokenId ID of the minted RFT618	/// @param tokenUri Token URI that would be stored in the RFT properties619	#[solidity(hide, rename_selector = "mintWithTokenURI")]620	#[weight(<SelfWeightOf<T>>::create_item())]621	fn mint_with_token_uri_check_id(622		&mut self,623		caller: caller,624		to: address,625		token_id: uint256,626		token_uri: string,627	) -> Result<bool> {628		let key = key::url();629		let permission = get_token_permission::<T>(self.id, &key)?;630		if !permission.collection_admin {631			return Err("Operation is not allowed".into());632		}633634		let caller = T::CrossAccountId::from_eth(caller);635		let to = T::CrossAccountId::from_eth(to);636		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;637		let budget = self638			.recorder639			.weight_calls_budget(<StructureWeight<T>>::find_parent());640641		if <TokensMinted<T>>::get(self.id)642			.checked_add(1)643			.ok_or("item id overflow")?644			!= token_id645		{646			return Err("item id should be next".into());647		}648649		let mut properties = CollectionPropertiesVec::default();650		properties651			.try_push(Property {652				key,653				value: token_uri654					.into_bytes()655					.try_into()656					.map_err(|_| "token uri is too long")?,657			})658			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;659660		let users = [(to.clone(), 1)]661			.into_iter()662			.collect::<BTreeMap<_, _>>()663			.try_into()664			.unwrap();665		<Pallet<T>>::create_item(666			self,667			&caller,668			CreateItemData::<T::CrossAccountId> { users, properties },669			&budget,670		)671		.map_err(dispatch_to_evm::<T>)?;672		Ok(true)673	}674675	/// @dev Not implemented676	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {677		Err("not implementable".into())678	}679}680681fn get_token_property<T: Config>(682	collection: &CollectionHandle<T>,683	token_id: u32,684	key: &up_data_structs::PropertyKey,685) -> Result<string> {686	collection.consume_store_reads(1)?;687	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))688		.map_err(|_| Error::Revert("Token properties not found".into()))?;689	if let Some(property) = properties.get(key) {690		return Ok(string::from_utf8_lossy(property).into());691	}692693	Err("Property tokenURI not found".into())694}695696fn get_token_permission<T: Config>(697	collection_id: CollectionId,698	key: &PropertyKey,699) -> Result<PropertyPermission> {700	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)701		.map_err(|_| Error::Revert("No permissions for collection".into()))?;702	let a = token_property_permissions703		.get(key)704		.map(Clone::clone)705		.ok_or_else(|| {706			let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();707			Error::Revert(alloc::format!("No permission for key {}", key))708		})?;709	Ok(a)710}711712/// @title Unique extensions for ERC721.713#[solidity_interface(name = ERC721UniqueExtensions)]714impl<T: Config> RefungibleHandle<T>715where716	T::AccountId: From<[u8; 32]>,717{718	/// @notice A descriptive name for a collection of NFTs in this contract719	fn name(&self) -> Result<string> {720		Ok(decode_utf16(self.name.iter().copied())721			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))722			.collect::<string>())723	}724725	/// @notice An abbreviated name for NFTs in this contract726	fn symbol(&self) -> Result<string> {727		Ok(string::from_utf8_lossy(&self.token_prefix).into())728	}729730	/// @notice Transfer ownership of an RFT731	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`732	///  is the zero address. Throws if `tokenId` is not a valid RFT.733	///  Throws if RFT pieces have multiple owners.734	/// @param to The new owner735	/// @param tokenId The RFT to transfer736	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]737	fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {738		let caller = T::CrossAccountId::from_eth(caller);739		let to = T::CrossAccountId::from_eth(to);740		let token = token_id.try_into()?;741		let budget = self742			.recorder743			.weight_calls_budget(<StructureWeight<T>>::find_parent());744745		let balance = balance(self, token, &caller)?;746		ensure_single_owner(self, token, balance)?;747748		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)749			.map_err(dispatch_to_evm::<T>)?;750		Ok(())751	}752753	/// @notice Transfer ownership of an RFT754	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`755	///  is the zero address. Throws if `tokenId` is not a valid RFT.756	///  Throws if RFT pieces have multiple owners.757	/// @param to The new owner758	/// @param tokenId The RFT to transfer759	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]760	fn transfer_cross(761		&mut self,762		caller: caller,763		to: EthCrossAccount,764		token_id: uint256,765	) -> Result<void> {766		let caller = T::CrossAccountId::from_eth(caller);767		let to = to.into_sub_cross_account::<T>()?;768		let token = token_id.try_into()?;769		let budget = self770			.recorder771			.weight_calls_budget(<StructureWeight<T>>::find_parent());772773		let balance = balance(self, token, &caller)?;774		ensure_single_owner(self, token, balance)?;775776		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)777			.map_err(dispatch_to_evm::<T>)?;778		Ok(())779	}780781	/// @notice Transfer ownership of an RFT782	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`783	///  is the zero address. Throws if `tokenId` is not a valid RFT.784	///  Throws if RFT pieces have multiple owners.785	/// @param to The new owner786	/// @param tokenId The RFT to transfer787	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]788	fn transfer_from_cross(789		&mut self,790		caller: caller,791		from: EthCrossAccount,792		to: EthCrossAccount,793		token_id: uint256,794	) -> Result<void> {795		let caller = T::CrossAccountId::from_eth(caller);796		let from = from.into_sub_cross_account::<T>()?;797		let to = to.into_sub_cross_account::<T>()?;798		let token_id = token_id.try_into()?;799		let budget = self800			.recorder801			.weight_calls_budget(<StructureWeight<T>>::find_parent());802803		let balance = balance(self, token_id, &from)?;804		ensure_single_owner(self, token_id, balance)?;805806		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)807			.map_err(dispatch_to_evm::<T>)?;808		Ok(())809	}810811	/// @notice Burns a specific ERC721 token.812	/// @dev Throws unless `msg.sender` is the current owner or an authorized813	///  operator for this RFT. Throws if `from` is not the current owner. Throws814	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.815	///  Throws if RFT pieces have multiple owners.816	/// @param from The current owner of the RFT817	/// @param tokenId The RFT to transfer818	#[solidity(hide)]819	#[weight(<SelfWeightOf<T>>::burn_from())]820	fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {821		let caller = T::CrossAccountId::from_eth(caller);822		let from = T::CrossAccountId::from_eth(from);823		let token = token_id.try_into()?;824		let budget = self825			.recorder826			.weight_calls_budget(<StructureWeight<T>>::find_parent());827828		let balance = balance(self, token, &from)?;829		ensure_single_owner(self, token, balance)?;830831		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)832			.map_err(dispatch_to_evm::<T>)?;833		Ok(())834	}835836	/// @notice Burns a specific ERC721 token.837	/// @dev Throws unless `msg.sender` is the current owner or an authorized838	///  operator for this RFT. Throws if `from` is not the current owner. Throws839	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.840	///  Throws if RFT pieces have multiple owners.841	/// @param from The current owner of the RFT842	/// @param tokenId The RFT to transfer843	#[weight(<SelfWeightOf<T>>::burn_from())]844	fn burn_from_cross(845		&mut self,846		caller: caller,847		from: EthCrossAccount,848		token_id: uint256,849	) -> Result<void> {850		let caller = T::CrossAccountId::from_eth(caller);851		let from = from.into_sub_cross_account::<T>()?;852		let token = token_id.try_into()?;853		let budget = self854			.recorder855			.weight_calls_budget(<StructureWeight<T>>::find_parent());856857		let balance = balance(self, token, &from)?;858		ensure_single_owner(self, token, balance)?;859860		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)861			.map_err(dispatch_to_evm::<T>)?;862		Ok(())863	}864865	/// @notice Returns next free RFT ID.866	fn next_token_id(&self) -> Result<uint256> {867		self.consume_store_reads(1)?;868		Ok(<TokensMinted<T>>::get(self.id)869			.checked_add(1)870			.ok_or("item id overflow")?871			.into())872	}873874	/// @notice Function to mint multiple tokens.875	/// @dev `tokenIds` should be an array of consecutive numbers and first number876	///  should be obtained with `nextTokenId` method877	/// @param to The new owner878	/// @param tokenIds IDs of the minted RFTs879	#[solidity(hide)]880	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]881	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {882		let caller = T::CrossAccountId::from_eth(caller);883		let to = T::CrossAccountId::from_eth(to);884		let mut expected_index = <TokensMinted<T>>::get(self.id)885			.checked_add(1)886			.ok_or("item id overflow")?;887		let budget = self888			.recorder889			.weight_calls_budget(<StructureWeight<T>>::find_parent());890891		let total_tokens = token_ids.len();892		for id in token_ids.into_iter() {893			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;894			if id != expected_index {895				return Err("item id should be next".into());896			}897			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;898		}899		let users = [(to.clone(), 1)]900			.into_iter()901			.collect::<BTreeMap<_, _>>()902			.try_into()903			.unwrap();904		let create_item_data = CreateItemData::<T::CrossAccountId> {905			users,906			properties: CollectionPropertiesVec::default(),907		};908		let data = (0..total_tokens)909			.map(|_| create_item_data.clone())910			.collect();911912		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)913			.map_err(dispatch_to_evm::<T>)?;914		Ok(true)915	}916917	/// @notice Function to mint multiple tokens with the given tokenUris.918	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive919	///  numbers and first number should be obtained with `nextTokenId` method920	/// @param to The new owner921	/// @param tokens array of pairs of token ID and token URI for minted tokens922	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]923	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]924	fn mint_bulk_with_token_uri(925		&mut self,926		caller: caller,927		to: address,928		tokens: Vec<(uint256, string)>,929	) -> Result<bool> {930		let key = key::url();931		let caller = T::CrossAccountId::from_eth(caller);932		let to = T::CrossAccountId::from_eth(to);933		let mut expected_index = <TokensMinted<T>>::get(self.id)934			.checked_add(1)935			.ok_or("item id overflow")?;936		let budget = self937			.recorder938			.weight_calls_budget(<StructureWeight<T>>::find_parent());939940		let mut data = Vec::with_capacity(tokens.len());941		let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]942			.into_iter()943			.collect::<BTreeMap<_, _>>()944			.try_into()945			.unwrap();946		for (id, token_uri) in tokens {947			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;948			if id != expected_index {949				return Err("item id should be next".into());950			}951			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;952953			let mut properties = CollectionPropertiesVec::default();954			properties955				.try_push(Property {956					key: key.clone(),957					value: token_uri958						.into_bytes()959						.try_into()960						.map_err(|_| "token uri is too long")?,961				})962				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;963964			let create_item_data = CreateItemData::<T::CrossAccountId> {965				users: users.clone(),966				properties,967			};968			data.push(create_item_data);969		}970971		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)972			.map_err(dispatch_to_evm::<T>)?;973		Ok(true)974	}975976	/// Returns EVM address for refungible token977	///978	/// @param token ID of the token979	fn token_contract_address(&self, token: uint256) -> Result<address> {980		Ok(T::EvmTokenAddressMapping::token_to_address(981			self.id,982			token.try_into().map_err(|_| "token id overflow")?,983		))984	}985}986987#[solidity_interface(988	name = UniqueRefungible,989	is(990		ERC721,991		ERC721Enumerable,992		ERC721UniqueExtensions,993		ERC721UniqueMintable,994		ERC721Burnable,995		ERC721Metadata(if(this.flags.erc721metadata)),996		Collection(via(common_mut returns CollectionHandle<T>)),997		TokenProperties,998	)999)]1000impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}10011002// Not a tests, but code generators1003generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1004generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);10051006impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1007where1008	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1009{1010	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1011	fn call(1012		self,1013		handle: &mut impl PrecompileHandle,1014	) -> Option<pallet_common::erc::PrecompileResult> {1015		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1016	}1017}