git.delta.rocks / unique-network / refs/commits / 8dd063b578e3

difftreelog

Merge pull request #869 from UniqueNetwork/feature/generalize_2_methods

Yaroslav Bolyukin2023-02-03parents: #f1a5ba7 #ccafa37.patch.diff
in: master
Feature/generalize_2_methods

34 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6361,7 +6361,7 @@
 
 [[package]]
 name = "pallet-fungible"
-version = "0.1.9"
+version = "0.1.10"
 dependencies = [
  "evm-coder",
  "frame-benchmarking",
@@ -6774,7 +6774,7 @@
 
 [[package]]
 name = "pallet-refungible"
-version = "0.2.12"
+version = "0.2.13"
 dependencies = [
  "evm-coder",
  "frame-benchmarking",
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -18,7 +18,10 @@
 
 use alloc::format;
 use sp_std::{vec, vec::Vec};
-use evm_coder::{AbiCoder, types::Address};
+use evm_coder::{
+	AbiCoder,
+	types::{Address, String},
+};
 pub use pallet_evm::{Config, account::CrossAccountId};
 use sp_core::{H160, U256};
 use up_data_structs::CollectionId;
@@ -390,6 +393,16 @@
 	}
 }
 
+/// Data for creation token with uri.
+#[derive(Debug, AbiCoder)]
+pub struct TokenUri {
+	/// Id of new token.
+	pub id: U256,
+
+	/// Uri of new token.
+	pub uri: String,
+}
+
 /// Nested collections.
 #[derive(Debug, Default, AbiCoder)]
 pub struct CollectionNesting {
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -66,10 +66,11 @@
 	ensure,
 	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},
 	dispatch::Pays,
-	transactional,
+	transactional, fail,
 };
 use pallet_evm::GasWeightMapping;
 use up_data_structs::{
+	AccessMode,
 	COLLECTION_NUMBER_LIMIT,
 	Collection,
 	RpcCollection,
@@ -124,6 +125,8 @@
 pub use pallet::*;
 use sp_core::H160;
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+
+use crate::erc::CollectionHelpersEvents;
 #[cfg(feature = "runtime-benchmarks")]
 pub mod benchmarking;
 pub mod dispatch;
@@ -1264,6 +1267,133 @@
 		Ok(())
 	}
 
