git.delta.rocks / unique-network / refs/commits / 448629b28a12

difftreelog

Merge pull request #986 from UniqueNetwork/feature/add_mint_bulk_cross

Yaroslav Bolyukin2023-09-25parents: #6486f2a #752e2b0.patch.diff
in: master
Add mintBulkCross to NFT and RFT collections

20 files changed

modifiednode/cli/src/command.rsdiffbeforeafterboth
--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -425,7 +425,7 @@
 				.map(|cfg| &cfg.registry);
 			let task_manager =
 				sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry)
-					.map_err(|e| format!("Error: {:?}", e))?;
+					.map_err(|e| format!("Error: {e:?}"))?;
 			let info_provider = Some(timestamp_with_aura_info(12000));
 
 			runner.async_run(|config| -> Result<(Pin<Box<dyn Future<Output = _>>>, _)> {
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -119,7 +119,7 @@
 		} else if self.sub == Default::default() {
 			Ok(Some(T::CrossAccountId::from_eth(self.eth)))
 		} else {
-			Err(format!("All fields of cross account is non zeroed {:?}", self).into())
+			Err(format!("All fields of cross account is non zeroed {self:?}").into())
 		}
 	}
 
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
before · pallets/nonfungible/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//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26	char::{REPLACEMENT_CHARACTER, decode_utf16},27	convert::TryInto,28};29use evm_coder::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};30use frame_support::BoundedVec;31use up_data_structs::{32	TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,33	CollectionPropertiesVec,34};35use pallet_evm_coder_substrate::{36	dispatch_to_evm, frontier_contract,37	execution::{Result, PreDispatch, Error},38};39use sp_std::{vec::Vec, vec};40use pallet_common::{41	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,42	erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},43	eth::{self, TokenUri},44	CommonWeightInfo,45};46use pallet_evm::{account::CrossAccountId, PrecompileHandle};47use pallet_evm_coder_substrate::call;48use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};49use sp_core::{U256, Get};5051use crate::{52	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,53	TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,54};5556/// Nft events.57#[derive(ToLog)]58pub enum ERC721TokenEvent {59	/// The token has been changed.60	TokenChanged {61		/// Token ID.62		#[indexed]63		token_id: U256,64	},65}6667frontier_contract! {68	macro_rules! NonfungibleHandle_result {...}69	impl<T: Config> Contract for NonfungibleHandle<T> {...}70}7172/// @title A contract that allows to set and delete token properties and change token property permissions.73#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]74impl<T: Config> NonfungibleHandle<T> {75	/// @notice Set permissions for token property.76	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.77	/// @param key Property key.78	/// @param isMutable Permission to mutate property.79	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.80	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.81	#[solidity(hide)]82	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]83	fn set_token_property_permission(84		&mut self,85		caller: Caller,86		key: String,87		is_mutable: bool,88		collection_admin: bool,89		token_owner: bool,90	) -> Result<()> {91		let caller = T::CrossAccountId::from_eth(caller);92		<Pallet<T>>::set_token_property_permissions(93			self,94			&caller,95			vec![PropertyKeyPermission {96				key: <Vec<u8>>::from(key)97					.try_into()98					.map_err(|_| "too long key")?,99				permission: PropertyPermission {100					mutable: is_mutable,101					collection_admin,102					token_owner,103				},104			}],105		)106		.map_err(dispatch_to_evm::<T>)107	}108109	/// @notice Set permissions for token property.110	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.111	/// @param permissions Permissions for keys.112	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]113	fn set_token_property_permissions(114		&mut self,115		caller: Caller,116		permissions: Vec<eth::TokenPropertyPermission>,117	) -> Result<()> {118		let caller = T::CrossAccountId::from_eth(caller);119		let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;120121		<Pallet<T>>::set_token_property_permissions(self, &caller, perms)122			.map_err(dispatch_to_evm::<T>)123	}124125	/// @notice Get permissions for token properties.126	fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {127		let perms = <Pallet<T>>::token_property_permission(self.id);128		Ok(perms129			.into_iter()130			.map(eth::TokenPropertyPermission::from)131			.collect())132	}133134	/// @notice Set token property value.135	/// @dev Throws error if `msg.sender` has no permission to edit the property.136	/// @param tokenId ID of the token.137	/// @param key Property key.138	/// @param value Property value.139	#[solidity(hide)]140	#[weight(<SelfWeightOf<T>>::set_token_properties(1))]141	fn set_property(142		&mut self,143		caller: Caller,144		token_id: U256,145		key: String,146		value: Bytes,147	) -> Result<()> {148		let caller = T::CrossAccountId::from_eth(caller);149		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;150		let key = <Vec<u8>>::from(key)151			.try_into()152			.map_err(|_| "key too long")?;153		let value = value.0.try_into().map_err(|_| "value too long")?;154155		let nesting_budget = self156			.recorder157			.weight_calls_budget(<StructureWeight<T>>::find_parent());158159		<Pallet<T>>::set_token_property(160			self,161			&caller,162			TokenId(token_id),163			Property { key, value },164			&nesting_budget,165		)166		.map_err(dispatch_to_evm::<T>)167	}168169	/// @notice Set token properties value.170	/// @dev Throws error if `msg.sender` has no permission to edit the property.171	/// @param tokenId ID of the token.172	/// @param properties settable properties173	#[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]174	fn set_properties(175		&mut self,176		caller: Caller,177		token_id: U256,178		properties: Vec<eth::Property>,179	) -> Result<()> {180		let caller = T::CrossAccountId::from_eth(caller);181		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;182183		let nesting_budget = self184			.recorder185			.weight_calls_budget(<StructureWeight<T>>::find_parent());186187		let properties = properties188			.into_iter()189			.map(eth::Property::try_into)190			.collect::<Result<Vec<_>>>()?;191192		<Pallet<T>>::set_token_properties(193			self,194			&caller,195			TokenId(token_id),196			properties.into_iter(),197			pallet_common::SetPropertyMode::ExistingToken,198			&nesting_budget,199		)200		.map_err(dispatch_to_evm::<T>)201	}202203	/// @notice Delete token property value.204	/// @dev Throws error if `msg.sender` has no permission to edit the property.205	/// @param tokenId ID of the token.206	/// @param key Property key.207	#[solidity(hide)]208	#[weight(<SelfWeightOf<T>>::delete_token_properties(1))]209	fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {210		let caller = T::CrossAccountId::from_eth(caller);211		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;212		let key = <Vec<u8>>::from(key)213			.try_into()214			.map_err(|_| "key too long")?;215216		let nesting_budget = self217			.recorder218			.weight_calls_budget(<StructureWeight<T>>::find_parent());219220		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)221			.map_err(dispatch_to_evm::<T>)222	}223224	/// @notice Delete token properties value.225	/// @dev Throws error if `msg.sender` has no permission to edit the property.226	/// @param tokenId ID of the token.227	/// @param keys Properties key.228	#[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]229	fn delete_properties(230		&mut self,231		token_id: U256,232		caller: Caller,233		keys: Vec<String>,234	) -> Result<()> {235		let caller = T::CrossAccountId::from_eth(caller);236		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;237		let keys = keys238			.into_iter()239			.map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))240			.collect::<Result<Vec<_>>>()?;241242		let nesting_budget = self243			.recorder244			.weight_calls_budget(<StructureWeight<T>>::find_parent());245246		<Pallet<T>>::delete_token_properties(247			self,248			&caller,249			TokenId(token_id),250			keys.into_iter(),251			&nesting_budget,252		)253		.map_err(dispatch_to_evm::<T>)254	}255256	/// @notice Get token property value.257	/// @dev Throws error if key not found258	/// @param tokenId ID of the token.259	/// @param key Property key.260	/// @return Property value bytes261	fn property(&self, token_id: U256, key: String) -> Result<Bytes> {262		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;263		let key = <Vec<u8>>::from(key)264			.try_into()265			.map_err(|_| "key too long")?;266267		let props = <TokenProperties<T>>::get((self.id, token_id));268		let prop = props.get(&key).ok_or("key not found")?;269270		Ok(prop.to_vec().into())271	}272}273274#[derive(ToLog)]275pub enum ERC721Events {276	/// @dev This emits when ownership of any NFT changes by any mechanism.277	///  This event emits when NFTs are created (`from` == 0) and destroyed278	///  (`to` == 0). Exception: during contract creation, any number of NFTs279	///  may be created and assigned without emitting Transfer. At the time of280	///  any transfer, the approved address for that NFT (if any) is reset to none.281	Transfer {282		#[indexed]283		from: Address,284		#[indexed]285		to: Address,286		#[indexed]287		token_id: U256,288	},289	/// @dev This emits when the approved address for an NFT is changed or290	///  reaffirmed. The zero address indicates there is no approved address.291	///  When a Transfer event emits, this also indicates that the approved292	///  address for that NFT (if any) is reset to none.293	Approval {294		#[indexed]295		owner: Address,296		#[indexed]297		approved: Address,298		#[indexed]299		token_id: U256,300	},301	/// @dev This emits when an operator is enabled or disabled for an owner.302	///  The operator can manage all NFTs of the owner.303	#[allow(dead_code)]304	ApprovalForAll {305		#[indexed]306		owner: Address,307		#[indexed]308		operator: Address,309		approved: bool,310	},311}312313/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension314/// @dev See https://eips.ethereum.org/EIPS/eip-721315#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f, enum(derive(PreDispatch)), enum_attr(weight))]316impl<T: Config> NonfungibleHandle<T>317where318	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,319{320	/// @notice A descriptive name for a collection of NFTs in this contract321	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`322	#[solidity(hide, rename_selector = "name")]323	fn name_proxy(&self) -> String {324		self.name()325	}326327	/// @notice An abbreviated name for NFTs in this contract328	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`329	#[solidity(hide, rename_selector = "symbol")]330	fn symbol_proxy(&self) -> String {331		self.symbol()332	}333334	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.335	///336	/// @dev If the token has a `url` property and it is not empty, it is returned.337	///  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`.338	///  If the collection property `baseURI` is empty or absent, return "" (empty string)339	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix340	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).341	///342	/// @return token's const_metadata343	#[solidity(rename_selector = "tokenURI")]344	fn token_uri(&self, token_id: U256) -> Result<String> {345		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;346347		match get_token_property(self, token_id_u32, &key::url()).as_deref() {348			Err(_) | Ok("") => (),349			Ok(url) => {350				return Ok(url.into());351			}352		};353354		let base_uri =355			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())356				.map(BoundedVec::into_inner)357				.map(String::from_utf8)358				.transpose()359				.map_err(|e| {360					Error::Revert(alloc::format!(361						"Can not convert value \"baseURI\" to string with error \"{e}\""362					))363				})?;364365		let base_uri = match base_uri.as_deref() {366			None | Some("") => {367				return Ok("".into());368			}369			Some(base_uri) => base_uri.into(),370		};371372		Ok(373			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {374				Err(_) | Ok("") => base_uri,375				Ok(suffix) => base_uri + suffix,376			},377		)378	}379}380381/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension382/// @dev See https://eips.ethereum.org/EIPS/eip-721383#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63, enum(derive(PreDispatch)), enum_attr(weight))]384impl<T: Config> NonfungibleHandle<T> {385	/// @notice Enumerate valid NFTs386	/// @param index A counter less than `totalSupply()`387	/// @return The token identifier for the `index`th NFT,388	///  (sort order not specified)389	fn token_by_index(&self, index: U256) -> U256 {390		index391	}392393	/// @dev Not implemented394	fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {395		// TODO: Not implemetable396		Err("not implemented".into())397	}398399	/// @notice Count NFTs tracked by this contract400	/// @return A count of valid NFTs tracked by this contract, where each one of401	///  them has an assigned and queryable owner not equal to the zero address402	fn total_supply(&self) -> Result<U256> {403		self.consume_store_reads(1)?;404		Ok(<Pallet<T>>::total_supply(self).into())405	}406}407408/// @title ERC-721 Non-Fungible Token Standard409/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md410#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]411impl<T: Config> NonfungibleHandle<T> {412	/// @notice Count all NFTs assigned to an owner413	/// @dev NFTs assigned to the zero address are considered invalid, and this414	///  function throws for queries about the zero address.415	/// @param owner An address for whom to query the balance416	/// @return The number of NFTs owned by `owner`, possibly zero417	fn balance_of(&self, owner: Address) -> Result<U256> {418		self.consume_store_reads(1)?;419		let owner = T::CrossAccountId::from_eth(owner);420		let balance = <AccountBalance<T>>::get((self.id, owner));421		Ok(balance.into())422	}423	/// @notice Find the owner of an NFT424	/// @dev NFTs assigned to zero address are considered invalid, and queries425	///  about them do throw.426	/// @param tokenId The identifier for an NFT427	/// @return The address of the owner of the NFT428	fn owner_of(&self, token_id: U256) -> Result<Address> {429		self.consume_store_reads(1)?;430		let token: TokenId = token_id.try_into()?;431		Ok(*<TokenData<T>>::get((self.id, token))432			.ok_or("token not found")?433			.owner434			.as_eth())435	}436	/// @dev Not implemented437	#[solidity(rename_selector = "safeTransferFrom")]438	fn safe_transfer_from_with_data(439		&mut self,440		_from: Address,441		_to: Address,442		_token_id: U256,443		_data: Bytes,444	) -> Result<()> {445		// TODO: Not implemetable446		Err("not implemented".into())447	}448	/// @dev Not implemented449	fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {450		// TODO: Not implemetable451		Err("not implemented".into())452	}453454	/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE455	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE456	///  THEY MAY BE PERMANENTLY LOST457	/// @dev Throws unless `msg.sender` is the current owner or an authorized458	///  operator for this NFT. Throws if `from` is not the current owner. Throws459	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.460	/// @param from The current owner of the NFT461	/// @param to The new owner462	/// @param tokenId The NFT to transfer463	#[weight(<CommonWeights<T>>::transfer_from())]464	fn transfer_from(465		&mut self,466		caller: Caller,467		from: Address,468		to: Address,469		token_id: U256,470	) -> Result<()> {471		let caller = T::CrossAccountId::from_eth(caller);472		let from = T::CrossAccountId::from_eth(from);473		let to = T::CrossAccountId::from_eth(to);474		let token = token_id.try_into()?;475		let budget = self476			.recorder477			.weight_calls_budget(<StructureWeight<T>>::find_parent());478479		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)480			.map_err(|e| dispatch_to_evm::<T>(e.error))?;481		Ok(())482	}483484	/// @notice Set or reaffirm the approved address for an NFT485	/// @dev The zero address indicates there is no approved address.486	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized487	///  operator of the current owner.488	/// @param approved The new approved NFT controller489	/// @param tokenId The NFT to approve490	#[weight(<SelfWeightOf<T>>::approve())]491	fn approve(&mut self, caller: Caller, approved: Address, token_id: U256) -> Result<()> {492		let caller = T::CrossAccountId::from_eth(caller);493		let approved = T::CrossAccountId::from_eth(approved);494		let token = token_id.try_into()?;495496		<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))497			.map_err(dispatch_to_evm::<T>)?;498		Ok(())499	}500501	/// @notice Sets or unsets the approval of a given operator.502	/// The `operator` is allowed to transfer all tokens of the `caller` on their behalf.503	/// @param operator Operator504	/// @param approved Should operator status be granted or revoked?505	#[weight(<SelfWeightOf<T>>::set_allowance_for_all())]506	fn set_approval_for_all(507		&mut self,508		caller: Caller,509		operator: Address,510		approved: bool,511	) -> Result<()> {512		let caller = T::CrossAccountId::from_eth(caller);513		let operator = T::CrossAccountId::from_eth(operator);514515		<Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)516			.map_err(dispatch_to_evm::<T>)?;517		Ok(())518	}519520	/// @notice Get the approved address for a single NFT521	/// @dev Throws if `tokenId` is not a valid NFT522	/// @param tokenId The NFT to find the approved address for523	/// @return The approved address for this NFT, or the zero address if there is none524	fn get_approved(&self, token_id: U256) -> Result<Address> {525		let token_id = token_id.try_into()?;526		let operator = <Pallet<T>>::get_allowance(self, token_id).map_err(dispatch_to_evm::<T>)?;527		Ok(if let Some(operator) = operator {528			*operator.as_eth()529		} else {530			Address::zero()531		})532	}533534	/// @notice Tells whether the given `owner` approves the `operator`.535	#[weight(<SelfWeightOf<T>>::allowance_for_all())]536	fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {537		let owner = T::CrossAccountId::from_eth(owner);538		let operator = T::CrossAccountId::from_eth(operator);539540		Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))541	}542}543544/// @title ERC721 Token that can be irreversibly burned (destroyed).545#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]546impl<T: Config> NonfungibleHandle<T> {547	/// @notice Burns a specific ERC721 token.548	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized549	///  operator of the current owner.550	/// @param tokenId The NFT to approve551	#[weight(<SelfWeightOf<T>>::burn_item())]552	fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {553		let caller = T::CrossAccountId::from_eth(caller);554		let token = token_id.try_into()?;555556		<Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;557		Ok(())558	}559}560561/// @title ERC721 minting logic.562#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]563impl<T: Config> NonfungibleHandle<T> {564	/// @notice Function to mint a token.565	/// @param to The new owner566	/// @return uint256 The id of the newly minted token567	#[weight(<SelfWeightOf<T>>::create_item())]568	fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {569		let token_id: U256 = <TokensMinted<T>>::get(self.id)570			.checked_add(1)571			.ok_or("item id overflow")?572			.into();573		self.mint_check_id(caller, to, token_id)?;574		Ok(token_id)575	}576577	/// @notice Function to mint a token.578	/// @dev `tokenId` should be obtained with `nextTokenId` method,579	///  unlike standard, you can't specify it manually580	/// @param to The new owner581	/// @param tokenId ID of the minted NFT582	#[solidity(hide, rename_selector = "mint")]583	#[weight(<SelfWeightOf<T>>::create_item())]584	fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {585		let caller = T::CrossAccountId::from_eth(caller);586		let to = T::CrossAccountId::from_eth(to);587		let token_id: u32 = token_id.try_into()?;588		let budget = self589			.recorder590			.weight_calls_budget(<StructureWeight<T>>::find_parent());591592		if <TokensMinted<T>>::get(self.id)593			.checked_add(1)594			.ok_or("item id overflow")?595			!= token_id596		{597			return Err("item id should be next".into());598		}599600		<Pallet<T>>::create_item(601			self,602			&caller,603			CreateItemData::<T> {604				properties: BoundedVec::default(),605				owner: to,606			},607			&budget,608		)609		.map_err(dispatch_to_evm::<T>)?;610611		Ok(true)612	}613614	/// @notice Function to mint token with the given tokenUri.615	/// @param to The new owner616	/// @param tokenUri Token URI that would be stored in the NFT properties617	/// @return uint256 The id of the newly minted token618	#[solidity(rename_selector = "mintWithTokenURI")]619	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]620	fn mint_with_token_uri(621		&mut self,622		caller: Caller,623		to: Address,624		token_uri: String,625	) -> Result<U256> {626		let token_id: U256 = <TokensMinted<T>>::get(self.id)627			.checked_add(1)628			.ok_or("item id overflow")?629			.into();630		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;631		Ok(token_id)632	}633634	/// @notice Function to mint token with the given tokenUri.635	/// @dev `tokenId` should be obtained with `nextTokenId` method,636	///  unlike standard, you can't specify it manually637	/// @param to The new owner638	/// @param tokenId ID of the minted NFT639	/// @param tokenUri Token URI that would be stored in the NFT properties640	#[solidity(hide, rename_selector = "mintWithTokenURI")]641	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]642	fn mint_with_token_uri_check_id(643		&mut self,644		caller: Caller,645		to: Address,646		token_id: U256,647		token_uri: String,648	) -> Result<bool> {649		let key = key::url();650		let permission = get_token_permission::<T>(self.id, &key)?;651		if !permission.collection_admin {652			return Err("Operation is not allowed".into());653		}654655		let caller = T::CrossAccountId::from_eth(caller);656		let to = T::CrossAccountId::from_eth(to);657		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;658		let budget = self659			.recorder660			.weight_calls_budget(<StructureWeight<T>>::find_parent());661662		if <TokensMinted<T>>::get(self.id)663			.checked_add(1)664			.ok_or("item id overflow")?665			!= token_id666		{667			return Err("item id should be next".into());668		}669670		let mut properties = CollectionPropertiesVec::default();671		properties672			.try_push(Property {673				key,674				value: token_uri675					.into_bytes()676					.try_into()677					.map_err(|_| "token uri is too long")?,678			})679			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;680681		<Pallet<T>>::create_item(682			self,683			&caller,684			CreateItemData::<T> {685				properties,686				owner: to,687			},688			&budget,689		)690		.map_err(dispatch_to_evm::<T>)?;691		Ok(true)692	}693}694695fn get_token_property<T: Config>(696	collection: &CollectionHandle<T>,697	token_id: u32,698	key: &up_data_structs::PropertyKey,699) -> Result<String> {700	collection.consume_store_reads(1)?;701	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))702		.map_err(|_| Error::Revert("Token properties not found".into()))?;703	if let Some(property) = properties.get(key) {704		return Ok(String::from_utf8_lossy(property).into());705	}706707	Err("Property tokenURI not found".into())708}709710fn get_token_permission<T: Config>(711	collection_id: CollectionId,712	key: &PropertyKey,713) -> Result<PropertyPermission> {714	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)715		.map_err(|_| Error::Revert("No permissions for collection".into()))?;716	let a = token_property_permissions717		.get(key)718		.map(Clone::clone)719		.ok_or_else(|| {720			let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();721			Error::Revert(alloc::format!("No permission for key {key}"))722		})?;723	Ok(a)724}725726/// @title Unique extensions for ERC721.727#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]728impl<T: Config> NonfungibleHandle<T>729where730	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,731{732	/// @notice A descriptive name for a collection of NFTs in this contract733	fn name(&self) -> String {734		decode_utf16(self.name.iter().copied())735			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))736			.collect::<String>()737	}738739	/// @notice An abbreviated name for NFTs in this contract740	fn symbol(&self) -> String {741		String::from_utf8_lossy(&self.token_prefix).into()742	}743744	/// @notice A description for the collection.745	fn description(&self) -> String {746		decode_utf16(self.description.iter().copied())747			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))748			.collect::<String>()749	}750751	/// Returns the owner (in cross format) of the token.752	///753	/// @param tokenId Id for the token.754	#[solidity(hide)]755	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {756		Self::owner_of_cross(self, token_id)757	}758759	/// Returns the owner (in cross format) of the token.760	///761	/// @param tokenId Id for the token.762	fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {763		Self::token_owner(self, token_id.try_into()?)764			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))765			.map_err(|_| Error::Revert("token not found".into()))766	}767768	/// @notice Count all NFTs assigned to an owner769	/// @param owner An cross address for whom to query the balance770	/// @return The number of NFTs owned by `owner`, possibly zero771	fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {772		self.consume_store_reads(1)?;773		let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));774		Ok(balance.into())775	}776777	/// Returns the token properties.778	///779	/// @param tokenId Id for the token.780	/// @param keys Properties keys. Empty keys for all propertyes.781	/// @return Vector of properties key/value pairs.782	fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {783		let keys = keys784			.into_iter()785			.map(|key| {786				<Vec<u8>>::from(key)787					.try_into()788					.map_err(|_| Error::Revert("key too large".into()))789			})790			.collect::<Result<Vec<_>>>()?;791792		<Self as CommonCollectionOperations<T>>::token_properties(793			self,794			token_id.try_into()?,795			if keys.is_empty() { None } else { Some(keys) },796		)797		.into_iter()798		.map(eth::Property::try_from)799		.collect::<Result<Vec<_>>>()800	}801802	/// @notice Set or reaffirm the approved address for an NFT803	/// @dev The zero address indicates there is no approved address.804	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized805	///  operator of the current owner.806	/// @param approved The new substrate address approved NFT controller807	/// @param tokenId The NFT to approve808	#[weight(<SelfWeightOf<T>>::approve())]809	fn approve_cross(810		&mut self,811		caller: Caller,812		approved: eth::CrossAddress,813		token_id: U256,814	) -> Result<()> {815		let caller = T::CrossAccountId::from_eth(caller);816		let approved = approved.into_sub_cross_account::<T>()?;817		let token = token_id.try_into()?;818819		<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))820			.map_err(dispatch_to_evm::<T>)?;821		Ok(())822	}823824	/// @notice Transfer ownership of an NFT825	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`826	///  is the zero address. Throws if `tokenId` is not a valid NFT.827	/// @param to The new owner828	/// @param tokenId The NFT to transfer829	#[weight(<CommonWeights<T>>::transfer())]830	fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {831		let caller = T::CrossAccountId::from_eth(caller);832		let to = T::CrossAccountId::from_eth(to);833		let token = token_id.try_into()?;834		let budget = self835			.recorder836			.weight_calls_budget(<StructureWeight<T>>::find_parent());837838		<Pallet<T>>::transfer(self, &caller, &to, token, &budget)839			.map_err(|e| dispatch_to_evm::<T>(e.error))?;840		Ok(())841	}842843	/// @notice Transfer ownership of an NFT844	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`845	///  is the zero address. Throws if `tokenId` is not a valid NFT.846	/// @param to The new owner847	/// @param tokenId The NFT to transfer848	#[weight(<CommonWeights<T>>::transfer())]849	fn transfer_cross(850		&mut self,851		caller: Caller,852		to: eth::CrossAddress,853		token_id: U256,854	) -> Result<()> {855		let caller = T::CrossAccountId::from_eth(caller);856		let to = to.into_sub_cross_account::<T>()?;857		let token = token_id.try_into()?;858		let budget = self859			.recorder860			.weight_calls_budget(<StructureWeight<T>>::find_parent());861862		<Pallet<T>>::transfer(self, &caller, &to, token, &budget)863			.map_err(|e| dispatch_to_evm::<T>(e.error))?;864		Ok(())865	}866867	/// @notice Transfer ownership of an NFT from cross account address to cross account address868	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`869	///  is the zero address. Throws if `tokenId` is not a valid NFT.870	/// @param from Cross acccount address of current owner871	/// @param to Cross acccount address of new owner872	/// @param tokenId The NFT to transfer873	#[weight(<CommonWeights<T>>::transfer_from())]874	fn transfer_from_cross(875		&mut self,876		caller: Caller,877		from: eth::CrossAddress,878		to: eth::CrossAddress,879		token_id: U256,880	) -> Result<()> {881		let caller = T::CrossAccountId::from_eth(caller);882		let from = from.into_sub_cross_account::<T>()?;883		let to = to.into_sub_cross_account::<T>()?;884		let token_id = token_id.try_into()?;885		let budget = self886			.recorder887			.weight_calls_budget(<StructureWeight<T>>::find_parent());888		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)889			.map_err(|e| dispatch_to_evm::<T>(e.error))?;890		Ok(())891	}892893	/// @notice Burns a specific ERC721 token.894	/// @dev Throws unless `msg.sender` is the current owner or an authorized895	///  operator for this NFT. Throws if `from` is not the current owner. Throws896	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.897	/// @param from The current owner of the NFT898	/// @param tokenId The NFT to transfer899	#[solidity(hide)]900	#[weight(<SelfWeightOf<T>>::burn_from())]901	fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {902		let caller = T::CrossAccountId::from_eth(caller);903		let from = T::CrossAccountId::from_eth(from);904		let token = token_id.try_into()?;905		let budget = self906			.recorder907			.weight_calls_budget(<StructureWeight<T>>::find_parent());908909		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)910			.map_err(dispatch_to_evm::<T>)?;911		Ok(())912	}913914	/// @notice Burns a specific ERC721 token.915	/// @dev Throws unless `msg.sender` is the current owner or an authorized916	///  operator for this NFT. Throws if `from` is not the current owner. Throws917	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.918	/// @param from The current owner of the NFT919	/// @param tokenId The NFT to transfer920	#[weight(<SelfWeightOf<T>>::burn_from())]921	fn burn_from_cross(922		&mut self,923		caller: Caller,924		from: eth::CrossAddress,925		token_id: U256,926	) -> Result<()> {927		let caller = T::CrossAccountId::from_eth(caller);928		let from = from.into_sub_cross_account::<T>()?;929		let token = token_id.try_into()?;930		let budget = self931			.recorder932			.weight_calls_budget(<StructureWeight<T>>::find_parent());933934		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)935			.map_err(dispatch_to_evm::<T>)?;936		Ok(())937	}938939	/// @notice Returns next free NFT ID.940	fn next_token_id(&self) -> Result<U256> {941		self.consume_store_reads(1)?;942		Ok(<Pallet<T>>::next_token_id(self)943			.map_err(dispatch_to_evm::<T>)?944			.into())945	}946947	/// @notice Function to mint multiple tokens.948	/// @dev `tokenIds` should be an array of consecutive numbers and first number949	///  should be obtained with `nextTokenId` method950	/// @param to The new owner951	/// @param tokenIds IDs of the minted NFTs952	#[solidity(hide)]953	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]954	fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {955		let caller = T::CrossAccountId::from_eth(caller);956		let to = T::CrossAccountId::from_eth(to);957		let mut expected_index = <TokensMinted<T>>::get(self.id)958			.checked_add(1)959			.ok_or("item id overflow")?;960		let budget = self961			.recorder962			.weight_calls_budget(<StructureWeight<T>>::find_parent());963964		let total_tokens = token_ids.len();965		for id in token_ids.into_iter() {966			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;967			if id != expected_index {968				return Err("item id should be next".into());969			}970			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;971		}972		let data = (0..total_tokens)973			.map(|_| CreateItemData::<T> {974				properties: BoundedVec::default(),975				owner: to.clone(),976			})977			.collect();978979		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)980			.map_err(dispatch_to_evm::<T>)?;981		Ok(true)982	}983984	/// @notice Function to mint multiple tokens with the given tokenUris.985	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive986	///  numbers and first number should be obtained with `nextTokenId` method987	/// @param to The new owner988	/// @param tokens array of pairs of token ID and token URI for minted tokens989	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]990	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32)  + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]991	fn mint_bulk_with_token_uri(992		&mut self,993		caller: Caller,994		to: Address,995		tokens: Vec<TokenUri>,996	) -> Result<bool> {997		let key = key::url();998		let caller = T::CrossAccountId::from_eth(caller);999		let to = T::CrossAccountId::from_eth(to);1000		let mut expected_index = <TokensMinted<T>>::get(self.id)1001			.checked_add(1)1002			.ok_or("item id overflow")?;1003		let budget = self1004			.recorder1005			.weight_calls_budget(<StructureWeight<T>>::find_parent());10061007		let mut data = Vec::with_capacity(tokens.len());1008		for TokenUri { id, uri } in tokens {1009			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1010			if id != expected_index {1011				return Err("item id should be next".into());1012			}1013			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10141015			let mut properties = CollectionPropertiesVec::default();1016			properties1017				.try_push(Property {1018					key: key.clone(),1019					value: uri1020						.into_bytes()1021						.try_into()1022						.map_err(|_| "token uri is too long")?,1023				})1024				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;10251026			data.push(CreateItemData::<T> {1027				properties,1028				owner: to.clone(),1029			});1030		}10311032		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1033			.map_err(dispatch_to_evm::<T>)?;1034		Ok(true)1035	}10361037	/// @notice Function to mint a token.1038	/// @param to The new owner crossAccountId1039	/// @param properties Properties of minted token1040	/// @return uint256 The id of the newly minted token1041	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1042	fn mint_cross(1043		&mut self,1044		caller: Caller,1045		to: eth::CrossAddress,1046		properties: Vec<eth::Property>,1047	) -> Result<U256> {1048		let token_id = <TokensMinted<T>>::get(self.id)1049			.checked_add(1)1050			.ok_or("item id overflow")?;10511052		let to = to.into_sub_cross_account::<T>()?;10531054		let properties = properties1055			.into_iter()1056			.map(eth::Property::try_into)1057			.collect::<Result<Vec<_>>>()?1058			.try_into()1059			.map_err(|_| Error::Revert("too many properties".to_string()))?;10601061		let caller = T::CrossAccountId::from_eth(caller);10621063		let budget = self1064			.recorder1065			.weight_calls_budget(<StructureWeight<T>>::find_parent());10661067		<Pallet<T>>::create_item(1068			self,1069			&caller,1070			CreateItemData::<T> {1071				properties,1072				owner: to,1073			},1074			&budget,1075		)1076		.map_err(dispatch_to_evm::<T>)?;10771078		Ok(token_id.into())1079	}10801081	/// @notice Returns collection helper contract address1082	fn collection_helper_address(&self) -> Address {1083		T::ContractAddress::get()1084	}1085}10861087#[solidity_interface(1088	name = UniqueNFT,1089	is(1090		ERC721,1091		ERC721Enumerable,1092		ERC721UniqueExtensions,1093		ERC721UniqueMintable,1094		ERC721Burnable,1095		ERC721Metadata(if(this.flags.erc721metadata)),1096		Collection(via(common_mut returns CollectionHandle<T>)),1097		TokenProperties,1098	),1099	enum(derive(PreDispatch)),1100)]1101impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11021103// Not a tests, but code generators1104generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);1105generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);11061107impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>1108where1109	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1110{1111	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");11121113	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {1114		call::<T, UniqueNFTCall<T>, _, _>(handle, self)1115	}1116}
after · pallets/nonfungible/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//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26	char::{REPLACEMENT_CHARACTER, decode_utf16},27	convert::TryInto,28};29use evm_coder::{abi::AbiType, AbiCoder, ToLog, generate_stubgen, solidity_interface, types::*};30use frame_support::BoundedVec;31use up_data_structs::{32	TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,33	CollectionPropertiesVec,34};35use pallet_evm_coder_substrate::{36	dispatch_to_evm, frontier_contract,37	execution::{Result, PreDispatch, Error},38};39use sp_std::{vec::Vec, vec};40use pallet_common::{41	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,42	erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},43	eth::{self, TokenUri},44	CommonWeightInfo,45};46use pallet_evm::{account::CrossAccountId, PrecompileHandle};47use pallet_evm_coder_substrate::call;48use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};49use sp_core::{U256, Get};5051use crate::{52	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,53	TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,54};5556/// Nft events.57#[derive(ToLog)]58pub enum ERC721TokenEvent {59	/// The token has been changed.60	TokenChanged {61		/// Token ID.62		#[indexed]63		token_id: U256,64	},65}6667/// Token minting parameters68#[derive(AbiCoder, Default, Debug)]69pub struct MintTokenData {70	/// Minted token owner71	pub owner: eth::CrossAddress,72	/// Minted token properties73	pub properties: Vec<eth::Property>,74}7576frontier_contract! {77	macro_rules! NonfungibleHandle_result {...}78	impl<T: Config> Contract for NonfungibleHandle<T> {...}79}8081/// @title A contract that allows to set and delete token properties and change token property permissions.82#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]83impl<T: Config> NonfungibleHandle<T> {84	/// @notice Set permissions for token property.85	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.86	/// @param key Property key.87	/// @param isMutable Permission to mutate property.88	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.89	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.90	#[solidity(hide)]91	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]92	fn set_token_property_permission(93		&mut self,94		caller: Caller,95		key: String,96		is_mutable: bool,97		collection_admin: bool,98		token_owner: bool,99	) -> Result<()> {100		let caller = T::CrossAccountId::from_eth(caller);101		<Pallet<T>>::set_token_property_permissions(102			self,103			&caller,104			vec![PropertyKeyPermission {105				key: <Vec<u8>>::from(key)106					.try_into()107					.map_err(|_| "too long key")?,108				permission: PropertyPermission {109					mutable: is_mutable,110					collection_admin,111					token_owner,112				},113			}],114		)115		.map_err(dispatch_to_evm::<T>)116	}117118	/// @notice Set permissions for token property.119	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.120	/// @param permissions Permissions for keys.121	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]122	fn set_token_property_permissions(123		&mut self,124		caller: Caller,125		permissions: Vec<eth::TokenPropertyPermission>,126	) -> Result<()> {127		let caller = T::CrossAccountId::from_eth(caller);128		let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;129130		<Pallet<T>>::set_token_property_permissions(self, &caller, perms)131			.map_err(dispatch_to_evm::<T>)132	}133134	/// @notice Get permissions for token properties.135	fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {136		let perms = <Pallet<T>>::token_property_permission(self.id);137		Ok(perms138			.into_iter()139			.map(eth::TokenPropertyPermission::from)140			.collect())141	}142143	/// @notice Set token property value.144	/// @dev Throws error if `msg.sender` has no permission to edit the property.145	/// @param tokenId ID of the token.146	/// @param key Property key.147	/// @param value Property value.148	#[solidity(hide)]149	#[weight(<SelfWeightOf<T>>::set_token_properties(1))]150	fn set_property(151		&mut self,152		caller: Caller,153		token_id: U256,154		key: String,155		value: Bytes,156	) -> Result<()> {157		let caller = T::CrossAccountId::from_eth(caller);158		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;159		let key = <Vec<u8>>::from(key)160			.try_into()161			.map_err(|_| "key too long")?;162		let value = value.0.try_into().map_err(|_| "value too long")?;163164		let nesting_budget = self165			.recorder166			.weight_calls_budget(<StructureWeight<T>>::find_parent());167168		<Pallet<T>>::set_token_property(169			self,170			&caller,171			TokenId(token_id),172			Property { key, value },173			&nesting_budget,174		)175		.map_err(dispatch_to_evm::<T>)176	}177178	/// @notice Set token properties value.179	/// @dev Throws error if `msg.sender` has no permission to edit the property.180	/// @param tokenId ID of the token.181	/// @param properties settable properties182	#[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]183	fn set_properties(184		&mut self,185		caller: Caller,186		token_id: U256,187		properties: Vec<eth::Property>,188	) -> Result<()> {189		let caller = T::CrossAccountId::from_eth(caller);190		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;191192		let nesting_budget = self193			.recorder194			.weight_calls_budget(<StructureWeight<T>>::find_parent());195196		let properties = properties197			.into_iter()198			.map(eth::Property::try_into)199			.collect::<Result<Vec<_>>>()?;200201		<Pallet<T>>::set_token_properties(202			self,203			&caller,204			TokenId(token_id),205			properties.into_iter(),206			pallet_common::SetPropertyMode::ExistingToken,207			&nesting_budget,208		)209		.map_err(dispatch_to_evm::<T>)210	}211212	/// @notice Delete token property value.213	/// @dev Throws error if `msg.sender` has no permission to edit the property.214	/// @param tokenId ID of the token.215	/// @param key Property key.216	#[solidity(hide)]217	#[weight(<SelfWeightOf<T>>::delete_token_properties(1))]218	fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {219		let caller = T::CrossAccountId::from_eth(caller);220		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;221		let key = <Vec<u8>>::from(key)222			.try_into()223			.map_err(|_| "key too long")?;224225		let nesting_budget = self226			.recorder227			.weight_calls_budget(<StructureWeight<T>>::find_parent());228229		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)230			.map_err(dispatch_to_evm::<T>)231	}232233	/// @notice Delete token properties value.234	/// @dev Throws error if `msg.sender` has no permission to edit the property.235	/// @param tokenId ID of the token.236	/// @param keys Properties key.237	#[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]238	fn delete_properties(239		&mut self,240		token_id: U256,241		caller: Caller,242		keys: Vec<String>,243	) -> Result<()> {244		let caller = T::CrossAccountId::from_eth(caller);245		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;246		let keys = keys247			.into_iter()248			.map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))249			.collect::<Result<Vec<_>>>()?;250251		let nesting_budget = self252			.recorder253			.weight_calls_budget(<StructureWeight<T>>::find_parent());254255		<Pallet<T>>::delete_token_properties(256			self,257			&caller,258			TokenId(token_id),259			keys.into_iter(),260			&nesting_budget,261		)262		.map_err(dispatch_to_evm::<T>)263	}264265	/// @notice Get token property value.266	/// @dev Throws error if key not found267	/// @param tokenId ID of the token.268	/// @param key Property key.269	/// @return Property value bytes270	fn property(&self, token_id: U256, key: String) -> Result<Bytes> {271		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;272		let key = <Vec<u8>>::from(key)273			.try_into()274			.map_err(|_| "key too long")?;275276		let props = <TokenProperties<T>>::get((self.id, token_id));277		let prop = props.get(&key).ok_or("key not found")?;278279		Ok(prop.to_vec().into())280	}281}282283#[derive(ToLog)]284pub enum ERC721Events {285	/// @dev This emits when ownership of any NFT changes by any mechanism.286	///  This event emits when NFTs are created (`from` == 0) and destroyed287	///  (`to` == 0). Exception: during contract creation, any number of NFTs288	///  may be created and assigned without emitting Transfer. At the time of289	///  any transfer, the approved address for that NFT (if any) is reset to none.290	Transfer {291		#[indexed]292		from: Address,293		#[indexed]294		to: Address,295		#[indexed]296		token_id: U256,297	},298	/// @dev This emits when the approved address for an NFT is changed or299	///  reaffirmed. The zero address indicates there is no approved address.300	///  When a Transfer event emits, this also indicates that the approved301	///  address for that NFT (if any) is reset to none.302	Approval {303		#[indexed]304		owner: Address,305		#[indexed]306		approved: Address,307		#[indexed]308		token_id: U256,309	},310	/// @dev This emits when an operator is enabled or disabled for an owner.311	///  The operator can manage all NFTs of the owner.312	#[allow(dead_code)]313	ApprovalForAll {314		#[indexed]315		owner: Address,316		#[indexed]317		operator: Address,318		approved: bool,319	},320}321322/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension323/// @dev See https://eips.ethereum.org/EIPS/eip-721324#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f, enum(derive(PreDispatch)), enum_attr(weight))]325impl<T: Config> NonfungibleHandle<T>326where327	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,328{329	/// @notice A descriptive name for a collection of NFTs in this contract330	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`331	#[solidity(hide, rename_selector = "name")]332	fn name_proxy(&self) -> String {333		self.name()334	}335336	/// @notice An abbreviated name for NFTs in this contract337	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`338	#[solidity(hide, rename_selector = "symbol")]339	fn symbol_proxy(&self) -> String {340		self.symbol()341	}342343	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.344	///345	/// @dev If the token has a `url` property and it is not empty, it is returned.346	///  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`.347	///  If the collection property `baseURI` is empty or absent, return "" (empty string)348	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix349	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).350	///351	/// @return token's const_metadata352	#[solidity(rename_selector = "tokenURI")]353	fn token_uri(&self, token_id: U256) -> Result<String> {354		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;355356		match get_token_property(self, token_id_u32, &key::url()).as_deref() {357			Err(_) | Ok("") => (),358			Ok(url) => {359				return Ok(url.into());360			}361		};362363		let base_uri =364			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())365				.map(BoundedVec::into_inner)366				.map(String::from_utf8)367				.transpose()368				.map_err(|e| {369					Error::Revert(alloc::format!(370						"Can not convert value \"baseURI\" to string with error \"{e}\""371					))372				})?;373374		let base_uri = match base_uri.as_deref() {375			None | Some("") => {376				return Ok("".into());377			}378			Some(base_uri) => base_uri.into(),379		};380381		Ok(382			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {383				Err(_) | Ok("") => base_uri,384				Ok(suffix) => base_uri + suffix,385			},386		)387	}388}389390/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension391/// @dev See https://eips.ethereum.org/EIPS/eip-721392#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63, enum(derive(PreDispatch)), enum_attr(weight))]393impl<T: Config> NonfungibleHandle<T> {394	/// @notice Enumerate valid NFTs395	/// @param index A counter less than `totalSupply()`396	/// @return The token identifier for the `index`th NFT,397	///  (sort order not specified)398	fn token_by_index(&self, index: U256) -> U256 {399		index400	}401402	/// @dev Not implemented403	fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {404		// TODO: Not implemetable405		Err("not implemented".into())406	}407408	/// @notice Count NFTs tracked by this contract409	/// @return A count of valid NFTs tracked by this contract, where each one of410	///  them has an assigned and queryable owner not equal to the zero address411	fn total_supply(&self) -> Result<U256> {412		self.consume_store_reads(1)?;413		Ok(<Pallet<T>>::total_supply(self).into())414	}415}416417/// @title ERC-721 Non-Fungible Token Standard418/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md419#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]420impl<T: Config> NonfungibleHandle<T> {421	/// @notice Count all NFTs assigned to an owner422	/// @dev NFTs assigned to the zero address are considered invalid, and this423	///  function throws for queries about the zero address.424	/// @param owner An address for whom to query the balance425	/// @return The number of NFTs owned by `owner`, possibly zero426	fn balance_of(&self, owner: Address) -> Result<U256> {427		self.consume_store_reads(1)?;428		let owner = T::CrossAccountId::from_eth(owner);429		let balance = <AccountBalance<T>>::get((self.id, owner));430		Ok(balance.into())431	}432	/// @notice Find the owner of an NFT433	/// @dev NFTs assigned to zero address are considered invalid, and queries434	///  about them do throw.435	/// @param tokenId The identifier for an NFT436	/// @return The address of the owner of the NFT437	fn owner_of(&self, token_id: U256) -> Result<Address> {438		self.consume_store_reads(1)?;439		let token: TokenId = token_id.try_into()?;440		Ok(*<TokenData<T>>::get((self.id, token))441			.ok_or("token not found")?442			.owner443			.as_eth())444	}445	/// @dev Not implemented446	#[solidity(rename_selector = "safeTransferFrom")]447	fn safe_transfer_from_with_data(448		&mut self,449		_from: Address,450		_to: Address,451		_token_id: U256,452		_data: Bytes,453	) -> Result<()> {454		// TODO: Not implemetable455		Err("not implemented".into())456	}457	/// @dev Not implemented458	fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {459		// TODO: Not implemetable460		Err("not implemented".into())461	}462463	/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE464	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE465	///  THEY MAY BE PERMANENTLY LOST466	/// @dev Throws unless `msg.sender` is the current owner or an authorized467	///  operator for this NFT. Throws if `from` is not the current owner. Throws468	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.469	/// @param from The current owner of the NFT470	/// @param to The new owner471	/// @param tokenId The NFT to transfer472	#[weight(<CommonWeights<T>>::transfer_from())]473	fn transfer_from(474		&mut self,475		caller: Caller,476		from: Address,477		to: Address,478		token_id: U256,479	) -> Result<()> {480		let caller = T::CrossAccountId::from_eth(caller);481		let from = T::CrossAccountId::from_eth(from);482		let to = T::CrossAccountId::from_eth(to);483		let token = token_id.try_into()?;484		let budget = self485			.recorder486			.weight_calls_budget(<StructureWeight<T>>::find_parent());487488		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)489			.map_err(|e| dispatch_to_evm::<T>(e.error))?;490		Ok(())491	}492493	/// @notice Set or reaffirm the approved address for an NFT494	/// @dev The zero address indicates there is no approved address.495	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized496	///  operator of the current owner.497	/// @param approved The new approved NFT controller498	/// @param tokenId The NFT to approve499	#[weight(<SelfWeightOf<T>>::approve())]500	fn approve(&mut self, caller: Caller, approved: Address, token_id: U256) -> Result<()> {501		let caller = T::CrossAccountId::from_eth(caller);502		let approved = T::CrossAccountId::from_eth(approved);503		let token = token_id.try_into()?;504505		<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))506			.map_err(dispatch_to_evm::<T>)?;507		Ok(())508	}509510	/// @notice Sets or unsets the approval of a given operator.511	/// The `operator` is allowed to transfer all tokens of the `caller` on their behalf.512	/// @param operator Operator513	/// @param approved Should operator status be granted or revoked?514	#[weight(<SelfWeightOf<T>>::set_allowance_for_all())]515	fn set_approval_for_all(516		&mut self,517		caller: Caller,518		operator: Address,519		approved: bool,520	) -> Result<()> {521		let caller = T::CrossAccountId::from_eth(caller);522		let operator = T::CrossAccountId::from_eth(operator);523524		<Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)525			.map_err(dispatch_to_evm::<T>)?;526		Ok(())527	}528529	/// @notice Get the approved address for a single NFT530	/// @dev Throws if `tokenId` is not a valid NFT531	/// @param tokenId The NFT to find the approved address for532	/// @return The approved address for this NFT, or the zero address if there is none533	fn get_approved(&self, token_id: U256) -> Result<Address> {534		let token_id = token_id.try_into()?;535		let operator = <Pallet<T>>::get_allowance(self, token_id).map_err(dispatch_to_evm::<T>)?;536		Ok(if let Some(operator) = operator {537			*operator.as_eth()538		} else {539			Address::zero()540		})541	}542543	/// @notice Tells whether the given `owner` approves the `operator`.544	#[weight(<SelfWeightOf<T>>::allowance_for_all())]545	fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {546		let owner = T::CrossAccountId::from_eth(owner);547		let operator = T::CrossAccountId::from_eth(operator);548549		Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))550	}551}552553/// @title ERC721 Token that can be irreversibly burned (destroyed).554#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]555impl<T: Config> NonfungibleHandle<T> {556	/// @notice Burns a specific ERC721 token.557	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized558	///  operator of the current owner.559	/// @param tokenId The NFT to approve560	#[weight(<SelfWeightOf<T>>::burn_item())]561	fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {562		let caller = T::CrossAccountId::from_eth(caller);563		let token = token_id.try_into()?;564565		<Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;566		Ok(())567	}568}569570/// @title ERC721 minting logic.571#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]572impl<T: Config> NonfungibleHandle<T> {573	/// @notice Function to mint a token.574	/// @param to The new owner575	/// @return uint256 The id of the newly minted token576	#[weight(<SelfWeightOf<T>>::create_item())]577	fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {578		let token_id: U256 = <TokensMinted<T>>::get(self.id)579			.checked_add(1)580			.ok_or("item id overflow")?581			.into();582		self.mint_check_id(caller, to, token_id)?;583		Ok(token_id)584	}585586	/// @notice Function to mint a token.587	/// @dev `tokenId` should be obtained with `nextTokenId` method,588	///  unlike standard, you can't specify it manually589	/// @param to The new owner590	/// @param tokenId ID of the minted NFT591	#[solidity(hide, rename_selector = "mint")]592	#[weight(<SelfWeightOf<T>>::create_item())]593	fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {594		let caller = T::CrossAccountId::from_eth(caller);595		let to = T::CrossAccountId::from_eth(to);596		let token_id: u32 = token_id.try_into()?;597		let budget = self598			.recorder599			.weight_calls_budget(<StructureWeight<T>>::find_parent());600601		if <TokensMinted<T>>::get(self.id)602			.checked_add(1)603			.ok_or("item id overflow")?604			!= token_id605		{606			return Err("item id should be next".into());607		}608609		<Pallet<T>>::create_item(610			self,611			&caller,612			CreateItemData::<T> {613				properties: BoundedVec::default(),614				owner: to,615			},616			&budget,617		)618		.map_err(dispatch_to_evm::<T>)?;619620		Ok(true)621	}622623	/// @notice Function to mint token with the given tokenUri.624	/// @param to The new owner625	/// @param tokenUri Token URI that would be stored in the NFT properties626	/// @return uint256 The id of the newly minted token627	#[solidity(rename_selector = "mintWithTokenURI")]628	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]629	fn mint_with_token_uri(630		&mut self,631		caller: Caller,632		to: Address,633		token_uri: String,634	) -> Result<U256> {635		let token_id: U256 = <TokensMinted<T>>::get(self.id)636			.checked_add(1)637			.ok_or("item id overflow")?638			.into();639		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;640		Ok(token_id)641	}642643	/// @notice Function to mint token with the given tokenUri.644	/// @dev `tokenId` should be obtained with `nextTokenId` method,645	///  unlike standard, you can't specify it manually646	/// @param to The new owner647	/// @param tokenId ID of the minted NFT648	/// @param tokenUri Token URI that would be stored in the NFT properties649	#[solidity(hide, rename_selector = "mintWithTokenURI")]650	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]651	fn mint_with_token_uri_check_id(652		&mut self,653		caller: Caller,654		to: Address,655		token_id: U256,656		token_uri: String,657	) -> Result<bool> {658		let key = key::url();659		let permission = get_token_permission::<T>(self.id, &key)?;660		if !permission.collection_admin {661			return Err("Operation is not allowed".into());662		}663664		let caller = T::CrossAccountId::from_eth(caller);665		let to = T::CrossAccountId::from_eth(to);666		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;667		let budget = self668			.recorder669			.weight_calls_budget(<StructureWeight<T>>::find_parent());670671		if <TokensMinted<T>>::get(self.id)672			.checked_add(1)673			.ok_or("item id overflow")?674			!= token_id675		{676			return Err("item id should be next".into());677		}678679		let mut properties = CollectionPropertiesVec::default();680		properties681			.try_push(Property {682				key,683				value: token_uri684					.into_bytes()685					.try_into()686					.map_err(|_| "token uri is too long")?,687			})688			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;689690		<Pallet<T>>::create_item(691			self,692			&caller,693			CreateItemData::<T> {694				properties,695				owner: to,696			},697			&budget,698		)699		.map_err(dispatch_to_evm::<T>)?;700		Ok(true)701	}702}703704fn get_token_property<T: Config>(705	collection: &CollectionHandle<T>,706	token_id: u32,707	key: &up_data_structs::PropertyKey,708) -> Result<String> {709	collection.consume_store_reads(1)?;710	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))711		.map_err(|_| Error::Revert("Token properties not found".into()))?;712	if let Some(property) = properties.get(key) {713		return Ok(String::from_utf8_lossy(property).into());714	}715716	Err("Property tokenURI not found".into())717}718719fn get_token_permission<T: Config>(720	collection_id: CollectionId,721	key: &PropertyKey,722) -> Result<PropertyPermission> {723	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)724		.map_err(|_| Error::Revert("No permissions for collection".into()))?;725	let a = token_property_permissions726		.get(key)727		.map(Clone::clone)728		.ok_or_else(|| {729			let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();730			Error::Revert(alloc::format!("No permission for key {key}"))731		})?;732	Ok(a)733}734735/// @title Unique extensions for ERC721.736#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]737impl<T: Config> NonfungibleHandle<T>738where739	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,740{741	/// @notice A descriptive name for a collection of NFTs in this contract742	fn name(&self) -> String {743		decode_utf16(self.name.iter().copied())744			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))745			.collect::<String>()746	}747748	/// @notice An abbreviated name for NFTs in this contract749	fn symbol(&self) -> String {750		String::from_utf8_lossy(&self.token_prefix).into()751	}752753	/// @notice A description for the collection.754	fn description(&self) -> String {755		decode_utf16(self.description.iter().copied())756			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))757			.collect::<String>()758	}759760	/// Returns the owner (in cross format) of the token.761	///762	/// @param tokenId Id for the token.763	#[solidity(hide)]764	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {765		Self::owner_of_cross(self, token_id)766	}767768	/// Returns the owner (in cross format) of the token.769	///770	/// @param tokenId Id for the token.771	fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {772		Self::token_owner(self, token_id.try_into()?)773			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))774			.map_err(|_| Error::Revert("token not found".into()))775	}776777	/// @notice Count all NFTs assigned to an owner778	/// @param owner An cross address for whom to query the balance779	/// @return The number of NFTs owned by `owner`, possibly zero780	fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {781		self.consume_store_reads(1)?;782		let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));783		Ok(balance.into())784	}785786	/// Returns the token properties.787	///788	/// @param tokenId Id for the token.789	/// @param keys Properties keys. Empty keys for all propertyes.790	/// @return Vector of properties key/value pairs.791	fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {792		let keys = keys793			.into_iter()794			.map(|key| {795				<Vec<u8>>::from(key)796					.try_into()797					.map_err(|_| Error::Revert("key too large".into()))798			})799			.collect::<Result<Vec<_>>>()?;800801		<Self as CommonCollectionOperations<T>>::token_properties(802			self,803			token_id.try_into()?,804			if keys.is_empty() { None } else { Some(keys) },805		)806		.into_iter()807		.map(eth::Property::try_from)808		.collect::<Result<Vec<_>>>()809	}810811	/// @notice Set or reaffirm the approved address for an NFT812	/// @dev The zero address indicates there is no approved address.813	/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized814	///  operator of the current owner.815	/// @param approved The new substrate address approved NFT controller816	/// @param tokenId The NFT to approve817	#[weight(<SelfWeightOf<T>>::approve())]818	fn approve_cross(819		&mut self,820		caller: Caller,821		approved: eth::CrossAddress,822		token_id: U256,823	) -> Result<()> {824		let caller = T::CrossAccountId::from_eth(caller);825		let approved = approved.into_sub_cross_account::<T>()?;826		let token = token_id.try_into()?;827828		<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))829			.map_err(dispatch_to_evm::<T>)?;830		Ok(())831	}832833	/// @notice Transfer ownership of an NFT834	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`835	///  is the zero address. Throws if `tokenId` is not a valid NFT.836	/// @param to The new owner837	/// @param tokenId The NFT to transfer838	#[weight(<CommonWeights<T>>::transfer())]839	fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {840		let caller = T::CrossAccountId::from_eth(caller);841		let to = T::CrossAccountId::from_eth(to);842		let token = token_id.try_into()?;843		let budget = self844			.recorder845			.weight_calls_budget(<StructureWeight<T>>::find_parent());846847		<Pallet<T>>::transfer(self, &caller, &to, token, &budget)848			.map_err(|e| dispatch_to_evm::<T>(e.error))?;849		Ok(())850	}851852	/// @notice Transfer ownership of an NFT853	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`854	///  is the zero address. Throws if `tokenId` is not a valid NFT.855	/// @param to The new owner856	/// @param tokenId The NFT to transfer857	#[weight(<CommonWeights<T>>::transfer())]858	fn transfer_cross(859		&mut self,860		caller: Caller,861		to: eth::CrossAddress,862		token_id: U256,863	) -> Result<()> {864		let caller = T::CrossAccountId::from_eth(caller);865		let to = to.into_sub_cross_account::<T>()?;866		let token = token_id.try_into()?;867		let budget = self868			.recorder869			.weight_calls_budget(<StructureWeight<T>>::find_parent());870871		<Pallet<T>>::transfer(self, &caller, &to, token, &budget)872			.map_err(|e| dispatch_to_evm::<T>(e.error))?;873		Ok(())874	}875876	/// @notice Transfer ownership of an NFT from cross account address to cross account address877	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`878	///  is the zero address. Throws if `tokenId` is not a valid NFT.879	/// @param from Cross acccount address of current owner880	/// @param to Cross acccount address of new owner881	/// @param tokenId The NFT to transfer882	#[weight(<CommonWeights<T>>::transfer_from())]883	fn transfer_from_cross(884		&mut self,885		caller: Caller,886		from: eth::CrossAddress,887		to: eth::CrossAddress,888		token_id: U256,889	) -> Result<()> {890		let caller = T::CrossAccountId::from_eth(caller);891		let from = from.into_sub_cross_account::<T>()?;892		let to = to.into_sub_cross_account::<T>()?;893		let token_id = token_id.try_into()?;894		let budget = self895			.recorder896			.weight_calls_budget(<StructureWeight<T>>::find_parent());897		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)898			.map_err(|e| dispatch_to_evm::<T>(e.error))?;899		Ok(())900	}901902	/// @notice Burns a specific ERC721 token.903	/// @dev Throws unless `msg.sender` is the current owner or an authorized904	///  operator for this NFT. Throws if `from` is not the current owner. Throws905	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.906	/// @param from The current owner of the NFT907	/// @param tokenId The NFT to transfer908	#[solidity(hide)]909	#[weight(<SelfWeightOf<T>>::burn_from())]910	fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {911		let caller = T::CrossAccountId::from_eth(caller);912		let from = T::CrossAccountId::from_eth(from);913		let token = token_id.try_into()?;914		let budget = self915			.recorder916			.weight_calls_budget(<StructureWeight<T>>::find_parent());917918		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)919			.map_err(dispatch_to_evm::<T>)?;920		Ok(())921	}922923	/// @notice Burns a specific ERC721 token.924	/// @dev Throws unless `msg.sender` is the current owner or an authorized925	///  operator for this NFT. Throws if `from` is not the current owner. Throws926	///  if `to` is the zero address. Throws if `tokenId` is not a valid NFT.927	/// @param from The current owner of the NFT928	/// @param tokenId The NFT to transfer929	#[weight(<SelfWeightOf<T>>::burn_from())]930	fn burn_from_cross(931		&mut self,932		caller: Caller,933		from: eth::CrossAddress,934		token_id: U256,935	) -> Result<()> {936		let caller = T::CrossAccountId::from_eth(caller);937		let from = from.into_sub_cross_account::<T>()?;938		let token = token_id.try_into()?;939		let budget = self940			.recorder941			.weight_calls_budget(<StructureWeight<T>>::find_parent());942943		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)944			.map_err(dispatch_to_evm::<T>)?;945		Ok(())946	}947948	/// @notice Returns next free NFT ID.949	fn next_token_id(&self) -> Result<U256> {950		self.consume_store_reads(1)?;951		Ok(<Pallet<T>>::next_token_id(self)952			.map_err(dispatch_to_evm::<T>)?953			.into())954	}955956	/// @notice Function to mint multiple tokens.957	/// @dev `tokenIds` should be an array of consecutive numbers and first number958	///  should be obtained with `nextTokenId` method959	/// @param to The new owner960	/// @param tokenIds IDs of the minted NFTs961	#[solidity(hide)]962	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]963	fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {964		let caller = T::CrossAccountId::from_eth(caller);965		let to = T::CrossAccountId::from_eth(to);966		let mut expected_index = <TokensMinted<T>>::get(self.id)967			.checked_add(1)968			.ok_or("item id overflow")?;969		let budget = self970			.recorder971			.weight_calls_budget(<StructureWeight<T>>::find_parent());972973		let total_tokens = token_ids.len();974		for id in token_ids.into_iter() {975			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;976			if id != expected_index {977				return Err("item id should be next".into());978			}979			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;980		}981		let data = (0..total_tokens)982			.map(|_| CreateItemData::<T> {983				properties: BoundedVec::default(),984				owner: to.clone(),985			})986			.collect();987988		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)989			.map_err(dispatch_to_evm::<T>)?;990		Ok(true)991	}992993	/// @notice Function to mint a token.994	/// @param data Array of pairs of token owner and token's properties for minted token995	#[weight(<SelfWeightOf<T>>::create_multiple_items(data.len() as u32) + <SelfWeightOf<T>>::set_token_properties(data.len() as u32))]996	fn mint_bulk_cross(&mut self, caller: Caller, data: Vec<MintTokenData>) -> Result<bool> {997		let caller = T::CrossAccountId::from_eth(caller);998		let budget = self999			.recorder1000			.weight_calls_budget(<StructureWeight<T>>::find_parent());10011002		let mut create_nft_data = Vec::with_capacity(data.len());1003		for MintTokenData { owner, properties } in data {1004			let owner = owner.into_sub_cross_account::<T>()?;1005			create_nft_data.push(CreateItemData::<T> {1006				properties: properties1007					.into_iter()1008					.map(|property| property.try_into())1009					.collect::<Result<Vec<_>>>()?1010					.try_into()1011					.map_err(|_| "too many properties")?,1012				owner,1013			});1014		}10151016		<Pallet<T>>::create_multiple_items(self, &caller, create_nft_data, &budget)1017			.map_err(dispatch_to_evm::<T>)?;1018		Ok(true)1019	}10201021	/// @notice Function to mint multiple tokens with the given tokenUris.1022	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1023	///  numbers and first number should be obtained with `nextTokenId` method1024	/// @param to The new owner1025	/// @param tokens array of pairs of token ID and token URI for minted tokens1026	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1027	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1028	fn mint_bulk_with_token_uri(1029		&mut self,1030		caller: Caller,1031		to: Address,1032		tokens: Vec<TokenUri>,1033	) -> Result<bool> {1034		let key = key::url();1035		let caller = T::CrossAccountId::from_eth(caller);1036		let to = T::CrossAccountId::from_eth(to);1037		let mut expected_index = <TokensMinted<T>>::get(self.id)1038			.checked_add(1)1039			.ok_or("item id overflow")?;1040		let budget = self1041			.recorder1042			.weight_calls_budget(<StructureWeight<T>>::find_parent());10431044		let mut data = Vec::with_capacity(tokens.len());1045		for TokenUri { id, uri } in tokens {1046			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1047			if id != expected_index {1048				return Err("item id should be next".into());1049			}1050			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10511052			let mut properties = CollectionPropertiesVec::default();1053			properties1054				.try_push(Property {1055					key: key.clone(),1056					value: uri1057						.into_bytes()1058						.try_into()1059						.map_err(|_| "token uri is too long")?,1060				})1061				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;10621063			data.push(CreateItemData::<T> {1064				properties,1065				owner: to.clone(),1066			});1067		}10681069		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1070			.map_err(dispatch_to_evm::<T>)?;1071		Ok(true)1072	}10731074	/// @notice Function to mint a token.1075	/// @param to The new owner crossAccountId1076	/// @param properties Properties of minted token1077	/// @return uint256 The id of the newly minted token1078	#[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1079	fn mint_cross(1080		&mut self,1081		caller: Caller,1082		to: eth::CrossAddress,1083		properties: Vec<eth::Property>,1084	) -> Result<U256> {1085		let token_id = <TokensMinted<T>>::get(self.id)1086			.checked_add(1)1087			.ok_or("item id overflow")?;10881089		let to = to.into_sub_cross_account::<T>()?;10901091		let properties = properties1092			.into_iter()1093			.map(eth::Property::try_into)1094			.collect::<Result<Vec<_>>>()?1095			.try_into()1096			.map_err(|_| Error::Revert("too many properties".to_string()))?;10971098		let caller = T::CrossAccountId::from_eth(caller);10991100		let budget = self1101			.recorder1102			.weight_calls_budget(<StructureWeight<T>>::find_parent());11031104		<Pallet<T>>::create_item(1105			self,1106			&caller,1107			CreateItemData::<T> {1108				properties,1109				owner: to,1110			},1111			&budget,1112		)1113		.map_err(dispatch_to_evm::<T>)?;11141115		Ok(token_id.into())1116	}11171118	/// @notice Returns collection helper contract address1119	fn collection_helper_address(&self) -> Address {1120		T::ContractAddress::get()1121	}1122}11231124#[solidity_interface(1125	name = UniqueNFT,1126	is(1127		ERC721,1128		ERC721Enumerable,1129		ERC721UniqueExtensions,1130		ERC721UniqueMintable,1131		ERC721Burnable,1132		ERC721Metadata(if(this.flags.erc721metadata)),1133		Collection(via(common_mut returns CollectionHandle<T>)),1134		TokenProperties,1135	),1136	enum(derive(PreDispatch)),1137)]1138impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11391140// Not a tests, but code generators1141generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);1142generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);11431144impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>1145where1146	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1147{1148	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");11491150	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {1151		call::<T, UniqueNFTCall<T>, _, _>(handle, self)1152	}1153}
modifiedpallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth
--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -800,7 +800,7 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x307b061a
+/// @dev the ERC-165 identifier for this interface is 0x9b397d16
 contract ERC721UniqueExtensions is Dummy, ERC165 {
 	/// @notice A descriptive name for a collection of NFTs in this contract
 	/// @dev EVM selector for this function is: 0x06fdde03,
@@ -997,6 +997,17 @@
 	// 	return false;
 	// }
 
+	/// @notice Function to mint a token.
+	/// @param data Array of pairs of token owner and token's properties for minted token
+	/// @dev EVM selector for this function is: 0xab427b0c,
+	///  or in textual repr: mintBulkCross(((address,uint256),(string,bytes)[])[])
+	function mintBulkCross(MintTokenData[] memory data) public returns (bool) {
+		require(false, stub_error);
+		data;
+		dummy = 0;
+		return false;
+	}
+
 	// /// @notice Function to mint multiple tokens with the given tokenUris.
 	// /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
 	// ///  numbers and first number should be obtained with `nextTokenId` method
@@ -1044,6 +1055,14 @@
 	string uri;
 }
 
