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

difftreelog

chore add transfer events for transfering from and to partial ownership

Grigoriy Simonov2022-08-03parent: #abc6b05.patch.diff
in: master

3 files changed

modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
before · pallets/refungible/src/erc.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26	char::{REPLACEMENT_CHARACTER, decode_utf16},27	convert::TryInto,28};29use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};30use frame_support::{BoundedBTreeMap, BoundedVec};31use pallet_common::{32	CollectionHandle, CollectionPropertyPermissions,33	erc::{34		CommonEvmHandler, CollectionCall,35		static_property::{key, value as property_value},36	},37	eth::collection_id_to_address,38};39use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm, PrecompileHandle};40use pallet_evm_coder_substrate::{call, dispatch_to_evm};41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};42use sp_core::H160;43use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};44use up_data_structs::{45	CollectionId, CollectionPropertiesVec, Property, PropertyKey, PropertyKeyPermission,46	PropertyPermission, TokenId,47};4849use crate::{50	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,51	TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,52};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 is_mutable Permission to mutate property.61	/// @param collection_admin Permission to mutate property by collection admin if property is mutable.62	/// @param token_owner 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	fn set_property(95		&mut self,96		caller: caller,97		token_id: uint256,98		key: string,99		value: bytes,100	) -> Result<()> {101		let caller = T::CrossAccountId::from_eth(caller);102		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;103		let key = <Vec<u8>>::from(key)104			.try_into()105			.map_err(|_| "key too long")?;106		let value = value.try_into().map_err(|_| "value too long")?;107108		let nesting_budget = self109			.recorder110			.weight_calls_budget(<StructureWeight<T>>::find_parent());111112		<Pallet<T>>::set_token_property(113			self,114			&caller,115			TokenId(token_id),116			Property { key, value },117			&nesting_budget,118		)119		.map_err(dispatch_to_evm::<T>)120	}121122	/// @notice Delete token property value.123	/// @dev Throws error if `msg.sender` has no permission to edit the property.124	/// @param tokenId ID of the token.125	/// @param key Property key.126	fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {127		let caller = T::CrossAccountId::from_eth(caller);128		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;129		let key = <Vec<u8>>::from(key)130			.try_into()131			.map_err(|_| "key too long")?;132133		let nesting_budget = self134			.recorder135			.weight_calls_budget(<StructureWeight<T>>::find_parent());136137		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)138			.map_err(dispatch_to_evm::<T>)139	}140141	/// @notice Get token property value.142	/// @dev Throws error if key not found143	/// @param tokenId ID of the token.144	/// @param key Property key.145	/// @return Property value bytes146	fn property(&self, token_id: uint256, key: string) -> Result<bytes> {147		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;148		let key = <Vec<u8>>::from(key)149			.try_into()150			.map_err(|_| "key too long")?;151152		let props = <TokenProperties<T>>::get((self.id, token_id));153		let prop = props.get(&key).ok_or("key not found")?;154155		Ok(prop.to_vec())156	}157}158159#[derive(ToLog)]160pub enum ERC721Events {161	/// @dev This event emits when NFTs are created (`from` == 0) and destroyed162	///  (`to` == 0). Exception: during contract creation, any number of RFTs163	///  may be created and assigned without emitting Transfer.164	Transfer {165		#[indexed]166		from: address,167		#[indexed]168		to: address,169		#[indexed]170		token_id: uint256,171	},172	/// @dev Not supported173	Approval {174		#[indexed]175		owner: address,176		#[indexed]177		approved: address,178		#[indexed]179		token_id: uint256,180	},181	/// @dev Not supported182	#[allow(dead_code)]183	ApprovalForAll {184		#[indexed]185		owner: address,186		#[indexed]187		operator: address,188		approved: bool,189	},190}191192#[derive(ToLog)]193pub enum ERC721MintableEvents {194	/// @dev Not supported195	#[allow(dead_code)]196	MintingFinished {},197}198199#[solidity_interface(name = "ERC721Metadata")]200impl<T: Config> RefungibleHandle<T> {201	/// @notice A descriptive name for a collection of RFTs in this contract202	fn name(&self) -> Result<string> {203		Ok(decode_utf16(self.name.iter().copied())204			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))205			.collect::<string>())206	}207208	/// @notice An abbreviated name for RFTs in this contract209	fn symbol(&self) -> Result<string> {210		Ok(string::from_utf8_lossy(&self.token_prefix).into())211	}212213	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.214	///215	/// @dev If the token has a `url` property and it is not empty, it is returned.216	///  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`.217	///  If the collection property `baseURI` is empty or absent, return "" (empty string)218	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix219	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).220	///221	/// @return token's const_metadata222	#[solidity(rename_selector = "tokenURI")]223	fn token_uri(&self, token_id: uint256) -> Result<string> {224		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;225226		if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {227			if !url.is_empty() {228				return Ok(url);229			}230		} else if !is_erc721_metadata_compatible::<T>(self.id) {231			return Err("tokenURI not set".into());232		}233234		if let Some(base_uri) =235			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())236		{237			if !base_uri.is_empty() {238				let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {239					Error::Revert(alloc::format!(240						"Can not convert value \"baseURI\" to string with error \"{}\"",241						e242					))243				})?;244				if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {245					if !suffix.is_empty() {246						return Ok(base_uri + suffix.as_str());247					}248				}249250				return Ok(base_uri + token_id.to_string().as_str());251			}252		}253254		Ok("".into())255	}256}257258/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension259/// @dev See https://eips.ethereum.org/EIPS/eip-721260#[solidity_interface(name = "ERC721Enumerable")]261impl<T: Config> RefungibleHandle<T> {262	/// @notice Enumerate valid RFTs263	/// @param index A counter less than `totalSupply()`264	/// @return The token identifier for the `index`th NFT,265	///  (sort order not specified)266	fn token_by_index(&self, index: uint256) -> Result<uint256> {267		Ok(index)268	}269270	/// Not implemented271	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {272		// TODO: Not implemetable273		Err("not implemented".into())274	}275276	/// @notice Count RFTs tracked by this contract277	/// @return A count of valid RFTs tracked by this contract, where each one of278	///  them has an assigned and queryable owner not equal to the zero address279	fn total_supply(&self) -> Result<uint256> {280		self.consume_store_reads(1)?;281		Ok(<Pallet<T>>::total_supply(self).into())282	}283}284285/// @title ERC-721 Non-Fungible Token Standard286/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md287#[solidity_interface(name = "ERC721", events(ERC721Events))]288impl<T: Config> RefungibleHandle<T> {289	/// @notice Count all RFTs assigned to an owner290	/// @dev RFTs assigned to the zero address are considered invalid, and this291	///  function throws for queries about the zero address.292	/// @param owner An address for whom to query the balance293	/// @return The number of RFTs owned by `owner`, possibly zero294	fn balance_of(&self, owner: address) -> Result<uint256> {295		self.consume_store_reads(1)?;296		let owner = T::CrossAccountId::from_eth(owner);297		let balance = <AccountBalance<T>>::get((self.id, owner));298		Ok(balance.into())299	}300301	fn owner_of(&self, token_id: uint256) -> Result<address> {302		self.consume_store_reads(2)?;303		let token = token_id.try_into()?;304		let owner = <Pallet<T>>::token_owner(self.id, token);305		Ok(owner306			.map(|address| *address.as_eth())307			.unwrap_or_else(|| H160::default()))308	}309310	/// @dev Not implemented311	fn safe_transfer_from_with_data(312		&mut self,313		_from: address,314		_to: address,315		_token_id: uint256,316		_data: bytes,317		_value: value,318	) -> Result<void> {319		// TODO: Not implemetable320		Err("not implemented".into())321	}322323	/// @dev Not implemented324	fn safe_transfer_from(325		&mut self,326		_from: address,327		_to: address,328		_token_id: uint256,329		_value: value,330	) -> Result<void> {331		// TODO: Not implemetable332		Err("not implemented".into())333	}334335	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE336	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE337	///  THEY MAY BE PERMANENTLY LOST338	/// @dev Throws unless `msg.sender` is the current owner or an authorized339	///  operator for this RFT. Throws if `from` is not the current owner. Throws340	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.341	///  Throws if RFT pieces have multiple owners.342	/// @param from The current owner of the NFT343	/// @param to The new owner344	/// @param tokenId The NFT to transfer345	/// @param _value Not used for an NFT346	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]347	fn transfer_from(348		&mut self,349		caller: caller,350		from: address,351		to: address,352		token_id: uint256,353		_value: value,354	) -> Result<void> {355		let caller = T::CrossAccountId::from_eth(caller);356		let from = T::CrossAccountId::from_eth(from);357		let to = T::CrossAccountId::from_eth(to);358		let token = token_id.try_into()?;359		let budget = self360			.recorder361			.weight_calls_budget(<StructureWeight<T>>::find_parent());362363		let balance = balance(&self, token, &from)?;364		ensure_single_owner(&self, token, balance)?;365366		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)367			.map_err(dispatch_to_evm::<T>)?;368369		<PalletEvm<T>>::deposit_log(370			ERC721Events::Transfer {371				from: *from.as_eth(),372				to: *to.as_eth(),373				token_id: token_id.into(),374			}375			.to_log(collection_id_to_address(self.id)),376		);377		Ok(())378	}379380	/// @dev Not implemented381	fn approve(382		&mut self,383		_caller: caller,384		_approved: address,385		_token_id: uint256,386		_value: value,387	) -> Result<void> {388		Err("not implemented".into())389	}390391	/// @dev Not implemented392	fn set_approval_for_all(393		&mut self,394		_caller: caller,395		_operator: address,396		_approved: bool,397	) -> Result<void> {398		// TODO: Not implemetable399		Err("not implemented".into())400	}401402	/// @dev Not implemented403	fn get_approved(&self, _token_id: uint256) -> Result<address> {404		// TODO: Not implemetable405		Err("not implemented".into())406	}407408	/// @dev Not implemented409	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {410		// TODO: Not implemetable411		Err("not implemented".into())412	}413}414415/// Returns amount of pieces of `token` that `owner` have416fn balance<T: Config>(417	collection: &RefungibleHandle<T>,418	token: TokenId,419	owner: &T::CrossAccountId,420) -> Result<u128> {421	collection.consume_store_reads(1)?;422	let balance = <Balance<T>>::get((collection.id, token, &owner));423	Ok(balance)424}425426/// Throws if `owner_balance` is lower than total amount of `token` pieces427fn ensure_single_owner<T: Config>(428	collection: &RefungibleHandle<T>,429	token: TokenId,430	owner_balance: u128,431) -> Result<()> {432	collection.consume_store_reads(1)?;433	let total_supply = <TotalSupply<T>>::get((collection.id, token));434	if total_supply != owner_balance {435		return Err("token has multiple owners".into());436	}437	Ok(())438}439440/// @title ERC721 Token that can be irreversibly burned (destroyed).441#[solidity_interface(name = "ERC721Burnable")]442impl<T: Config> RefungibleHandle<T> {443	/// @notice Burns a specific ERC721 token.444	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized445	///  operator of the current owner.446	/// @param tokenId The RFT to approve447	#[weight(<SelfWeightOf<T>>::burn_item_fully())]448	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {449		let caller = T::CrossAccountId::from_eth(caller);450		let token = token_id.try_into()?;451452		let balance = balance(&self, token, &caller)?;453		ensure_single_owner(&self, token, balance)?;454455		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;456		Ok(())457	}458}459460/// @title ERC721 minting logic.461#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]462impl<T: Config> RefungibleHandle<T> {463	fn minting_finished(&self) -> Result<bool> {464		Ok(false)465	}466467	/// @notice Function to mint token.468	/// @dev `tokenId` should be obtained with `nextTokenId` method,469	///  unlike standard, you can't specify it manually470	/// @param to The new owner471	/// @param tokenId ID of the minted RFT472	#[weight(<SelfWeightOf<T>>::create_item())]473	fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {474		let caller = T::CrossAccountId::from_eth(caller);475		let to = T::CrossAccountId::from_eth(to);476		let token_id: u32 = token_id.try_into()?;477		let budget = self478			.recorder479			.weight_calls_budget(<StructureWeight<T>>::find_parent());480481		if <TokensMinted<T>>::get(self.id)482			.checked_add(1)483			.ok_or("item id overflow")?484			!= token_id485		{486			return Err("item id should be next".into());487		}488489		let const_data = BoundedVec::default();490		let users = [(to.clone(), 1)]491			.into_iter()492			.collect::<BTreeMap<_, _>>()493			.try_into()494			.unwrap();495		<Pallet<T>>::create_item(496			self,497			&caller,498			CreateItemData::<T> {499				const_data,500				users,501				properties: CollectionPropertiesVec::default(),502			},503			&budget,504		)505		.map_err(dispatch_to_evm::<T>)?;506507		Ok(true)508	}509510	/// @notice Function to mint token with the given tokenUri.511	/// @dev `tokenId` should be obtained with `nextTokenId` method,512	///  unlike standard, you can't specify it manually513	/// @param to The new owner514	/// @param tokenId ID of the minted RFT515	/// @param tokenUri Token URI that would be stored in the RFT properties516	#[solidity(rename_selector = "mintWithTokenURI")]517	#[weight(<SelfWeightOf<T>>::create_item())]518	fn mint_with_token_uri(519		&mut self,520		caller: caller,521		to: address,522		token_id: uint256,523		token_uri: string,524	) -> Result<bool> {525		let key = key::url();526		let permission = get_token_permission::<T>(self.id, &key)?;527		if !permission.collection_admin {528			return Err("Operation is not allowed".into());529		}530531		let caller = T::CrossAccountId::from_eth(caller);532		let to = T::CrossAccountId::from_eth(to);533		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;534		let budget = self535			.recorder536			.weight_calls_budget(<StructureWeight<T>>::find_parent());537538		if <TokensMinted<T>>::get(self.id)539			.checked_add(1)540			.ok_or("item id overflow")?541			!= token_id542		{543			return Err("item id should be next".into());544		}545546		let mut properties = CollectionPropertiesVec::default();547		properties548			.try_push(Property {549				key,550				value: token_uri551					.into_bytes()552					.try_into()553					.map_err(|_| "token uri is too long")?,554			})555			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;556557		let const_data = BoundedVec::default();558		let users = [(to.clone(), 1)]559			.into_iter()560			.collect::<BTreeMap<_, _>>()561			.try_into()562			.unwrap();563		<Pallet<T>>::create_item(564			self,565			&caller,566			CreateItemData::<T> {567				const_data,568				users,569				properties,570			},571			&budget,572		)573		.map_err(dispatch_to_evm::<T>)?;574		Ok(true)575	}576577	/// @dev Not implemented578	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {579		Err("not implementable".into())580	}581}582583fn get_token_property<T: Config>(584	collection: &CollectionHandle<T>,585	token_id: u32,586	key: &up_data_structs::PropertyKey,587) -> Result<string> {588	collection.consume_store_reads(1)?;589	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))590		.map_err(|_| Error::Revert("Token properties not found".into()))?;591	if let Some(property) = properties.get(key) {592		return Ok(string::from_utf8_lossy(property).into());593	}594595	Err("Property tokenURI not found".into())596}597598fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {599	if let Some(shema_name) =600		pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())601	{602		let shema_name = shema_name.into_inner();603		shema_name == property_value::ERC721_METADATA604	} else {605		false606	}607}608609fn get_token_permission<T: Config>(610	collection_id: CollectionId,611	key: &PropertyKey,612) -> Result<PropertyPermission> {613	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)614		.map_err(|_| Error::Revert("No permissions for collection".into()))?;615	let a = token_property_permissions616		.get(key)617		.map(Clone::clone)618		.ok_or_else(|| {619			let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();620			Error::Revert(alloc::format!("No permission for key {}", key))621		})?;622	Ok(a)623}624625/// @title Unique extensions for ERC721.626#[solidity_interface(name = "ERC721UniqueExtensions")]627impl<T: Config> RefungibleHandle<T> {628	/// @notice Transfer ownership of an RFT629	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`630	///  is the zero address. Throws if `tokenId` is not a valid RFT.631	///  Throws if RFT pieces have multiple owners.632	/// @param to The new owner633	/// @param tokenId The RFT to transfer634	/// @param _value Not used for an RFT635	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]636	fn transfer(637		&mut self,638		caller: caller,639		to: address,640		token_id: uint256,641		_value: value,642	) -> Result<void> {643		let caller = T::CrossAccountId::from_eth(caller);644		let to = T::CrossAccountId::from_eth(to);645		let token = token_id.try_into()?;646		let budget = self647			.recorder648			.weight_calls_budget(<StructureWeight<T>>::find_parent());649650		let balance = balance(&self, token, &caller)?;651		ensure_single_owner(&self, token, balance)?;652653		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)654			.map_err(dispatch_to_evm::<T>)?;655		<PalletEvm<T>>::deposit_log(656			ERC721Events::Transfer {657				from: *caller.as_eth(),658				to: *to.as_eth(),659				token_id: token_id.into(),660			}661			.to_log(collection_id_to_address(self.id)),662		);663		Ok(())664	}665666	/// @notice Burns a specific ERC721 token.667	/// @dev Throws unless `msg.sender` is the current owner or an authorized668	///  operator for this RFT. Throws if `from` is not the current owner. Throws669	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.670	///  Throws if RFT pieces have multiple owners.671	/// @param from The current owner of the RFT672	/// @param tokenId The RFT to transfer673	/// @param _value Not used for an RFT674	#[weight(<SelfWeightOf<T>>::burn_from())]675	fn burn_from(676		&mut self,677		caller: caller,678		from: address,679		token_id: uint256,680		_value: value,681	) -> Result<void> {682		let caller = T::CrossAccountId::from_eth(caller);683		let from = T::CrossAccountId::from_eth(from);684		let token = token_id.try_into()?;685		let budget = self686			.recorder687			.weight_calls_budget(<StructureWeight<T>>::find_parent());688689		let balance = balance(&self, token, &caller)?;690		ensure_single_owner(&self, token, balance)?;691692		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)693			.map_err(dispatch_to_evm::<T>)?;694		Ok(())695	}696697	/// @notice Returns next free RFT ID.698	fn next_token_id(&self) -> Result<uint256> {699		self.consume_store_reads(1)?;700		Ok(<TokensMinted<T>>::get(self.id)701			.checked_add(1)702			.ok_or("item id overflow")?703			.into())704	}705706	/// @notice Function to mint multiple tokens.707	/// @dev `tokenIds` should be an array of consecutive numbers and first number708	///  should be obtained with `nextTokenId` method709	/// @param to The new owner710	/// @param tokenIds IDs of the minted RFTs711	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]712	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {713		let caller = T::CrossAccountId::from_eth(caller);714		let to = T::CrossAccountId::from_eth(to);715		let mut expected_index = <TokensMinted<T>>::get(self.id)716			.checked_add(1)717			.ok_or("item id overflow")?;718		let budget = self719			.recorder720			.weight_calls_budget(<StructureWeight<T>>::find_parent());721722		let total_tokens = token_ids.len();723		for id in token_ids.into_iter() {724			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;725			if id != expected_index {726				return Err("item id should be next".into());727			}728			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;729		}730		let const_data = BoundedVec::default();731		let users = [(to.clone(), 1)]732			.into_iter()733			.collect::<BTreeMap<_, _>>()734			.try_into()735			.unwrap();736		let create_item_data = CreateItemData::<T> {737			const_data,738			users,739			properties: CollectionPropertiesVec::default(),740		};741		let data = (0..total_tokens)742			.map(|_| create_item_data.clone())743			.collect();744745		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)746			.map_err(dispatch_to_evm::<T>)?;747		Ok(true)748	}749750	/// @notice Function to mint multiple tokens with the given tokenUris.751	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive752	///  numbers and first number should be obtained with `nextTokenId` method753	/// @param to The new owner754	/// @param tokens array of pairs of token ID and token URI for minted tokens755	#[solidity(rename_selector = "mintBulkWithTokenURI")]756	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]757	fn mint_bulk_with_token_uri(758		&mut self,759		caller: caller,760		to: address,761		tokens: Vec<(uint256, string)>,762	) -> Result<bool> {763		let key = key::url();764		let caller = T::CrossAccountId::from_eth(caller);765		let to = T::CrossAccountId::from_eth(to);766		let mut expected_index = <TokensMinted<T>>::get(self.id)767			.checked_add(1)768			.ok_or("item id overflow")?;769		let budget = self770			.recorder771			.weight_calls_budget(<StructureWeight<T>>::find_parent());772773		let mut data = Vec::with_capacity(tokens.len());774		let const_data = BoundedVec::default();775		let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]776			.into_iter()777			.collect::<BTreeMap<_, _>>()778			.try_into()779			.unwrap();780		for (id, token_uri) in tokens {781			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;782			if id != expected_index {783				return Err("item id should be next".into());784			}785			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;786787			let mut properties = CollectionPropertiesVec::default();788			properties789				.try_push(Property {790					key: key.clone(),791					value: token_uri792						.into_bytes()793						.try_into()794						.map_err(|_| "token uri is too long")?,795				})796				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;797798			let create_item_data = CreateItemData::<T> {799				const_data: const_data.clone(),800				users: users.clone(),801				properties,802			};803			data.push(create_item_data);804		}805806		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)807			.map_err(dispatch_to_evm::<T>)?;808		Ok(true)809	}810}811812#[solidity_interface(813	name = "UniqueRefungible",814	is(815		ERC721,816		ERC721Metadata,817		ERC721Enumerable,818		ERC721UniqueExtensions,819		ERC721Mintable,820		ERC721Burnable,821		via("CollectionHandle<T>", common_mut, Collection),822		TokenProperties,823	)824)]825impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> {}826827// Not a tests, but code generators828generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);829generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);830831impl<T: Config> CommonEvmHandler for RefungibleHandle<T>832where833	T::AccountId: From<[u8; 32]>,834{835	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");836	fn call(837		self,838		handle: &mut impl PrecompileHandle,839	) -> Option<pallet_common::erc::PrecompileResult> {840		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)841	}842}
after · pallets/refungible/src/erc.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26	char::{REPLACEMENT_CHARACTER, decode_utf16},27	convert::TryInto,28};29use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};30use frame_support::{BoundedBTreeMap, BoundedVec};31use pallet_common::{32	CollectionHandle, CollectionPropertyPermissions,33	erc::{34		CommonEvmHandler, CollectionCall,35		static_property::{key, value as property_value},36	},37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{call, dispatch_to_evm};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};41use sp_core::H160;42use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};43use up_data_structs::{44	CollectionId, CollectionPropertiesVec, Property, PropertyKey, PropertyKeyPermission,45	PropertyPermission, TokenId,46};4748use crate::{49	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,50	TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,51};5253pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5455/// @title A contract that allows to set and delete token properties and change token property permissions.56#[solidity_interface(name = "TokenProperties")]57impl<T: Config> RefungibleHandle<T> {58	/// @notice Set permissions for token property.59	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.60	/// @param key Property key.61	/// @param is_mutable Permission to mutate property.62	/// @param collection_admin Permission to mutate property by collection admin if property is mutable.63	/// @param token_owner Permission to mutate property by token owner if property is mutable.64	fn set_token_property_permission(65		&mut self,66		caller: caller,67		key: string,68		is_mutable: bool,69		collection_admin: bool,70		token_owner: bool,71	) -> Result<()> {72		let caller = T::CrossAccountId::from_eth(caller);73		<Pallet<T>>::set_token_property_permissions(74			self,75			&caller,76			vec![PropertyKeyPermission {77				key: <Vec<u8>>::from(key)78					.try_into()79					.map_err(|_| "too long key")?,80				permission: PropertyPermission {81					mutable: is_mutable,82					collection_admin,83					token_owner,84				},85			}],86		)87		.map_err(dispatch_to_evm::<T>)88	}8990	/// @notice Set token property value.91	/// @dev Throws error if `msg.sender` has no permission to edit the property.92	/// @param tokenId ID of the token.93	/// @param key Property key.94	/// @param value Property value.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.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 Delete token property value.124	/// @dev Throws error if `msg.sender` has no permission to edit the property.125	/// @param tokenId ID of the token.126	/// @param key Property key.127	fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {128		let caller = T::CrossAccountId::from_eth(caller);129		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;130		let key = <Vec<u8>>::from(key)131			.try_into()132			.map_err(|_| "key too long")?;133134		let nesting_budget = self135			.recorder136			.weight_calls_budget(<StructureWeight<T>>::find_parent());137138		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)139			.map_err(dispatch_to_evm::<T>)140	}141142	/// @notice Get token property value.143	/// @dev Throws error if key not found144	/// @param tokenId ID of the token.145	/// @param key Property key.146	/// @return Property value bytes147	fn property(&self, token_id: uint256, key: string) -> Result<bytes> {148		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;149		let key = <Vec<u8>>::from(key)150			.try_into()151			.map_err(|_| "key too long")?;152153		let props = <TokenProperties<T>>::get((self.id, token_id));154		let prop = props.get(&key).ok_or("key not found")?;155156		Ok(prop.to_vec())157	}158}159160#[derive(ToLog)]161pub enum ERC721Events {162	/// @dev This event emits when NFTs are created (`from` == 0) and destroyed163	///  (`to` == 0). Exception: during contract creation, any number of RFTs164	///  may be created and assigned without emitting Transfer.165	Transfer {166		#[indexed]167		from: address,168		#[indexed]169		to: address,170		#[indexed]171		token_id: uint256,172	},173	/// @dev Not supported174	Approval {175		#[indexed]176		owner: address,177		#[indexed]178		approved: address,179		#[indexed]180		token_id: uint256,181	},182	/// @dev Not supported183	#[allow(dead_code)]184	ApprovalForAll {185		#[indexed]186		owner: address,187		#[indexed]188		operator: address,189		approved: bool,190	},191}192193#[derive(ToLog)]194pub enum ERC721MintableEvents {195	/// @dev Not supported196	#[allow(dead_code)]197	MintingFinished {},198}199200#[solidity_interface(name = "ERC721Metadata")]201impl<T: Config> RefungibleHandle<T> {202	/// @notice A descriptive name for a collection of RFTs in this contract203	fn name(&self) -> Result<string> {204		Ok(decode_utf16(self.name.iter().copied())205			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))206			.collect::<string>())207	}208209	/// @notice An abbreviated name for RFTs in this contract210	fn symbol(&self) -> Result<string> {211		Ok(string::from_utf8_lossy(&self.token_prefix).into())212	}213214	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.215	///216	/// @dev If the token has a `url` property and it is not empty, it is returned.217	///  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`.218	///  If the collection property `baseURI` is empty or absent, return "" (empty string)219	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix220	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).221	///222	/// @return token's const_metadata223	#[solidity(rename_selector = "tokenURI")]224	fn token_uri(&self, token_id: uint256) -> Result<string> {225		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;226227		if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {228			if !url.is_empty() {229				return Ok(url);230			}231		} else if !is_erc721_metadata_compatible::<T>(self.id) {232			return Err("tokenURI not set".into());233		}234235		if let Some(base_uri) =236			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())237		{238			if !base_uri.is_empty() {239				let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {240					Error::Revert(alloc::format!(241						"Can not convert value \"baseURI\" to string with error \"{}\"",242						e243					))244				})?;245				if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {246					if !suffix.is_empty() {247						return Ok(base_uri + suffix.as_str());248					}249				}250251				return Ok(base_uri + token_id.to_string().as_str());252			}253		}254255		Ok("".into())256	}257}258259/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension260/// @dev See https://eips.ethereum.org/EIPS/eip-721261#[solidity_interface(name = "ERC721Enumerable")]262impl<T: Config> RefungibleHandle<T> {263	/// @notice Enumerate valid RFTs264	/// @param index A counter less than `totalSupply()`265	/// @return The token identifier for the `index`th NFT,266	///  (sort order not specified)267	fn token_by_index(&self, index: uint256) -> Result<uint256> {268		Ok(index)269	}270271	/// Not implemented272	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {273		// TODO: Not implemetable274		Err("not implemented".into())275	}276277	/// @notice Count RFTs tracked by this contract278	/// @return A count of valid RFTs tracked by this contract, where each one of279	///  them has an assigned and queryable owner not equal to the zero address280	fn total_supply(&self) -> Result<uint256> {281		self.consume_store_reads(1)?;282		Ok(<Pallet<T>>::total_supply(self).into())283	}284}285286/// @title ERC-721 Non-Fungible Token Standard287/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md288#[solidity_interface(name = "ERC721", events(ERC721Events))]289impl<T: Config> RefungibleHandle<T> {290	/// @notice Count all RFTs assigned to an owner291	/// @dev RFTs assigned to the zero address are considered invalid, and this292	///  function throws for queries about the zero address.293	/// @param owner An address for whom to query the balance294	/// @return The number of RFTs owned by `owner`, possibly zero295	fn balance_of(&self, owner: address) -> Result<uint256> {296		self.consume_store_reads(1)?;297		let owner = T::CrossAccountId::from_eth(owner);298		let balance = <AccountBalance<T>>::get((self.id, owner));299		Ok(balance.into())300	}301302	/// @notice Find the owner of an RFT303	/// @dev RFTs assigned to zero address are considered invalid, and queries304	///  about them do throw.305	///  Returns special 0xffffffffffffffffffffffffffffffffffffffff address for306	///  the tokens that are partially owned.307	/// @param tokenId The identifier for an RFT308	/// @return The address of the owner of the RFT309	fn owner_of(&self, token_id: uint256) -> Result<address> {310		self.consume_store_reads(2)?;311		let token = token_id.try_into()?;312		let owner = <Pallet<T>>::token_owner(self.id, token);313		Ok(owner314			.map(|address| *address.as_eth())315			.unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))316	}317318	/// @dev Not implemented319	fn safe_transfer_from_with_data(320		&mut self,321		_from: address,322		_to: address,323		_token_id: uint256,324		_data: bytes,325		_value: value,326	) -> Result<void> {327		// TODO: Not implemetable328		Err("not implemented".into())329	}330331	/// @dev Not implemented332	fn safe_transfer_from(333		&mut self,334		_from: address,335		_to: address,336		_token_id: uint256,337		_value: value,338	) -> Result<void> {339		// TODO: Not implemetable340		Err("not implemented".into())341	}342343	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE344	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE345	///  THEY MAY BE PERMANENTLY LOST346	/// @dev Throws unless `msg.sender` is the current owner or an authorized347	///  operator for this RFT. Throws if `from` is not the current owner. Throws348	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.349	///  Throws if RFT pieces have multiple owners.350	/// @param from The current owner of the NFT351	/// @param to The new owner352	/// @param tokenId The NFT to transfer353	/// @param _value Not used for an NFT354	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]355	fn transfer_from(356		&mut self,357		caller: caller,358		from: address,359		to: address,360		token_id: uint256,361		_value: value,362	) -> Result<void> {363		let caller = T::CrossAccountId::from_eth(caller);364		let from = T::CrossAccountId::from_eth(from);365		let to = T::CrossAccountId::from_eth(to);366		let token = token_id.try_into()?;367		let budget = self368			.recorder369			.weight_calls_budget(<StructureWeight<T>>::find_parent());370371		let balance = balance(&self, token, &from)?;372		ensure_single_owner(&self, token, balance)?;373374		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)375			.map_err(dispatch_to_evm::<T>)?;376377		Ok(())378	}379380	/// @dev Not implemented381	fn approve(382		&mut self,383		_caller: caller,384		_approved: address,385		_token_id: uint256,386		_value: value,387	) -> Result<void> {388		Err("not implemented".into())389	}390391	/// @dev Not implemented392	fn set_approval_for_all(393		&mut self,394		_caller: caller,395		_operator: address,396		_approved: bool,397	) -> Result<void> {398		// TODO: Not implemetable399		Err("not implemented".into())400	}401402	/// @dev Not implemented403	fn get_approved(&self, _token_id: uint256) -> Result<address> {404		// TODO: Not implemetable405		Err("not implemented".into())406	}407408	/// @dev Not implemented409	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {410		// TODO: Not implemetable411		Err("not implemented".into())412	}413}414415/// Returns amount of pieces of `token` that `owner` have416fn balance<T: Config>(417	collection: &RefungibleHandle<T>,418	token: TokenId,419	owner: &T::CrossAccountId,420) -> Result<u128> {421	collection.consume_store_reads(1)?;422	let balance = <Balance<T>>::get((collection.id, token, &owner));423	Ok(balance)424}425426/// Throws if `owner_balance` is lower than total amount of `token` pieces427fn ensure_single_owner<T: Config>(428	collection: &RefungibleHandle<T>,429	token: TokenId,430	owner_balance: u128,431) -> Result<()> {432	collection.consume_store_reads(1)?;433	let total_supply = <TotalSupply<T>>::get((collection.id, token));434	if total_supply != owner_balance {435		return Err("token has multiple owners".into());436	}437	Ok(())438}439440/// @title ERC721 Token that can be irreversibly burned (destroyed).441#[solidity_interface(name = "ERC721Burnable")]442impl<T: Config> RefungibleHandle<T> {443	/// @notice Burns a specific ERC721 token.444	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized445	///  operator of the current owner.446	/// @param tokenId The RFT to approve447	#[weight(<SelfWeightOf<T>>::burn_item_fully())]448	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {449		let caller = T::CrossAccountId::from_eth(caller);450		let token = token_id.try_into()?;451452		let balance = balance(&self, token, &caller)?;453		ensure_single_owner(&self, token, balance)?;454455		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;456		Ok(())457	}458}459460/// @title ERC721 minting logic.461#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]462impl<T: Config> RefungibleHandle<T> {463	fn minting_finished(&self) -> Result<bool> {464		Ok(false)465	}466467	/// @notice Function to mint token.468	/// @dev `tokenId` should be obtained with `nextTokenId` method,469	///  unlike standard, you can't specify it manually470	/// @param to The new owner471	/// @param tokenId ID of the minted RFT472	#[weight(<SelfWeightOf<T>>::create_item())]473	fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {474		let caller = T::CrossAccountId::from_eth(caller);475		let to = T::CrossAccountId::from_eth(to);476		let token_id: u32 = token_id.try_into()?;477		let budget = self478			.recorder479			.weight_calls_budget(<StructureWeight<T>>::find_parent());480481		if <TokensMinted<T>>::get(self.id)482			.checked_add(1)483			.ok_or("item id overflow")?484			!= token_id485		{486			return Err("item id should be next".into());487		}488489		let const_data = BoundedVec::default();490		let users = [(to.clone(), 1)]491			.into_iter()492			.collect::<BTreeMap<_, _>>()493			.try_into()494			.unwrap();495		<Pallet<T>>::create_item(496			self,497			&caller,498			CreateItemData::<T> {499				const_data,500				users,501				properties: CollectionPropertiesVec::default(),502			},503			&budget,504		)505		.map_err(dispatch_to_evm::<T>)?;506507		Ok(true)508	}509510	/// @notice Function to mint token with the given tokenUri.511	/// @dev `tokenId` should be obtained with `nextTokenId` method,512	///  unlike standard, you can't specify it manually513	/// @param to The new owner514	/// @param tokenId ID of the minted RFT515	/// @param tokenUri Token URI that would be stored in the RFT properties516	#[solidity(rename_selector = "mintWithTokenURI")]517	#[weight(<SelfWeightOf<T>>::create_item())]518	fn mint_with_token_uri(519		&mut self,520		caller: caller,521		to: address,522		token_id: uint256,523		token_uri: string,524	) -> Result<bool> {525		let key = key::url();526		let permission = get_token_permission::<T>(self.id, &key)?;527		if !permission.collection_admin {528			return Err("Operation is not allowed".into());529		}530531		let caller = T::CrossAccountId::from_eth(caller);532		let to = T::CrossAccountId::from_eth(to);533		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;534		let budget = self535			.recorder536			.weight_calls_budget(<StructureWeight<T>>::find_parent());537538		if <TokensMinted<T>>::get(self.id)539			.checked_add(1)540			.ok_or("item id overflow")?541			!= token_id542		{543			return Err("item id should be next".into());544		}545546		let mut properties = CollectionPropertiesVec::default();547		properties548			.try_push(Property {549				key,550				value: token_uri551					.into_bytes()552					.try_into()553					.map_err(|_| "token uri is too long")?,554			})555			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;556557		let const_data = BoundedVec::default();558		let users = [(to.clone(), 1)]559			.into_iter()560			.collect::<BTreeMap<_, _>>()561			.try_into()562			.unwrap();563		<Pallet<T>>::create_item(564			self,565			&caller,566			CreateItemData::<T> {567				const_data,568				users,569				properties,570			},571			&budget,572		)573		.map_err(dispatch_to_evm::<T>)?;574		Ok(true)575	}576577	/// @dev Not implemented578	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {579		Err("not implementable".into())580	}581}582583fn get_token_property<T: Config>(584	collection: &CollectionHandle<T>,585	token_id: u32,586	key: &up_data_structs::PropertyKey,587) -> Result<string> {588	collection.consume_store_reads(1)?;589	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))590		.map_err(|_| Error::Revert("Token properties not found".into()))?;591	if let Some(property) = properties.get(key) {592		return Ok(string::from_utf8_lossy(property).into());593	}594595	Err("Property tokenURI not found".into())596}597598fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {599	if let Some(shema_name) =600		pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())601	{602		let shema_name = shema_name.into_inner();603		shema_name == property_value::ERC721_METADATA604	} else {605		false606	}607}608609fn get_token_permission<T: Config>(610	collection_id: CollectionId,611	key: &PropertyKey,612) -> Result<PropertyPermission> {613	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)614		.map_err(|_| Error::Revert("No permissions for collection".into()))?;615	let a = token_property_permissions616		.get(key)617		.map(Clone::clone)618		.ok_or_else(|| {619			let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();620			Error::Revert(alloc::format!("No permission for key {}", key))621		})?;622	Ok(a)623}624625/// @title Unique extensions for ERC721.626#[solidity_interface(name = "ERC721UniqueExtensions")]627impl<T: Config> RefungibleHandle<T> {628	/// @notice Transfer ownership of an RFT629	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`630	///  is the zero address. Throws if `tokenId` is not a valid RFT.631	///  Throws if RFT pieces have multiple owners.632	/// @param to The new owner633	/// @param tokenId The RFT to transfer634	/// @param _value Not used for an RFT635	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]636	fn transfer(637		&mut self,638		caller: caller,639		to: address,640		token_id: uint256,641		_value: value,642	) -> Result<void> {643		let caller = T::CrossAccountId::from_eth(caller);644		let to = T::CrossAccountId::from_eth(to);645		let token = token_id.try_into()?;646		let budget = self647			.recorder648			.weight_calls_budget(<StructureWeight<T>>::find_parent());649650		let balance = balance(&self, token, &caller)?;651		ensure_single_owner(&self, token, balance)?;652653		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)654			.map_err(dispatch_to_evm::<T>)?;655		Ok(())656	}657658	/// @notice Burns a specific ERC721 token.659	/// @dev Throws unless `msg.sender` is the current owner or an authorized660	///  operator for this RFT. Throws if `from` is not the current owner. Throws661	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.662	///  Throws if RFT pieces have multiple owners.663	/// @param from The current owner of the RFT664	/// @param tokenId The RFT to transfer665	/// @param _value Not used for an RFT666	#[weight(<SelfWeightOf<T>>::burn_from())]667	fn burn_from(668		&mut self,669		caller: caller,670		from: address,671		token_id: uint256,672		_value: value,673	) -> Result<void> {674		let caller = T::CrossAccountId::from_eth(caller);675		let from = T::CrossAccountId::from_eth(from);676		let token = token_id.try_into()?;677		let budget = self678			.recorder679			.weight_calls_budget(<StructureWeight<T>>::find_parent());680681		let balance = balance(&self, token, &caller)?;682		ensure_single_owner(&self, token, balance)?;683684		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)685			.map_err(dispatch_to_evm::<T>)?;686		Ok(())687	}688689	/// @notice Returns next free RFT ID.690	fn next_token_id(&self) -> Result<uint256> {691		self.consume_store_reads(1)?;692		Ok(<TokensMinted<T>>::get(self.id)693			.checked_add(1)694			.ok_or("item id overflow")?695			.into())696	}697698	/// @notice Function to mint multiple tokens.699	/// @dev `tokenIds` should be an array of consecutive numbers and first number700	///  should be obtained with `nextTokenId` method701	/// @param to The new owner702	/// @param tokenIds IDs of the minted RFTs703	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]704	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {705		let caller = T::CrossAccountId::from_eth(caller);706		let to = T::CrossAccountId::from_eth(to);707		let mut expected_index = <TokensMinted<T>>::get(self.id)708			.checked_add(1)709			.ok_or("item id overflow")?;710		let budget = self711			.recorder712			.weight_calls_budget(<StructureWeight<T>>::find_parent());713714		let total_tokens = token_ids.len();715		for id in token_ids.into_iter() {716			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;717			if id != expected_index {718				return Err("item id should be next".into());719			}720			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;721		}722		let const_data = BoundedVec::default();723		let users = [(to.clone(), 1)]724			.into_iter()725			.collect::<BTreeMap<_, _>>()726			.try_into()727			.unwrap();728		let create_item_data = CreateItemData::<T> {729			const_data,730			users,731			properties: CollectionPropertiesVec::default(),732		};733		let data = (0..total_tokens)734			.map(|_| create_item_data.clone())735			.collect();736737		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)738			.map_err(dispatch_to_evm::<T>)?;739		Ok(true)740	}741742	/// @notice Function to mint multiple tokens with the given tokenUris.743	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive744	///  numbers and first number should be obtained with `nextTokenId` method745	/// @param to The new owner746	/// @param tokens array of pairs of token ID and token URI for minted tokens747	#[solidity(rename_selector = "mintBulkWithTokenURI")]748	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]749	fn mint_bulk_with_token_uri(750		&mut self,751		caller: caller,752		to: address,753		tokens: Vec<(uint256, string)>,754	) -> Result<bool> {755		let key = key::url();756		let caller = T::CrossAccountId::from_eth(caller);757		let to = T::CrossAccountId::from_eth(to);758		let mut expected_index = <TokensMinted<T>>::get(self.id)759			.checked_add(1)760			.ok_or("item id overflow")?;761		let budget = self762			.recorder763			.weight_calls_budget(<StructureWeight<T>>::find_parent());764765		let mut data = Vec::with_capacity(tokens.len());766		let const_data = BoundedVec::default();767		let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]768			.into_iter()769			.collect::<BTreeMap<_, _>>()770			.try_into()771			.unwrap();772		for (id, token_uri) in tokens {773			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;774			if id != expected_index {775				return Err("item id should be next".into());776			}777			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;778779			let mut properties = CollectionPropertiesVec::default();780			properties781				.try_push(Property {782					key: key.clone(),783					value: token_uri784						.into_bytes()785						.try_into()786						.map_err(|_| "token uri is too long")?,787				})788				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;789790			let create_item_data = CreateItemData::<T> {791				const_data: const_data.clone(),792				users: users.clone(),793				properties,794			};795			data.push(create_item_data);796		}797798		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)799			.map_err(dispatch_to_evm::<T>)?;800		Ok(true)801	}802}803804#[solidity_interface(805	name = "UniqueRefungible",806	is(807		ERC721,808		ERC721Metadata,809		ERC721Enumerable,810		ERC721UniqueExtensions,811		ERC721Mintable,812		ERC721Burnable,813		via("CollectionHandle<T>", common_mut, Collection),814		TokenProperties,815	)816)]817impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> {}818819// Not a tests, but code generators820generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);821generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);822823impl<T: Config> CommonEvmHandler for RefungibleHandle<T>824where825	T::AccountId: From<[u8; 32]>,826{827	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");828	fn call(829		self,830		handle: &mut impl PrecompileHandle,831	) -> Option<pallet_common::erc::PrecompileResult> {832		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)833	}834}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -707,12 +707,13 @@
 		}
 		<PalletCommon<T>>::ensure_correct_receiver(to)?;
 