+	/// A batch operation to add, edit or remove properties for a token.
+	/// It sets or removes a token's properties according to
+	/// `properties_updates` contents:
+	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
+	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.
+	///
+	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
+	/// - `is_token_create`: Indicates that method is called during token initialization.
+	///   Allows to bypass ownership check.
+	///
+	/// All affected properties should have `mutable` permission
+	/// to be **deleted** or to be **set more than once**,
+	/// and the sender should have permission to edit those properties.
+	///
+	/// This function fires an event for each property change.
+	/// In case of an error, all the changes (including the events) will be reverted
+	/// since the function is transactional.
+	pub fn modify_token_properties(
+		collection: &CollectionHandle<T>,
+		sender: &T::CrossAccountId,
+		token_id: TokenId,
+		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+		is_token_create: bool,
+		mut stored_properties: Properties,
+		is_token_owner: impl Fn() -> Result<bool, DispatchError>,
+		set_token_properties: impl FnOnce(Properties),
+	) -> DispatchResult {
+		let is_collection_admin = collection.is_owner_or_admin(sender);
+		let permissions = Self::property_permissions(collection.id);
+
+		let mut token_owner_result = None;
+		let mut is_token_owner = || -> Result<bool, DispatchError> {
+			*token_owner_result.get_or_insert_with(&is_token_owner)
+		};
+
+		for (key, value) in properties_updates {
+			let permission = permissions
+				.get(&key)
+				.cloned()
+				.unwrap_or_else(PropertyPermission::none);
+
+			let is_property_exists = stored_properties.get(&key).is_some();
+
+			match permission {
+				PropertyPermission { mutable: false, .. } if is_property_exists => {
+					return Err(<Error<T>>::NoPermission.into());
+				}
+
+				PropertyPermission {
+					collection_admin,
+					token_owner,
+					..
+				} => {
+					//TODO: investigate threats during public minting.
+					let is_token_create =
+						is_token_create && (collection_admin || token_owner) && value.is_some();
+					if !(is_token_create
+						|| (collection_admin && is_collection_admin)
+						|| (token_owner && is_token_owner()?))
+					{
+						fail!(<Error<T>>::NoPermission);
+					}
+				}
+			}
+
+			match value {
+				Some(value) => {
+					stored_properties
+						.try_set(key.clone(), value)
+						.map_err(<Error<T>>::from)?;
+
+					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));
+				}
+				None => {
+					stored_properties.remove(&key).map_err(<Error<T>>::from)?;
+
+					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));
+				}
+			}
+
+			<PalletEvm<T>>::deposit_log(
+				CollectionHelpersEvents::TokenChanged {
+					collection_id: eth::collection_id_to_address(collection.id),
+					token_id: token_id.into(),
+				}
+				.to_log(T::ContractAddress::get()),
+			);
+		}
+
+		set_token_properties(stored_properties);
+
+		Ok(())
+	}
+
+	/// Sets or unsets the approval of a given operator.
+	///
+	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.
+	/// - `owner`: Token owner
+	/// - `operator`: Operator
+	/// - `approve`: Should operator status be granted or revoked?
+	pub fn set_allowance_for_all(
+		collection: &CollectionHandle<T>,
+		owner: &T::CrossAccountId,
+		operator: &T::CrossAccountId,
+		approve: bool,
+		set_allowance: impl FnOnce(),
+		log: evm_coder::ethereum::Log,
+	) -> DispatchResult {
+		if collection.permissions.access() == AccessMode::AllowList {
+			collection.check_allowlist(owner)?;
+			collection.check_allowlist(operator)?;
+		}
+
+		Self::ensure_correct_receiver(operator)?;
+
+		set_allowance();
+
+		<PalletEvm<T>>::deposit_log(log);
+		Self::deposit_event(Event::ApprovedForAll(
+			collection.id,
+			owner.clone(),
+			operator.clone(),
+			approve,
+		));
+		Ok(())
+	}
+
 	/// Set collection property.
 	///
 	/// * `collection` - Collection handler.
modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/fungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/fungible/CHANGELOG.md
+++ b/pallets/fungible/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.10] - 2023-02-01
+
+### Added
+
+- The functions `allowanceCross` to `ERC20UniqueExtensions` interface.
+
 ## [0.1.9] - 2022-12-01
 
 ### Added
modifiedpallets/fungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -2,7 +2,7 @@
 edition = "2021"
 license = "GPLv3"
 name = "pallet-fungible"
-version = "0.1.9"
+version = "0.1.10"
 
 [dependencies]
 # Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -19,6 +19,7 @@
 extern crate alloc;
 use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
 use core::convert::TryInto;
+use evm_coder::AbiCoder;
 use evm_coder::{
 	abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,
 	weight,
@@ -27,6 +28,7 @@
 use pallet_common::{
 	CollectionHandle,
 	erc::{CommonEvmHandler, PrecompileResult, CollectionCall},
+	eth::CrossAddress,
 };
 use sp_std::vec::Vec;
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
@@ -57,6 +59,12 @@
 	},
 }
 