+/// Token minting parameters
+struct MintTokenData {
+	/// Minted token owner
+	CrossAddress owner;
+	/// Minted token properties
+	Property[] properties;
+}
+
 /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 /// @dev See https://eips.ethereum.org/EIPS/eip-721
 /// @dev the ERC-165 identifier for this interface is 0x780e9d63
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -26,7 +26,7 @@
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
 };
-use evm_coder::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};
+use evm_coder::{abi::AbiType, AbiCoder, ToLog, generate_stubgen, solidity_interface, types::*};
 use frame_support::{BoundedBTreeMap, BoundedVec};
 use pallet_common::{
 	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
@@ -71,6 +71,24 @@
 	},
 }
 
+/// Token minting parameters
+#[derive(AbiCoder, Default, Debug)]
+pub struct OwnerPieces {
+	/// Minted token owner
+	pub owner: eth::CrossAddress,
+	/// Number of token pieces
+	pub pieces: u128,
+}
+
+/// Token minting parameters
+#[derive(AbiCoder, Default, Debug)]
+pub struct MintTokenData {
+	/// Minted token owner and number of pieces
+	pub owners: Vec<OwnerPieces>,
+	/// Minted token properties
+	pub properties: Vec<eth::Property>,
+}
+
 /// @title A contract that allows to set and delete token properties and change token property permissions.
 #[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]
 impl<T: Config> RefungibleHandle<T> {
@@ -1021,6 +1039,55 @@
 		Ok(true)
 	}
 