-		let balance_from = <Balance<T>>::get((collection.id, token, from))
+		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));
+		let updated_balance_from = initial_balance_from
 			.checked_sub(amount)
 			.ok_or(<CommonError<T>>::TokenValueTooLow)?;
 		let mut create_target = false;
 		let from_to_differ = from != to;
-		let balance_to = if from != to {
+		let updated_balance_to = if from != to {
 			let old_balance = <Balance<T>>::get((collection.id, token, to));
 			if old_balance == 0 {
 				create_target = true;
@@ -726,7 +727,7 @@
 			None
 		};
 
-		let account_balance_from = if balance_from == 0 {
+		let account_balance_from = if updated_balance_from == 0 {
 			Some(
 				<AccountBalance<T>>::get((collection.id, from))
 					.checked_sub(1)
@@ -762,15 +763,15 @@
 			nesting_budget,
 		)?;
 
-		if let Some(balance_to) = balance_to {
+		if let Some(updated_balance_to) = updated_balance_to {
 			// from != to
-			if balance_from == 0 {
+			if updated_balance_from == 0 {
 				<Balance<T>>::remove((collection.id, token, from));
 				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);
 			} else {
-				<Balance<T>>::insert((collection.id, token, from), balance_from);
+				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);
 			}
-			<Balance<T>>::insert((collection.id, token, to), balance_to);
+			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);
 			if let Some(account_balance_from) = account_balance_from {
 				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);
 				<Owned<T>>::remove((collection.id, from, token));
@@ -800,6 +801,46 @@
 			to.clone(),
 			amount,
 		));
+
+		let total_supply = <TotalSupply<T>>::get((collection.id, token));
+
+		if amount == total_supply {
+			// if token was fully owned by `from` and will be fully owned by `to` after transfer
+			<PalletEvm<T>>::deposit_log(
+				ERC721Events::Transfer {
+					from: *from.as_eth(),
+					to: *to.as_eth(),
+					token_id: token.into(),
+				}
+				.to_log(collection_id_to_address(collection.id)),
+			);
+		} else if let Some(updated_balance_to) = updated_balance_to {
+			// if `from` not equals `to`. This condition is needed to avoid sending event
+			// when `from` fully owns token and sends part of token pieces to itself.
+			if initial_balance_from == total_supply {
+				// if token was fully owned by `from` and will be only partially owned by `to`
+				// and `from` after transfer
+				<PalletEvm<T>>::deposit_log(
+					ERC721Events::Transfer {
+						from: *from.as_eth(),
+						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
+						token_id: token.into(),
+					}
+					.to_log(collection_id_to_address(collection.id)),
+				);
+			} else if updated_balance_to == total_supply {
+				// if token was partially owned by `from` and will be fully owned by `to` after transfer
+				<PalletEvm<T>>::deposit_log(
+					ERC721Events::Transfer {
+						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
+						to: *to.as_eth(),
+						token_id: token.into(),
+					}
+					.to_log(collection_id_to_address(collection.id)),
+				);
+			}
+		}
+
 		Ok(())
 	}
 
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -14,7 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {createCollectionExpectSuccess, UNIQUE} from '../util/helpers';
+import {createCollectionExpectSuccess, transfer, UNIQUE} from '../util/helpers';
 import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, tokenIdToAddress} from './util/helpers';
 import reFungibleAbi from './reFungibleAbi.json';
 import reFungibleTokenAbi from './reFungibleTokenAbi.json';