+#[derive(AbiCoder, Debug)]
+pub struct AmountForAddress {
+	to: Address,
+	amount: U256,
+}
+
 #[solidity_interface(name = ERC20, events(ERC20Events), expect_selector = 0x942e8b22)]
 impl<T: Config> FungibleHandle<T> {
 	fn name(&self) -> Result<String> {
@@ -161,6 +169,17 @@
 where
 	T::AccountId: From<[u8; 32]>,
 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	fn allowance_cross(&self, owner: CrossAddress, spender: CrossAddress) -> Result<U256> {
+		let owner = owner.into_sub_cross_account::<T>()?;
+		let spender = spender.into_sub_cross_account::<T>()?;
+
+		Ok(<Allowance<T>>::get((self.id, owner, spender)).into())
+	}
+
 	/// @notice A description for the collection.
 	fn description(&self) -> Result<String> {
 		Ok(decode_utf16(self.description.iter().copied())
@@ -169,12 +188,7 @@
 	}
 
 	#[weight(<SelfWeightOf<T>>::create_item())]
-	fn mint_cross(
-		&mut self,
-		caller: Caller,
-		to: pallet_common::eth::CrossAddress,
-		amount: U256,
-	) -> Result<bool> {
+	fn mint_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = to.into_sub_cross_account::<T>()?;
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
@@ -190,7 +204,7 @@
 	fn approve_cross(
 		&mut self,
 		caller: Caller,
-		spender: pallet_common::eth::CrossAddress,
+		spender: CrossAddress,
 		amount: U256,
 	) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
@@ -231,7 +245,7 @@
 	fn burn_from_cross(
 		&mut self,
 		caller: Caller,
-		from: pallet_common::eth::CrossAddress,
+		from: CrossAddress,
 		amount: U256,
 	) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
@@ -249,14 +263,14 @@
 	/// Mint tokens for multiple accounts.
 	/// @param amounts array of pairs of account address and amount
 	#[weight(<SelfWeightOf<T>>::create_multiple_items_ex(amounts.len() as u32))]
-	fn mint_bulk(&mut self, caller: Caller, amounts: Vec<(Address, U256)>) -> Result<bool> {
+	fn mint_bulk(&mut self, caller: Caller, amounts: Vec<AmountForAddress>) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let budget = self
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 		let amounts = amounts
 			.into_iter()
-			.map(|(to, amount)| {
+			.map(|AmountForAddress { to, amount }| {
 				Ok((
 					T::CrossAccountId::from_eth(to),
 					amount.try_into().map_err(|_| "amount overflow")?,
@@ -270,12 +284,7 @@
 	}
 
 	#[weight(<SelfWeightOf<T>>::transfer())]
-	fn transfer_cross(
-		&mut self,
-		caller: Caller,
-		to: pallet_common::eth::CrossAddress,
-		amount: U256,
-	) -> Result<bool> {
+	fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = to.into_sub_cross_account::<T>()?;
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
@@ -291,8 +300,8 @@
 	fn transfer_from_cross(
 		&mut self,
 		caller: Caller,
-		from: pallet_common::eth::CrossAddress,
-		to: pallet_common::eth::CrossAddress,
+		from: CrossAddress,
+		to: CrossAddress,
 		amount: U256,
 	) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -165,8 +165,8 @@
 	pub type Allowance<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
-			Key<Blake2_128, T::CrossAccountId>,
-			Key<Blake2_128Concat, T::CrossAccountId>,
+			Key<Blake2_128, T::CrossAccountId>,       // Owner
+			Key<Blake2_128Concat, T::CrossAccountId>, // Spender
 		),
 		Value = u128,
 		QueryKind = ValueQuery,
modifiedpallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterboth

binary blob — no preview

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

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
@@ -36,8 +36,22 @@
 	}
 }
 
-/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
+/// @dev the ERC-165 identifier for this interface is 0x01d536fc
 contract ERC20UniqueExtensions is Dummy, ERC165 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	/// @dev EVM selector for this function is: 0xe0af4bd7,
+	///  or in textual repr: allowanceCross((address,uint256),(address,uint256))
+	function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) public view returns (uint256) {
+		require(false, stub_error);
+		owner;
+		spender;
+		dummy;
+		return 0;
+	}
+
 	// /// @dev Function that burns an amount of the token of a given account,
 	// /// deducting from the sender's allowance for said account.
 	// /// @param from The account whose tokens will be burnt.
modifiedpallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedruntime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -341,7 +341,9 @@
 			ERC165Call(_, _) => None,
 
 			// Not sponsored
-			BurnFrom { .. } | BurnFromCross { .. } | Repartition { .. } => None,
+			AllowanceCross { .. } | BurnFrom { .. } | BurnFromCross { .. } | Repartition { .. } => {
+				None
+			}
 
 			TransferCross { .. } | TransferFromCross { .. } => {
 				let RefungibleTokenHandle(handle, token_id) = token;
modifiedtests/src/eth/abi/fungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/fungible.json
+++ b/tests/src/eth/abi/fungible.json
@@ -101,6 +101,32 @@
           { "internalType": "uint256", "name": "sub", "type": "uint256" }
         ],
         "internalType": "struct CrossAddress",
+        "name": "owner",
+        "type": "tuple"
+      },
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "spender",
+        "type": "tuple"
+      }
+    ],
+    "name": "allowanceCross",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
         "name": "user",
         "type": "tuple"
       }
@@ -408,10 +434,10 @@
     "inputs": [
       {
         "components": [
-          { "internalType": "address", "name": "field_0", "type": "address" },
-          { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+          { "internalType": "address", "name": "to", "type": "address" },
+          { "internalType": "uint256", "name": "amount", "type": "uint256" }
         ],
-        "internalType": "struct Tuple9[]",
+        "internalType": "struct AmountForAddress[]",
         "name": "amounts",
         "type": "tuple[]"
       }
modifiedtests/src/eth/abi/reFungibleToken.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungibleToken.json
+++ b/tests/src/eth/abi/reFungibleToken.json
@@ -61,6 +61,32 @@
   },
   {
     "inputs": [
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "owner",
+        "type": "tuple"
+      },
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "spender",
+        "type": "tuple"
+      }
+    ],
+    "name": "allowanceCross",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
       { "internalType": "address", "name": "spender", "type": "address" },
       { "internalType": "uint256", "name": "amount", "type": "uint256" }
     ],
modifiedtests/src/eth/api/UniqueFungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -353,8 +353,16 @@
 	bytes value;
 }
 
-/// @dev the ERC-165 identifier for this interface is 0x65789571
+/// @dev the ERC-165 identifier for this interface is 0x85d7dea6
 interface ERC20UniqueExtensions is Dummy, ERC165 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	/// @dev EVM selector for this function is: 0xe0af4bd7,
+	///  or in textual repr: allowanceCross((address,uint256),(address,uint256))
+	function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) external view returns (uint256);
+
 	/// @notice A description for the collection.
 	/// @dev EVM selector for this function is: 0x7284e416,
 	///  or in textual repr: description()