+	/// @notice Function to mint a token.
+	/// @param tokenProperties Properties of minted token
+	#[weight(if token_properties.len() == 1 {
+		<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(token_properties.iter().next().unwrap().owners.len() as u32)
+	} else {
+		<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(token_properties.len() as u32)
+	} + <SelfWeightOf<T>>::set_token_properties(token_properties.len() as u32))]
+	fn mint_bulk_cross(
+		&mut self,
+		caller: Caller,
+		token_properties: Vec<MintTokenData>,
+	) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+		let has_multiple_tokens = token_properties.len() > 1;
+
+		let mut create_rft_data = Vec::with_capacity(token_properties.len());
+		for MintTokenData { owners, properties } in token_properties {
+			let has_multiple_owners = owners.len() > 1;
+			if has_multiple_tokens & has_multiple_owners {
+				return Err(
+					"creation of multiple tokens supported only if they have single owner each"
+						.into(),
+				);
+			}
+			let users: BoundedBTreeMap<_, _, _> = owners
+				.into_iter()
+				.map(|data| Ok((data.owner.into_sub_cross_account::<T>()?, data.pieces)))
+				.collect::<Result<BTreeMap<_, _>>>()?
+				.try_into()
+				.map_err(|_| "too many users")?;
+			create_rft_data.push(CreateItemData::<T> {
+				properties: properties
+					.into_iter()
+					.map(|property| property.try_into())
+					.collect::<Result<Vec<_>>>()?
+					.try_into()
+					.map_err(|_| "too many properties")?,
+				users,
+			});
+		}
+
+		<Pallet<T>>::create_multiple_items(self, &caller, create_rft_data, &budget)
+			.map_err(dispatch_to_evm::<T>)?;
+		Ok(true)
+	}
+
 	/// @notice Function to mint multiple tokens with the given tokenUris.
 	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
 	///  numbers and first number should be obtained with `nextTokenId` method
modifiedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -800,7 +800,7 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x95c0f66c
+/// @dev the ERC-165 identifier for this interface is 0x4abaabdb
 contract ERC721UniqueExtensions is Dummy, ERC165 {
 	/// @notice A descriptive name for a collection of NFTs in this contract
 	/// @dev EVM selector for this function is: 0x06fdde03,
@@ -986,6 +986,17 @@
 	// 	return false;
 	// }
 
+	/// @notice Function to mint a token.
+	/// @param tokenProperties Properties of minted token
+	/// @dev EVM selector for this function is: 0xdf7a5db7,
+	///  or in textual repr: mintBulkCross((((address,uint256),uint128)[],(string,bytes)[])[])
+	function mintBulkCross(MintTokenData[] memory tokenProperties) public returns (bool) {
+		require(false, stub_error);
+		tokenProperties;
+		dummy = 0;
+		return false;
+	}
+
 	// /// @notice Function to mint multiple tokens with the given tokenUris.
 	// /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
 	// ///  numbers and first number should be obtained with `nextTokenId` method
@@ -1045,6 +1056,22 @@
 	string uri;
 }
 
+/// Token minting parameters
+struct MintTokenData {
+	/// Minted token owner and number of pieces
+	OwnerPieces[] owners;
+	/// Minted token properties
+	Property[] properties;
+}
+
+/// Token minting parameters
+struct OwnerPieces {
+	/// Minted token owner
+	CrossAddress owner;
+	/// Number of token pieces
+	uint128 pieces;
+}
+
 /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 /// @dev See https://eips.ethereum.org/EIPS/eip-721
 /// @dev the ERC-165 identifier for this interface is 0x780e9d63