@@ -96,6 +96,28 @@
 
     expect(owner).to.equal(receiver);
   });
+
+  itWeb3('ownerOf for partial ownership', async ({api, web3, privateKeyWrapper}) => {
+    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const receiver = createEthAccount(web3);
+    const helper = evmCollectionHelpers(web3, caller);
+    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+    const tokenId = await contract.methods.nextTokenId().call();
+    await contract.methods.mint(caller, tokenId).send();
+
+    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
+    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+
+    await tokenContract.methods.repartition(2).send();
+    await tokenContract.methods.transfer(receiver, 1).send();
+
+    const owner = await contract.methods.ownerOf(tokenId).call();
+
+    expect(owner).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
+  });
 });
 
 describe('Refungible: Plain calls', () => {
@@ -293,6 +315,74 @@
       expect(+balance).to.equal(1);
     }
   });
+
+  itWeb3('transfer event on transfer from partial ownership to full ownership', async ({api, web3, privateKeyWrapper}) => {
+    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const receiver = createEthAccount(web3);
+    const helper = evmCollectionHelpers(web3, caller);
+    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+    const tokenId = await contract.methods.nextTokenId().call();
+    await contract.methods.mint(caller, tokenId).send();
+
+    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
+    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+
+    await tokenContract.methods.repartition(2).send();
+    await tokenContract.methods.transfer(receiver, 1).send();
+
+    let transfer;
+    contract.events.Transfer({}, function(_error: any, event: any){ transfer = event;});
+    await tokenContract.methods.transfer(receiver, 1).send();
+    const events = normalizeEvents([transfer]);
+    expect(events).to.deep.equal([
+      {
+        address: collectionIdAddress,
+        event: 'Transfer',
+        args: {
+          from: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
+          to: receiver,
+          tokenId: tokenId.toString(),
+        },
+      },
+    ]);
+  });
+
+  itWeb3('transfer event on transfer from full ownership to partial ownership', async ({api, web3, privateKeyWrapper}) => {
+    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const receiver = createEthAccount(web3);
+    const helper = evmCollectionHelpers(web3, caller);
+    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+    const tokenId = await contract.methods.nextTokenId().call();
+    await contract.methods.mint(caller, tokenId).send();
+
+    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
+    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+
+    await tokenContract.methods.repartition(2).send();
+    
+    let transfer;
+    contract.events.Transfer({}, function(_error: any, event: any){ transfer = event;});
+    await tokenContract.methods.transfer(receiver, 1).send();
+
+    const events = normalizeEvents([transfer]);
+    expect(events).to.deep.equal([
+      {
+        address: collectionIdAddress,
+        event: 'Transfer',
+        args: {
+          from: caller,
+          to: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
+          tokenId: tokenId.toString(),
+        },
+      },
+    ]);
+  });
 });
 
 describe('RFT: Fees', () => {