@@ -390,7 +398,7 @@
 	/// @param amounts array of pairs of account address and amount
 	/// @dev EVM selector for this function is: 0x1acf2d55,
 	///  or in textual repr: mintBulk((address,uint256)[])
-	function mintBulk(Tuple9[] memory amounts) external returns (bool);
+	function mintBulk(AmountForAddress[] memory amounts) external returns (bool);
 
 	/// @dev EVM selector for this function is: 0x2ada85ff,
 	///  or in textual repr: transferCross((address,uint256),uint256)
@@ -410,10 +418,9 @@
 	function collectionHelperAddress() external view returns (address);
 }
 
-/// @dev anonymous struct
-struct Tuple9 {
-	address field_0;
-	uint256 field_1;
+struct AmountForAddress {
+	address to;
+	uint256 amount;
 }
 
 /// @dev the ERC-165 identifier for this interface is 0x40c10f19
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -644,7 +644,7 @@
 	// /// @param tokens array of pairs of token ID and token URI for minted tokens
 	// /// @dev EVM selector for this function is: 0x36543006,
 	// ///  or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
-	// function mintBulkWithTokenURI(address to, Tuple13[] memory tokens) external returns (bool);
+	// function mintBulkWithTokenURI(address to, TokenUri[] memory tokens) external returns (bool);
 
 	/// @notice Function to mint a token.
 	/// @param to The new owner crossAccountId
@@ -660,10 +660,12 @@
 	function collectionHelperAddress() external view returns (address);
 }
 