modifiedpallets/scheduler-v2/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/benchmarking.rs
+++ b/pallets/scheduler-v2/src/benchmarking.rs
@@ -136,8 +136,10 @@
 	let bound = EncodedCall::bound() as u32;
 	let mut len = match maybe_lookup_len {
 		Some(len) => {
-			len.min(<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2)
-				.max(bound) - 3
+			len.clamp(
+				bound,
+				<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2,
+			) - 3
 		}
 		None => bound.saturating_sub(4),
 	};
modifiedpallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth
--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -25,12 +25,12 @@
 }
 
 /// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x4135fff1
+/// @dev the ERC-165 identifier for this interface is 0x94e5af0d
 contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
 	/// Create a collection
 	/// @return address Address of the newly created collection
-	/// @dev EVM selector for this function is: 0xa765ee5b,
-	///  or in textual repr: createCollection(((address,uint256),string,string,string,uint8,uint8,(string,bytes)[],(string,(uint8,bool)[])[],(address,uint256)[],(bool,bool,address[]),(uint8,uint256)[],uint8))
+	/// @dev EVM selector for this function is: 0x72b5bea7,
+	///  or in textual repr: createCollection((string,string,string,uint8,uint8,(string,bytes)[],(string,(uint8,bool)[])[],(address,uint256)[],(bool,bool,address[]),(uint8,uint256)[],(address,uint256),uint8))
 	function createCollection(CreateCollectionData memory data) public payable returns (address) {
 		require(false, stub_error);
 		data;
@@ -170,8 +170,6 @@
 
 /// Collection properties
 struct CreateCollectionData {
-	/// Collection sponsor
-	CrossAddress pending_sponsor;
 	/// Collection name
 	string name;
 	/// Collection description
@@ -192,11 +190,12 @@
 	CollectionNestingAndPermission nesting_settings;
 	/// Collection limits
 	CollectionLimitValue[] limits;
+	/// Collection sponsor
+	CrossAddress pending_sponsor;
 	/// Extra collection flags
 	CollectionFlags flags;
 }
 
-/// Cross account struct
 type CollectionFlags is uint8;
 
 library CollectionFlagsLib {
@@ -207,13 +206,19 @@
 	/// External collections can't be managed using `unique` api
 	CollectionFlags constant externalField = CollectionFlags.wrap(1);
 
-	/// Reserved bits
+	/// Reserved flags
 	function reservedField(uint8 value) public pure returns (CollectionFlags) {
 		require(value < 1 << 5, "out of bound value");
 		return CollectionFlags.wrap(value << 1);
 	}
 }
 
+/// Cross account struct
+struct CrossAddress {
+	address eth;
+	uint256 sub;
+}
+
 /// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
 struct CollectionLimitValue {
 	CollectionLimitField field;
@@ -250,12 +255,6 @@
 	bool collection_admin;
 	/// If set - only tokens from specified collections can be nested.
 	address[] restricted;
-}
-
-/// Cross account struct
-struct CrossAddress {
-	address eth;
-	uint256 sub;
 }
 
 /// Ethereum representation of Token Property Permissions.
@@ -292,10 +291,10 @@
 
 /// Type of tokens in collection
 enum CollectionMode {
-	/// Fungible
-	Fungible,
 	/// Nonfungible
 	Nonfungible,
+	/// Fungible
+	Fungible,
 	/// Refungible
 	Refungible
 }
modifiedruntime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -242,6 +242,7 @@
 			BurnFrom { .. }
 			| BurnFromCross { .. }
 			| MintBulk { .. }
+			| MintBulkCross { .. }
 			| MintBulkWithTokenUri { .. } => None,
 
 			MintCross { .. } => withdraw_create_item::<T>(
modifiedruntime/common/tests/mod.rsdiffbeforeafterboth
--- a/runtime/common/tests/mod.rs
+++ b/runtime/common/tests/mod.rs
@@ -33,7 +33,7 @@
 const PARA_ID: u32 = 2037;
 
 fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
-	TPublic::Pair::from_string(&format!("//{}", seed), None)
+	TPublic::Pair::from_string(&format!("//{seed}"), None)
 		.expect("static values are valid; qed")
 		.public()
 }
modifiedtests/src/eth/abi/nonFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -469,6 +469,39 @@
     "inputs": [
       {
         "components": [
+          {
+            "components": [
+              { "internalType": "address", "name": "eth", "type": "address" },
+              { "internalType": "uint256", "name": "sub", "type": "uint256" }
+            ],
+            "internalType": "struct CrossAddress",
+            "name": "owner",
+            "type": "tuple"
+          },
+          {
+            "components": [
+              { "internalType": "string", "name": "key", "type": "string" },
+              { "internalType": "bytes", "name": "value", "type": "bytes" }
+            ],
+            "internalType": "struct Property[]",
+            "name": "properties",
+            "type": "tuple[]"
+          }
+        ],
+        "internalType": "struct MintTokenData[]",
+        "name": "data",
+        "type": "tuple[]"
+      }
+    ],
+    "name": "mintBulkCross",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "components": [
           { "internalType": "address", "name": "eth", "type": "address" },
           { "internalType": "uint256", "name": "sub", "type": "uint256" }
         ],
modifiedtests/src/eth/abi/reFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -451,6 +451,55 @@
     "inputs": [
       {
         "components": [
+          {
+            "components": [
+              {
+                "components": [
+                  {
+                    "internalType": "address",
+                    "name": "eth",
+                    "type": "address"
+                  },
+                  {
+                    "internalType": "uint256",
+                    "name": "sub",
+                    "type": "uint256"
+                  }
+                ],
+                "internalType": "struct CrossAddress",
+                "name": "owner",
+                "type": "tuple"
+              },
+              { "internalType": "uint128", "name": "pieces", "type": "uint128" }
+            ],
+            "internalType": "struct OwnerPieces[]",
+            "name": "owners",
+            "type": "tuple[]"
+          },
+          {
+            "components": [
+              { "internalType": "string", "name": "key", "type": "string" },
+              { "internalType": "bytes", "name": "value", "type": "bytes" }
+            ],
+            "internalType": "struct Property[]",
+            "name": "properties",
+            "type": "tuple[]"
+          }
+        ],
+        "internalType": "struct MintTokenData[]",
+        "name": "tokenProperties",
+        "type": "tuple[]"
+      }
+    ],
+    "name": "mintBulkCross",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "components": [
           { "internalType": "address", "name": "eth", "type": "address" },
           { "internalType": "uint256", "name": "sub", "type": "uint256" }
         ],
modifiedtests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -20,12 +20,12 @@
 }
 
 /// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x4135fff1
+/// @dev the ERC-165 identifier for this interface is 0x94e5af0d
 interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
 	/// Create a collection
 	/// @return address Address of the newly created collection
-	/// @dev EVM selector for this function is: 0xa765ee5b,
-	///  or in textual repr: createCollection(((address,uint256),string,string,string,uint8,uint8,(string,bytes)[],(string,(uint8,bool)[])[],(address,uint256)[],(bool,bool,address[]),(uint8,uint256)[],uint8))
+	/// @dev EVM selector for this function is: 0x72b5bea7,
+	///  or in textual repr: createCollection((string,string,string,uint8,uint8,(string,bytes)[],(string,(uint8,bool)[])[],(address,uint256)[],(bool,bool,address[]),(uint8,uint256)[],(address,uint256),uint8))
 	function createCollection(CreateCollectionData memory data) external payable returns (address);
 
 	/// Create an NFT collection
@@ -103,8 +103,6 @@
 
 /// Collection properties
 struct CreateCollectionData {
-	/// Collection sponsor
-	CrossAddress pending_sponsor;
 	/// Collection name
 	string name;
 	/// Collection description
@@ -125,11 +123,12 @@
 	CollectionNestingAndPermission nesting_settings;
 	/// Collection limits
 	CollectionLimitValue[] limits;
+	/// Collection sponsor
+	CrossAddress pending_sponsor;
 	/// Extra collection flags
 	CollectionFlags flags;
 }
 