-/// @dev anonymous struct
-struct Tuple13 {
-	uint256 field_0;
-	string field_1;
+/// Data for creation token with uri.
+struct TokenUri {
+	/// Id of new token.
+	uint256 id;
+	/// Uri of new token.
+	string uri;
 }
 
 /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -638,7 +638,7 @@
 	// /// @param tokens array of pairs of token ID and token URI for minted tokens
 	// /// @dev EVM selector for this function is: 0x36543006,
 	// ///  or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
-	// function mintBulkWithTokenURI(address to, Tuple12[] memory tokens) external returns (bool);
+	// function mintBulkWithTokenURI(address to, TokenUri[] memory tokens) external returns (bool);
 
 	/// @notice Function to mint a token.
 	/// @param to The new owner crossAccountId
@@ -661,10 +661,12 @@
 	function collectionHelperAddress() external view returns (address);
 }
 
-/// @dev anonymous struct
-struct Tuple12 {
-	uint256 field_0;
-	string field_1;
+/// Data for creation token with uri.
+struct TokenUri {
+	/// Id of new token.
+	uint256 id;
+	/// Uri of new token.
+	string uri;
 }
 
 /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
modifiedtests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -23,8 +23,16 @@
 	function parentTokenId() external view returns (uint256);
 }
 
-/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
+/// @dev the ERC-165 identifier for this interface is 0x01d536fc
 interface ERC20UniqueExtensions is Dummy, ERC165 {
+	/// @dev Function to check the amount of tokens that an owner allowed to a spender.
+	/// @param owner crossAddress The address which owns the funds.
+	/// @param spender crossAddress The address which will spend the funds.
+	/// @return A uint256 specifying the amount of tokens still available for the spender.
+	/// @dev EVM selector for this function is: 0xe0af4bd7,
+	///  or in textual repr: allowanceCross((address,uint256),(address,uint256))
+	function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) external view returns (uint256);
+
 	// /// @dev Function that burns an amount of the token of a given account,
 	// /// deducting from the sender's allowance for said account.
 	// /// @param from The account whose tokens will be burnt.
modifiedtests/src/eth/fungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -134,6 +134,12 @@
       const allowance = await contract.methods.allowance(owner, spender).call();
       expect(+allowance).to.equal(100);
     }
+    {
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const spenderCross = helper.ethCrossAccount.fromAddress(spender);
+      const allowance = await contract.methods.allowanceCross(ownerCross, spenderCross).call();
+      expect(+allowance).to.equal(100);
+    }
   });
 
   itEth('Can perform approveCross()', async ({helper}) => {
modifiedtests/src/eth/proxy/UniqueNFTProxy.soldiffbeforeafterboth
--- a/tests/src/eth/proxy/UniqueNFTProxy.sol
+++ b/tests/src/eth/proxy/UniqueNFTProxy.sol
@@ -168,7 +168,7 @@
         return proxied.mintBulk(to, tokenIds);
     }
 
-    function mintBulkWithTokenURI(address to, Tuple6[] memory tokens)
+    function mintBulkWithTokenURI(address to, TokenUri[] memory tokens)
         external
         override
         returns (bool)
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -219,8 +219,16 @@
       await rftToken.methods.approve(operator, 15n).send({from: owner});
       await contract.methods.setApprovalForAll(operator, true).send({from: owner});
       await rftToken.methods.burnFrom(owner, 10n).send({from: operator});
+    }
+    {
       const allowance = await rftToken.methods.allowance(owner, operator).call();
-      expect(allowance).to.be.equal('5');
+      expect(+allowance).to.be.equal(5);
+    }
+    {
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const operatorCross = helper.ethCrossAccount.fromAddress(operator);
+      const allowance = await rftToken.methods.allowanceCross(ownerCross, operatorCross).call();
+      expect(+allowance).to.equal(5);
     }
   });