-/// Cross account struct
 type CollectionFlags is uint8;
 
 library CollectionFlagsLib {
@@ -140,13 +139,19 @@
 	/// External collections can't be managed using `unique` api
 	CollectionFlags constant externalField = CollectionFlags.wrap(1);
 
-	/// Reserved bits
+	/// Reserved flags
 	function reservedField(uint8 value) public pure returns (CollectionFlags) {
 		require(value < 1 << 5, "out of bound value");
 		return CollectionFlags.wrap(value << 1);
 	}
 }
 
+/// Cross account struct
+struct CrossAddress {
+	address eth;
+	uint256 sub;
+}
+
 /// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
 struct CollectionLimitValue {
 	CollectionLimitField field;
@@ -183,12 +188,6 @@
 	bool collection_admin;
 	/// If set - only tokens from specified collections can be nested.
 	address[] restricted;
-}
-
-/// Cross account struct
-struct CrossAddress {
-	address eth;
-	uint256 sub;
 }
 
 /// Ethereum representation of Token Property Permissions.
@@ -225,10 +224,10 @@
 
 /// Type of tokens in collection
 enum CollectionMode {
-	/// Fungible
-	Fungible,
 	/// Nonfungible
 	Nonfungible,
+	/// Fungible
+	Fungible,
 	/// Refungible
 	Refungible
 }
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -551,7 +551,7 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x307b061a
+/// @dev the ERC-165 identifier for this interface is 0x9b397d16
 interface ERC721UniqueExtensions is Dummy, ERC165 {
 	/// @notice A descriptive name for a collection of NFTs in this contract
 	/// @dev EVM selector for this function is: 0x06fdde03,
@@ -674,6 +674,12 @@
 	// ///  or in textual repr: mintBulk(address,uint256[])
 	// function mintBulk(address to, uint256[] memory tokenIds) external returns (bool);
 
+	/// @notice Function to mint a token.
+	/// @param data Array of pairs of token owner and token's properties for minted token
+	/// @dev EVM selector for this function is: 0xab427b0c,
+	///  or in textual repr: mintBulkCross(((address,uint256),(string,bytes)[])[])
+	function mintBulkCross(MintTokenData[] memory data) external returns (bool);
+
 	// /// @notice Function to mint multiple tokens with the given tokenUris.
 	// /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
 	// ///  numbers and first number should be obtained with `nextTokenId` method
@@ -705,6 +711,14 @@
 	string uri;
 }
 
+/// Token minting parameters
+struct MintTokenData {
+	/// Minted token owner
+	CrossAddress owner;
+	/// Minted token properties
+	Property[] properties;
+}
+
 /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 /// @dev See https://eips.ethereum.org/EIPS/eip-721
 /// @dev the ERC-165 identifier for this interface is 0x780e9d63
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -551,7 +551,7 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x95c0f66c
+/// @dev the ERC-165 identifier for this interface is 0x4abaabdb
 interface ERC721UniqueExtensions is Dummy, ERC165 {
 	/// @notice A descriptive name for a collection of NFTs in this contract
 	/// @dev EVM selector for this function is: 0x06fdde03,
@@ -668,6 +668,12 @@
 	// ///  or in textual repr: mintBulk(address,uint256[])
 	// function mintBulk(address to, uint256[] memory tokenIds) external returns (bool);
 
+	/// @notice Function to mint a token.
+	/// @param tokenProperties Properties of minted token
+	/// @dev EVM selector for this function is: 0xdf7a5db7,
+	///  or in textual repr: mintBulkCross((((address,uint256),uint128)[],(string,bytes)[])[])
+	function mintBulkCross(MintTokenData[] memory tokenProperties) external returns (bool);
+
 	// /// @notice Function to mint multiple tokens with the given tokenUris.
 	// /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
 	// ///  numbers and first number should be obtained with `nextTokenId` method
@@ -706,6 +712,22 @@
 	string uri;
 }
 
+/// Token minting parameters
+struct MintTokenData {
+	/// Minted token owner and number of pieces
+	OwnerPieces[] owners;
+	/// Minted token properties
+	Property[] properties;
+}
+
+/// Token minting parameters
+struct OwnerPieces {
+	/// Minted token owner
+	CrossAddress owner;
+	/// Number of token pieces
+	uint128 pieces;
+}
+
 /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 /// @dev See https://eips.ethereum.org/EIPS/eip-721
 /// @dev the ERC-165 identifier for this interface is 0x780e9d63
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -18,6 +18,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {Contract} from 'web3-eth-contract';
 import {ITokenPropertyPermission} from '../util/playgrounds/types';
+import {CREATE_COLLECTION_DATA_DEFAULTS, CollectionMode, CreateCollectionData, TokenPermissionField} from './util/playgrounds/types';
 
 describe('Check ERC721 token URI for NFT', () => {
   let donor: IKeyringPair;
@@ -197,6 +198,96 @@
     }
   });
 
+  itEth('Can perform mintBulkCross()', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const callerCross = helper.ethCrossAccount.fromAddress(caller);
+    const receiver = helper.eth.createAccount();
+    const receiverCross = helper.ethCrossAccount.fromAddress(receiver);
+
+    const permissions = [
+      {code: TokenPermissionField.Mutable, value: true},
+      {code: TokenPermissionField.TokenOwner, value: true},
+      {code: TokenPermissionField.CollectionAdmin, value: true},
+    ];
+    const {collectionAddress} = await helper.eth.createCollection(
+      caller,
+      {
+        ...CREATE_COLLECTION_DATA_DEFAULTS,
+        name: 'A',
+        description: 'B',
+        tokenPrefix: 'C',
+        collectionMode: 'nft',
+        adminList: [callerCross],
+        tokenPropertyPermissions: [
+          {key: 'key_0_0', permissions},
+          {key: 'key_1_0', permissions},
+          {key: 'key_1_1', permissions},
+          {key: 'key_2_0', permissions},
+          {key: 'key_2_1', permissions},
+          {key: 'key_2_2', permissions},
+        ],
+      },
+    ).send();
+
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', caller);
+    {
+      const nextTokenId = await contract.methods.nextTokenId().call();
+      expect(nextTokenId).to.be.equal('1');
+      const result = await contract.methods.mintBulkCross([
+        {
+          owner: receiverCross,
+          properties: [
+            {key: 'key_0_0', value: Buffer.from('value_0_0')},
+          ],
+        },
+        {
+          owner: receiverCross,
+          properties: [
+            {key: 'key_1_0', value: Buffer.from('value_1_0')},
+            {key: 'key_1_1', value: Buffer.from('value_1_1')},
+          ],
+        },
+        {
+          owner: receiverCross,
+          properties: [
+            {key: 'key_2_0', value: Buffer.from('value_2_0')},
+            {key: 'key_2_1', value: Buffer.from('value_2_1')},
+            {key: 'key_2_2', value: Buffer.from('value_2_2')},
+          ],
+        },
+      ]).send({from: caller});
+      const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.tokenId - b.returnValues.tokenId);
+      const bulkSize = 3;
+      for(let i = 0; i < bulkSize; i++) {
+        const event = events[i];
+        expect(event.address).to.equal(collectionAddress);
+        expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+        expect(event.returnValues.to).to.equal(receiver);
+        expect(event.returnValues.tokenId).to.equal(`${+nextTokenId + i}`);
+      }
+
+      const properties = [
+        await contract.methods.properties(+nextTokenId, []).call(),
+        await contract.methods.properties(+nextTokenId + 1, []).call(),
+        await contract.methods.properties(+nextTokenId + 2, []).call(),
+      ];
+      expect(properties).to.be.deep.equal([
+        [
+          ['key_0_0', helper.getWeb3().utils.toHex('value_0_0')],
+        ],
+        [
+          ['key_1_0', helper.getWeb3().utils.toHex('value_1_0')],
+          ['key_1_1', helper.getWeb3().utils.toHex('value_1_1')],
+        ],
+        [
+          ['key_2_0', helper.getWeb3().utils.toHex('value_2_0')],
+          ['key_2_1', helper.getWeb3().utils.toHex('value_2_1')],
+          ['key_2_2', helper.getWeb3().utils.toHex('value_2_2')],
+        ],
+      ]);
+    }
+  });
+
   itEth('Can perform burn()', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
 
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -18,6 +18,7 @@
 import {expect, itEth, usingEthPlaygrounds} from './util';
 import {IKeyringPair} from '@polkadot/types/types';
 import {ITokenPropertyPermission} from '../util/playgrounds/types';
+import {CREATE_COLLECTION_DATA_DEFAULTS, TokenPermissionField} from './util/playgrounds/types';
 
 describe('Refungible: Plain calls', () => {
   let donor: IKeyringPair;
@@ -125,6 +126,169 @@
     }
   });
 
+  itEth('Can perform mintBulkCross() with multiple tokens', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const callerCross = helper.ethCrossAccount.fromAddress(caller);
+    const receiver = helper.eth.createAccount();
+    const receiverCross = helper.ethCrossAccount.fromAddress(receiver);
+
+    const permissions = [
+      {code: TokenPermissionField.Mutable, value: true},
+      {code: TokenPermissionField.TokenOwner, value: true},
+      {code: TokenPermissionField.CollectionAdmin, value: true},
+    ];
+    const {collectionAddress} = await helper.eth.createCollection(
+      caller,
+      {
+        ...CREATE_COLLECTION_DATA_DEFAULTS,
+        name: 'A',
+        description: 'B',
+        tokenPrefix: 'C',
+        collectionMode: 'rft',
+        adminList: [callerCross],
+        tokenPropertyPermissions: [
+          {key: 'key_0_0', permissions},
+          {key: 'key_1_0', permissions},
+          {key: 'key_1_1', permissions},
+          {key: 'key_2_0', permissions},
+          {key: 'key_2_1', permissions},
+          {key: 'key_2_2', permissions},
+        ],
+      },
+    ).send();
+
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
+    const nextTokenId = await contract.methods.nextTokenId().call();
+    expect(nextTokenId).to.be.equal('1');
+    const result = await contract.methods.mintBulkCross([
+      {
+        owners: [{
+          owner: receiverCross,
+          pieces: 1,
+        }],
+        properties: [
+          {key: 'key_0_0', value: Buffer.from('value_0_0')},
+        ],
+      },
+      {
+        owners: [{
+          owner: receiverCross,
+          pieces: 2,
+        }],
+        properties: [
+          {key: 'key_1_0', value: Buffer.from('value_1_0')},
+          {key: 'key_1_1', value: Buffer.from('value_1_1')},
+        ],
+      },
+      {
+        owners: [{
+          owner: receiverCross,
+          pieces: 1,
+        }],
+        properties: [
+          {key: 'key_2_0', value: Buffer.from('value_2_0')},
+          {key: 'key_2_1', value: Buffer.from('value_2_1')},
+          {key: 'key_2_2', value: Buffer.from('value_2_2')},
+        ],
+      },
+    ]).send({from: caller});
+    const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.tokenId - b.returnValues.tokenId);
+    const bulkSize = 3;
+    for(let i = 0; i < bulkSize; i++) {
+      const event = events[i];
+      expect(event.address).to.equal(collectionAddress);
+      expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+      expect(event.returnValues.to).to.equal(receiver);
+      expect(event.returnValues.tokenId).to.equal(`${+nextTokenId + i}`);
+    }
+
+    const properties = [
+      await contract.methods.properties(+nextTokenId, []).call(),
+      await contract.methods.properties(+nextTokenId + 1, []).call(),
+      await contract.methods.properties(+nextTokenId + 2, []).call(),
+    ];
+    expect(properties).to.be.deep.equal([
+      [
+        ['key_0_0', helper.getWeb3().utils.toHex('value_0_0')],
+      ],
+      [
+        ['key_1_0', helper.getWeb3().utils.toHex('value_1_0')],
+        ['key_1_1', helper.getWeb3().utils.toHex('value_1_1')],
+      ],
+      [
+        ['key_2_0', helper.getWeb3().utils.toHex('value_2_0')],
+        ['key_2_1', helper.getWeb3().utils.toHex('value_2_1')],
+        ['key_2_2', helper.getWeb3().utils.toHex('value_2_2')],
+      ],
+    ]);
+  });
+
+  itEth('Can perform mintBulkCross() with multiple owners', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const callerCross = helper.ethCrossAccount.fromAddress(caller);
+    const receiver = helper.eth.createAccount();
+    const receiverCross = helper.ethCrossAccount.fromAddress(receiver);
+    const receiver2 = helper.eth.createAccount();
+    const receiver2Cross = helper.ethCrossAccount.fromAddress(receiver2);
+
+    const permissions = [
+      {code: TokenPermissionField.Mutable, value: true},
+      {code: TokenPermissionField.TokenOwner, value: true},
+      {code: TokenPermissionField.CollectionAdmin, value: true},
+    ];
+    const {collectionAddress} = await helper.eth.createCollection(
+      caller,
+      {
+        ...CREATE_COLLECTION_DATA_DEFAULTS,
+        name: 'A',
+        description: 'B',
+        tokenPrefix: 'C',
+        collectionMode: 'rft',
+        adminList: [callerCross],
+        tokenPropertyPermissions: [
+          {key: 'key_2_0', permissions},
+          {key: 'key_2_1', permissions},
+          {key: 'key_2_2', permissions},
+        ],
+      },
+    ).send();
+
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
+    const nextTokenId = await contract.methods.nextTokenId().call();
+    expect(nextTokenId).to.be.equal('1');
+    const result = await contract.methods.mintBulkCross([{
+      owners: [
+        {
+          owner: receiverCross,
+          pieces: 1,
+        },
+        {
+          owner: receiver2Cross,
+          pieces: 2,
+        },
+      ],
+      properties: [
+        {key: 'key_2_0', value: Buffer.from('value_2_0')},
+        {key: 'key_2_1', value: Buffer.from('value_2_1')},
+        {key: 'key_2_2', value: Buffer.from('value_2_2')},
+      ],
+    }]).send({from: caller});
+    const event = result.events.Transfer;
+    expect(event.address).to.equal(collectionAddress);
+    expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.to).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
+    expect(event.returnValues.tokenId).to.equal(`${+nextTokenId}`);
+
+    const properties = [
+      await contract.methods.properties(+nextTokenId, []).call(),
+    ];
+    expect(properties).to.be.deep.equal([[
+      ['key_2_0', helper.getWeb3().utils.toHex('value_2_0')],
+      ['key_2_1', helper.getWeb3().utils.toHex('value_2_1')],
+      ['key_2_2', helper.getWeb3().utils.toHex('value_2_2')],
+    ]]);
+  });
+
   itEth('Can perform setApprovalForAll()', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const operator = helper.eth.createAccount();
@@ -786,4 +950,70 @@
 
     await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;
   });
+
+  itEth('[negative] Can perform mintBulkCross() with multiple owners and multiple tokens', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const callerCross = helper.ethCrossAccount.fromAddress(caller);
+    const receiver = helper.eth.createAccount();
+    const receiverCross = helper.ethCrossAccount.fromAddress(receiver);
+    const receiver2 = helper.eth.createAccount();
+    const receiver2Cross = helper.ethCrossAccount.fromAddress(receiver2);
+
+    const permissions = [
+      {code: TokenPermissionField.Mutable, value: true},
+      {code: TokenPermissionField.TokenOwner, value: true},
+      {code: TokenPermissionField.CollectionAdmin, value: true},
+    ];
+    const {collectionAddress} = await helper.eth.createCollection(
+      caller,
+      {
+        ...CREATE_COLLECTION_DATA_DEFAULTS,
+        name: 'A',
+        description: 'B',
+        tokenPrefix: 'C',
+        collectionMode: 'rft',
+        adminList: [callerCross],
+        tokenPropertyPermissions: [
+          {key: 'key_0_0', permissions},
+          {key: 'key_2_0', permissions},
+          {key: 'key_2_1', permissions},
+          {key: 'key_2_2', permissions},
+        ],
+      },
+    ).send();
+
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
+    const nextTokenId = await contract.methods.nextTokenId().call();
+    expect(nextTokenId).to.be.equal('1');
+    const createData = [
+      {
+        owners: [{
+          owner: receiverCross,
+          pieces: 1,
+        }],
+        properties: [
+          {key: 'key_0_0', value: Buffer.from('value_0_0')},
+        ],
+      },
+      {
+        owners: [
+          {
+            owner: receiverCross,
+            pieces: 1,
+          },
+          {
+            owner: receiver2Cross,
+            pieces: 2,
+          },
+        ],
+        properties: [
+          {key: 'key_2_0', value: Buffer.from('value_2_0')},
+          {key: 'key_2_1', value: Buffer.from('value_2_1')},
+          {key: 'key_2_2', value: Buffer.from('value_2_2')},
+        ],
+      },
+    ];
+
+    await expect(contract.methods.mintBulkCross(createData).call({from: caller})).to.be.rejectedWith('creation of multiple tokens supported only if they have single owner each');
+  });
 });