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

difftreelog

feature: make collection creation methods `payable`

Grigoriy Simonov2022-09-30parent: #fea73f4.patch.diff
in: master

19 files changed

modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -560,6 +560,7 @@
 	selector: u32,
 	args: Vec<MethodArg>,
 	has_normal_args: bool,
+	has_value_args: bool,
 	mutability: Mutability,
 	result: Type,
 	weight: Option<Expr>,
@@ -647,14 +648,20 @@
 			.unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));
 		let mut selector_str = camel_name.clone();
 		selector_str.push('(');
-		let mut has_normal_args = false;
-		for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {
-			if i != 0 {
-				selector_str.push(',');
+		let mut normal_args_count = 0u32;
+		let mut has_value_args = false;
+		for arg in args.iter() {
+			if arg.is_value() {
+				has_value_args = true;
+			} else if !arg.is_special() {
+				if normal_args_count != 0 {
+					selector_str.push(',');
+				}
+				write!(selector_str, "{}", arg.selector_ty()).unwrap();
+				normal_args_count = normal_args_count.saturating_add(1);
 			}
-			write!(selector_str, "{}", arg.selector_ty()).unwrap();
-			has_normal_args = true;
 		}
+		let has_normal_args = normal_args_count > 0;
 		selector_str.push(')');
 		let selector = fn_selector_str(&selector_str);
 
@@ -667,6 +674,7 @@
 			selector,
 			args,
 			has_normal_args,
+			has_value_args,
 			mutability,
 			result: result.clone(),
 			weight,
@@ -823,7 +831,7 @@
 		let docs = &self.docs;
 		let selector_str = &self.selector_str;
 		let selector = self.selector;
-
+		let is_payable = self.has_value_args;
 		quote! {
 			SolidityFunction {
 				docs: &[#(#docs),*],
@@ -831,6 +839,7 @@
 				selector: #selector,
 				name: #camel_name,
 				mutability: #mutability,
+				is_payable: #is_payable,
 				args: (
 					#(
 						#args,
modifiedcrates/evm-coder/src/solidity.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -422,6 +422,7 @@
 	pub args: A,
 	pub result: R,
 	pub mutability: SolidityMutability,
+	pub is_payable: bool,
 }
 impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {
 	fn solidity_name(
@@ -452,6 +453,9 @@
 			SolidityMutability::View => write!(writer, " view")?,
 			SolidityMutability::Mutable => {}
 		}
+		if self.is_payable {
+			write!(writer, " payable")?;
+		}
 		if !self.result.is_empty() {
 			write!(writer, " returns (")?;
 			self.result.solidity_name(writer, tc)?;
modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -78,6 +78,7 @@
 	/// * `data` - Description of the created collection.
 	fn create(
 		sender: T::CrossAccountId,
+		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
 	) -> Result<CollectionId, DispatchError>;
 
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -866,6 +866,7 @@
 	/// * `flags` - Extra flags to store.
 	pub fn init_collection(
 		owner: T::CrossAccountId,
+		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
 		flags: CollectionFlags,
 	) -> Result<CollectionId, DispatchError> {
@@ -939,7 +940,7 @@
 				),
 			);
 			<T as Config>::Currency::settle(
-				owner.as_sub(),
+				payer.as_sub(),
 				imbalance,
 				WithdrawReasons::TRANSFER,
 				ExistenceRequirement::KeepAlive,
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -309,9 +309,10 @@
 				mode: CollectionMode::Fungible(md.decimals),
 				..Default::default()
 			};
-
+			let owner = T::CrossAccountId::from_sub(owner);
 			let bounded_collection_id = <PalletFungible<T>>::init_foreign_collection(
-				CrossAccountId::from_sub(owner),
+				owner.clone(),
+				owner,
 				data,
 			)?;
 			let foreign_asset_id =
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
before · pallets/fungible/src/lib.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//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//!	- [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::{ensure};84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86	AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,87	mapping::TokenAddressMapping, budget::Budget,88};89use pallet_common::{90	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91	eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115	use up_data_structs::CollectionId;116	use super::weights::WeightInfo;117118	#[pallet::error]119	pub enum Error<T> {120		/// Not Fungible item data used to mint in Fungible collection.121		NotFungibleDataUsedToMintFungibleCollectionToken,122		/// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123		FungibleItemsHaveNoId,124		/// Tried to set data for fungible item.125		FungibleItemsDontHaveData,126		/// Fungible token does not support nesting.127		FungibleDisallowsNesting,128		/// Setting item properties is not allowed.129		SettingPropertiesNotAllowed,130	}131132	#[pallet::config]133	pub trait Config:134		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config135	{136		type WeightInfo: WeightInfo;137	}138139	#[pallet::pallet]140	#[pallet::generate_store(pub(super) trait Store)]141	pub struct Pallet<T>(_);142143	/// Total amount of fungible tokens inside a collection.144	#[pallet::storage]145	pub type TotalSupply<T: Config> =146		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;147148	/// Amount of tokens owned by an account inside a collection.149	#[pallet::storage]150	pub type Balance<T: Config> = StorageNMap<151		Key = (152			Key<Twox64Concat, CollectionId>,153			Key<Blake2_128Concat, T::CrossAccountId>,154		),155		Value = u128,156		QueryKind = ValueQuery,157	>;158159	/// Storage for assets delegated to a limited extent to other users.160	#[pallet::storage]161	pub type Allowance<T: Config> = StorageNMap<162		Key = (163			Key<Twox64Concat, CollectionId>,164			Key<Blake2_128, T::CrossAccountId>,165			Key<Blake2_128Concat, T::CrossAccountId>,166		),167		Value = u128,168		QueryKind = ValueQuery,169	>;170}171172/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.173/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].174pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);175176/// Implementation of methods required for dispatching during runtime.177impl<T: Config> FungibleHandle<T> {178	/// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].179	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {180		Self(inner)181	}182183	/// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].184	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {185		self.0186	}187	/// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].188	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {189		&mut self.0190	}191}192impl<T: Config> WithRecorder<T> for FungibleHandle<T> {193	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {194		self.0.recorder()195	}196	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {197		self.0.into_recorder()198	}199}200impl<T: Config> Deref for FungibleHandle<T> {201	type Target = pallet_common::CollectionHandle<T>;202203	fn deref(&self) -> &Self::Target {204		&self.0205	}206}207208/// Pallet implementation for fungible assets209impl<T: Config> Pallet<T> {210	/// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.211	pub fn init_collection(212		owner: T::CrossAccountId,213		data: CreateCollectionData<T::AccountId>,214	) -> Result<CollectionId, DispatchError> {215		<PalletCommon<T>>::init_collection(owner, data, CollectionFlags::default())216	}217218	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.219	pub fn init_foreign_collection(220		owner: T::CrossAccountId,221		data: CreateCollectionData<T::AccountId>,222	) -> Result<CollectionId, DispatchError> {223		let id = <PalletCommon<T>>::init_collection(224			owner,225			data,226			CollectionFlags {227				foreign: true,228				..Default::default()229			},230		)?;231		Ok(id)232	}233234	/// Destroys a collection.235	pub fn destroy_collection(236		collection: FungibleHandle<T>,237		sender: &T::CrossAccountId,238	) -> DispatchResult {239		let id = collection.id;240241		if Self::collection_has_tokens(id) {242			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());243		}244245		// =========246247		PalletCommon::destroy_collection(collection.0, sender)?;248249		<TotalSupply<T>>::remove(id);250		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);251		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);252		Ok(())253	}254255	///Checks if collection has tokens. Return `true` if it has.256	fn collection_has_tokens(collection_id: CollectionId) -> bool {257		<TotalSupply<T>>::get(collection_id) != 0258	}259260	/// Burns the specified amount of the token. If the token balance261	/// or total supply is less than the given value,262	/// it will return [DispatchError].263	pub fn burn(264		collection: &FungibleHandle<T>,265		owner: &T::CrossAccountId,266		amount: u128,267	) -> DispatchResult {268		let total_supply = <TotalSupply<T>>::get(collection.id)269			.checked_sub(amount)270			.ok_or(<CommonError<T>>::TokenValueTooLow)?;271272		let balance = <Balance<T>>::get((collection.id, owner))273			.checked_sub(amount)274			.ok_or(<CommonError<T>>::TokenValueTooLow)?;275276		// Foreign collection check277		ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);278279		if collection.permissions.access() == AccessMode::AllowList {280			collection.check_allowlist(owner)?;281		}282283		// =========284285		if balance == 0 {286			<Balance<T>>::remove((collection.id, owner));287			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());288		} else {289			<Balance<T>>::insert((collection.id, owner), balance);290		}291		<TotalSupply<T>>::insert(collection.id, total_supply);292293		<PalletEvm<T>>::deposit_log(294			ERC20Events::Transfer {295				from: *owner.as_eth(),296				to: H160::default(),297				value: amount.into(),298			}299			.to_log(collection_id_to_address(collection.id)),300		);301		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(302			collection.id,303			TokenId::default(),304			owner.clone(),305			amount,306		));307		Ok(())308	}309310	/// Burns the specified amount of the token.311	pub fn burn_foreign(312		collection: &FungibleHandle<T>,313		owner: &T::CrossAccountId,314		amount: u128,315	) -> DispatchResult {316		let total_supply = <TotalSupply<T>>::get(collection.id)317			.checked_sub(amount)318			.ok_or(<CommonError<T>>::TokenValueTooLow)?;319320		let balance = <Balance<T>>::get((collection.id, owner))321			.checked_sub(amount)322			.ok_or(<CommonError<T>>::TokenValueTooLow)?;323		// =========324325		if balance == 0 {326			<Balance<T>>::remove((collection.id, owner));327			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());328		} else {329			<Balance<T>>::insert((collection.id, owner), balance);330		}331		<TotalSupply<T>>::insert(collection.id, total_supply);332333		<PalletEvm<T>>::deposit_log(334			ERC20Events::Transfer {335				from: *owner.as_eth(),336				to: H160::default(),337				value: amount.into(),338			}339			.to_log(collection_id_to_address(collection.id)),340		);341		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(342			collection.id,343			TokenId::default(),344			owner.clone(),345			amount,346		));347		Ok(())348	}349350	/// Transfers the specified amount of tokens. Will check that351	/// the transfer is allowed for the token.352	///353	/// - `from`: Owner of tokens to transfer.354	/// - `to`: Recepient of transfered tokens.355	/// - `amount`: Amount of tokens to transfer.356	/// - `collection`: Collection that contains the token357	pub fn transfer(358		collection: &FungibleHandle<T>,359		from: &T::CrossAccountId,360		to: &T::CrossAccountId,361		amount: u128,362		nesting_budget: &dyn Budget,363	) -> DispatchResult {364		ensure!(365			collection.limits.transfers_enabled(),366			<CommonError<T>>::TransferNotAllowed,367		);368369		if collection.permissions.access() == AccessMode::AllowList {370			collection.check_allowlist(from)?;371			collection.check_allowlist(to)?;372		}373		<PalletCommon<T>>::ensure_correct_receiver(to)?;374375		let balance_from = <Balance<T>>::get((collection.id, from))376			.checked_sub(amount)377			.ok_or(<CommonError<T>>::TokenValueTooLow)?;378		let balance_to = if from != to {379			Some(380				<Balance<T>>::get((collection.id, to))381					.checked_add(amount)382					.ok_or(ArithmeticError::Overflow)?,383			)384		} else {385			None386		};387388		// =========389390		<PalletStructure<T>>::nest_if_sent_to_token(391			from.clone(),392			to,393			collection.id,394			TokenId::default(),395			nesting_budget,396		)?;397398		if let Some(balance_to) = balance_to {399			// from != to400			if balance_from == 0 {401				<Balance<T>>::remove((collection.id, from));402				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());403			} else {404				<Balance<T>>::insert((collection.id, from), balance_from);405			}406			<Balance<T>>::insert((collection.id, to), balance_to);407		}408409		<PalletEvm<T>>::deposit_log(410			ERC20Events::Transfer {411				from: *from.as_eth(),412				to: *to.as_eth(),413				value: amount.into(),414			}415			.to_log(collection_id_to_address(collection.id)),416		);417		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(418			collection.id,419			TokenId::default(),420			from.clone(),421			to.clone(),422			amount,423		));424		Ok(())425	}426427	/// Minting tokens for multiple IDs.428	/// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]429	/// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]430	pub fn create_multiple_items_common(431		collection: &FungibleHandle<T>,432		sender: &T::CrossAccountId,433		data: BTreeMap<T::CrossAccountId, u128>,434		nesting_budget: &dyn Budget,435	) -> DispatchResult {436		let total_supply = data437			.iter()438			.map(|(_, v)| *v)439			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {440				acc.checked_add(v)441			})442			.ok_or(ArithmeticError::Overflow)?;443444		for (to, _) in data.iter() {445			<PalletStructure<T>>::check_nesting(446				sender.clone(),447				to,448				collection.id,449				TokenId::default(),450				nesting_budget,451			)?;452		}453454		let updated_balances = data455			.into_iter()456			.map(|(user, amount)| {457				let updated_balance = <Balance<T>>::get((collection.id, &user))458					.checked_add(amount)459					.ok_or(ArithmeticError::Overflow)?;460				Ok((user, amount, updated_balance))461			})462			.collect::<Result<Vec<_>, DispatchError>>()?;463464		// =========465466		<TotalSupply<T>>::insert(collection.id, total_supply);467		for (user, amount, updated_balance) in updated_balances {468			<Balance<T>>::insert((collection.id, &user), updated_balance);469			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(470				&user,471				collection.id,472				TokenId::default(),473			);474			<PalletEvm<T>>::deposit_log(475				ERC20Events::Transfer {476					from: H160::default(),477					to: *user.as_eth(),478					value: amount.into(),479				}480				.to_log(collection_id_to_address(collection.id)),481			);482			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(483				collection.id,484				TokenId::default(),485				user.clone(),486				amount,487			));488		}489490		Ok(())491	}492493	/// Minting tokens for multiple IDs.494	/// See [`create_item`][`Pallet::create_item`] for more details.495	pub fn create_multiple_items(496		collection: &FungibleHandle<T>,497		sender: &T::CrossAccountId,498		data: BTreeMap<T::CrossAccountId, u128>,499		nesting_budget: &dyn Budget,500	) -> DispatchResult {501		// Foreign collection check502		ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);503504		if !collection.is_owner_or_admin(sender) {505			ensure!(506				collection.permissions.mint_mode(),507				<CommonError<T>>::PublicMintingNotAllowed508			);509			collection.check_allowlist(sender)?;510511			for (owner, _) in data.iter() {512				collection.check_allowlist(owner)?;513			}514		}515516		Self::create_multiple_items_common(collection, sender, data, nesting_budget)517	}518519	/// Minting tokens for multiple IDs.520	/// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.521	pub fn create_multiple_items_foreign(522		collection: &FungibleHandle<T>,523		sender: &T::CrossAccountId,524		data: BTreeMap<T::CrossAccountId, u128>,525		nesting_budget: &dyn Budget,526	) -> DispatchResult {527		Self::create_multiple_items_common(collection, sender, data, nesting_budget)528	}529530	fn set_allowance_unchecked(531		collection: &FungibleHandle<T>,532		owner: &T::CrossAccountId,533		spender: &T::CrossAccountId,534		amount: u128,535	) {536		if amount == 0 {537			<Allowance<T>>::remove((collection.id, owner, spender));538		} else {539			<Allowance<T>>::insert((collection.id, owner, spender), amount);540		}541542		<PalletEvm<T>>::deposit_log(543			ERC20Events::Approval {544				owner: *owner.as_eth(),545				spender: *spender.as_eth(),546				value: amount.into(),547			}548			.to_log(collection_id_to_address(collection.id)),549		);550		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(551			collection.id,552			TokenId(0),553			owner.clone(),554			spender.clone(),555			amount,556		));557	}558559	/// Set allowance for the spender to `transfer` or `burn` owner's tokens.560	///561	/// - `collection`: Collection that contains the token562	/// - `owner`: Owner of tokens that sets the allowance.563	/// - `spender`: Recipient of the allowance rights.564	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.565	pub fn set_allowance(566		collection: &FungibleHandle<T>,567		owner: &T::CrossAccountId,568		spender: &T::CrossAccountId,569		amount: u128,570	) -> DispatchResult {571		if collection.permissions.access() == AccessMode::AllowList {572			collection.check_allowlist(owner)?;573			collection.check_allowlist(spender)?;574		}575576		if <Balance<T>>::get((collection.id, owner)) < amount {577			ensure!(578				collection.ignores_owned_amount(owner),579				<CommonError<T>>::CantApproveMoreThanOwned580			);581		}582583		// =========584585		Self::set_allowance_unchecked(collection, owner, spender, amount);586		Ok(())587	}588589	/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.590	/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.591	///592	/// - `collection`: Collection that contains the token.593	/// - `spender`: CrossAccountId who has the allowance rights.594	/// - `from`: The owner of the tokens who sets the allowance.595	/// - `amount`: Amount of tokens by which the allowance sholud be reduced.596	fn check_allowed(597		collection: &FungibleHandle<T>,598		spender: &T::CrossAccountId,599		from: &T::CrossAccountId,600		amount: u128,601		nesting_budget: &dyn Budget,602	) -> Result<Option<u128>, DispatchError> {603		if spender.conv_eq(from) {604			return Ok(None);605		}606		if collection.permissions.access() == AccessMode::AllowList {607			// `from`, `to` checked in [`transfer`]608			collection.check_allowlist(spender)?;609		}610		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {611			// TODO: should collection owner be allowed to perform this transfer?612			ensure!(613				<PalletStructure<T>>::check_indirectly_owned(614					spender.clone(),615					source.0,616					source.1,617					None,618					nesting_budget619				)?,620				<CommonError<T>>::ApprovedValueTooLow,621			);622			return Ok(None);623		}624		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);625		if allowance.is_none() {626			ensure!(627				collection.ignores_allowance(spender),628				<CommonError<T>>::ApprovedValueTooLow629			);630		}631632		Ok(allowance)633	}634635	/// Transfer fungible tokens from one account to another.636	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.637	/// The owner should set allowance for the spender to transfer pieces.638	///	See [`set_allowance`][`Pallet::set_allowance`] for more details.639640	pub fn transfer_from(641		collection: &FungibleHandle<T>,642		spender: &T::CrossAccountId,643		from: &T::CrossAccountId,644		to: &T::CrossAccountId,645		amount: u128,646		nesting_budget: &dyn Budget,647	) -> DispatchResult {648		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;649650		// =========651652		Self::transfer(collection, from, to, amount, nesting_budget)?;653		if let Some(allowance) = allowance {654			Self::set_allowance_unchecked(collection, from, spender, allowance);655		}656		Ok(())657	}658659	/// Burn fungible tokens from the account.660	///661	/// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should662	/// set allowance for the spender to burn tokens.663	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.664	pub fn burn_from(665		collection: &FungibleHandle<T>,666		spender: &T::CrossAccountId,667		from: &T::CrossAccountId,668		amount: u128,669		nesting_budget: &dyn Budget,670	) -> DispatchResult {671		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;672673		// =========674675		Self::burn(collection, from, amount)?;676		if let Some(allowance) = allowance {677			Self::set_allowance_unchecked(collection, from, spender, allowance);678		}679		Ok(())680	}681682	///	Creates fungible token.683	///684	/// The sender should be the owner/admin of the collection or collection should be configured685	/// to allow public minting.686	///687	/// - `data`: Contains user who will become the owners of the tokens and amount688	///   of tokens he will receive.689	pub fn create_item(690		collection: &FungibleHandle<T>,691		sender: &T::CrossAccountId,692		data: CreateItemData<T>,693		nesting_budget: &dyn Budget,694	) -> DispatchResult {695		Self::create_multiple_items(696			collection,697			sender,698			[(data.0, data.1)].into_iter().collect(),699			nesting_budget,700		)701	}702703	///	Creates fungible token.704	///705	/// - `data`: Contains user who will become the owners of the tokens and amount706	///   of tokens he will receive.707	pub fn create_item_foreign(708		collection: &FungibleHandle<T>,709		sender: &T::CrossAccountId,710		data: CreateItemData<T>,711		nesting_budget: &dyn Budget,712	) -> DispatchResult {713		Self::create_multiple_items_foreign(714			collection,715			sender,716			[(data.0, data.1)].into_iter().collect(),717			nesting_budget,718		)719	}720721	/// Returns 10 tokens owners in no particular order722	///723	/// There is no direct way to get token holders in ascending order,724	/// since `iter_prefix` returns values in no particular order.725	/// Therefore, getting the 10 largest holders with a large value of holders726	/// can lead to impact memory allocation + sorting with  `n * log (n)`.727	pub fn token_owners(728		collection: CollectionId,729		_token: TokenId,730	) -> Option<Vec<T::CrossAccountId>> {731		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))732			.map(|(owner, _amount)| owner)733			.take(10)734			.collect();735736		if res.is_empty() {737			None738		} else {739			Some(res)740		}741	}742}
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -405,11 +405,13 @@
 	/// - `data`: Contains settings for collection limits and permissions.
 	pub fn init_collection(
 		owner: T::CrossAccountId,
+		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
 		is_external: bool,
 	) -> Result<CollectionId, DispatchError> {
 		<PalletCommon<T>>::init_collection(
 			owner,
+			payer,
 			data,
 			CollectionFlags {
 				external: is_external,
modifiedpallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -1448,7 +1448,7 @@
 		data: CreateCollectionData<T::AccountId>,
 		properties: impl Iterator<Item = Property>,
 	) -> Result<CollectionId, DispatchError> {
-		let collection_id = <PalletNft<T>>::init_collection(sender, data, true);
+		let collection_id = <PalletNft<T>>::init_collection(sender.clone(), sender, data, true);
 
 		if let Err(DispatchError::Arithmetic(_)) = &collection_id {
 			return Err(<Error<T>>::NoAvailableCollectionId.into());
modifiedpallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -251,7 +251,7 @@
 			};
 
 			let collection_id_res =
-				<PalletNft<T>>::init_collection(cross_sender.clone(), data, true);
+				<PalletNft<T>>::init_collection(cross_sender.clone(), cross_sender.clone(), data, true);
 
 			if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
 				return Err(<Error<T>>::NoAvailableBaseId.into());
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -373,9 +373,10 @@
 	/// - `data`: Contains settings for collection limits and permissions.
 	pub fn init_collection(
 		owner: T::CrossAccountId,
+		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
 	) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(owner, data, CollectionFlags::default())
+		<PalletCommon<T>>::init_collection(owner, payer, data, CollectionFlags::default())
 	}
 
 	/// Destroy RFT collection
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -28,7 +28,7 @@
 		static_property::{key, value as property_value},
 	},
 };
-use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
+use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};
 use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
 use up_data_structs::{
 	CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
@@ -156,6 +156,7 @@
 	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,
 >(
 	caller: caller,
+	value: value,
 	name: string,
 	description: string,
 	token_prefix: string,
@@ -172,8 +173,16 @@
 		base_uri_value,
 		add_properties,
 	)?;
+	let value = value.as_u128();
+	let creation_price: Result<u128> = T::CollectionCreationPrice::get()
+		.try_into()
+		.map_err(|_| "collection creation price should be convertible to u128".into());
+	if value != creation_price? {
+		return Err("Sent amount not equals to collection creation price".into());
+	}
+	let collection_helpers_address =  T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
 
-	let collection_id = T::CollectionDispatch::create(caller.clone(), data)
+	let collection_id = T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)
 		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
 	let address = pallet_common::eth::collection_id_to_address(collection_id);
 	Ok(address)
@@ -183,7 +192,7 @@
 #[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]
 impl<T> EvmCollectionHelpers<T>
 where
-	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,
+	T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,
 {
 	/// Create an NFT collection
 	/// @param name Name of the collection
@@ -209,8 +218,17 @@
 			Default::default(),
 			false,
 		)?;
-		let collection_id = T::CollectionDispatch::create(caller, data)
-			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+		let value = value.as_u128();
+		let creation_price: Result<u128> = T::CollectionCreationPrice::get()
+			.try_into()
+			.map_err(|_| "collection creation price should be convertible to u128".into());
+		let creation_price = creation_price?;
+		if value != creation_price {
+			return Err(format!("Sent amount not equals to collection creation price ({0})", creation_price).into());
+		}
+		let collection_helpers_address =  T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
+		let collection_id =
+			T::CollectionDispatch::create(caller, collection_helpers_address, data).map_err(dispatch_to_evm::<T>)?;
 
 		let address = pallet_common::eth::collection_id_to_address(collection_id);
 		Ok(address)
@@ -221,6 +239,7 @@
 	fn create_nonfungible_collection_with_properties(
 		&mut self,
 		caller: caller,
+		value: value,
 		name: string,
 		description: string,
 		token_prefix: string,
@@ -236,7 +255,15 @@
 			base_uri_value,
 			true,
 		)?;
-		let collection_id = T::CollectionDispatch::create(caller, data)
+		let value = value.as_u128();
+		let creation_price: Result<u128> = T::CollectionCreationPrice::get()
+			.try_into()
+			.map_err(|_| "collection creation price should be convertible to u128".into());
+		if value != creation_price? {
+			return Err("Sent amount not equals to collection creation price".into());
+		}
+		let collection_helpers_address =  T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
+		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
 			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
 
 		let address = pallet_common::eth::collection_id_to_address(collection_id);
@@ -248,12 +275,14 @@
 	fn create_refungible_collection(
 		&mut self,
 		caller: caller,
+		value: value,
 		name: string,
 		description: string,
 		token_prefix: string,
 	) -> Result<address> {
 		create_refungible_collection_internal::<T>(
 			caller,
+			value,
 			name,
 			description,
 			token_prefix,
@@ -267,6 +296,7 @@
 	fn create_refungible_collection_with_properties(
 		&mut self,
 		caller: caller,
+		value: value,
 		name: string,
 		description: string,
 		token_prefix: string,
@@ -274,6 +304,7 @@
 	) -> Result<address> {
 		create_refungible_collection_internal::<T>(
 			caller,
+			value,
 			name,
 			description,
 			token_prefix,
modifiedpallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth
--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -36,7 +36,7 @@
 		string memory name,
 		string memory description,
 		string memory tokenPrefix
-	) public returns (address) {
+	) public payable returns (address) {
 		require(false, stub_error);
 		name;
 		description;
@@ -52,7 +52,7 @@
 		string memory description,
 		string memory tokenPrefix,
 		string memory baseUri
-	) public returns (address) {
+	) public payable returns (address) {
 		require(false, stub_error);
 		name;
 		description;
@@ -68,7 +68,7 @@
 		string memory name,
 		string memory description,
 		string memory tokenPrefix
-	) public returns (address) {
+	) public payable returns (address) {
 		require(false, stub_error);
 		name;
 		description;
@@ -84,7 +84,7 @@
 		string memory description,
 		string memory tokenPrefix,
 		string memory baseUri
-	) public returns (address) {
+	) public payable returns (address) {
 		require(false, stub_error);
 		name;
 		description;
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -344,8 +344,8 @@
 			let sender = ensure_signed(origin)?;
 
 			// =========
-
-			let _id = T::CollectionDispatch::create(T::CrossAccountId::from_sub(sender), data)?;
+			let sender = T::CrossAccountId::from_sub(sender);
+			let _id = T::CollectionDispatch::create(sender.clone(), sender, data)?;
 
 			Ok(())
 		}
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -55,21 +55,22 @@
 {
 	fn create(
 		sender: T::CrossAccountId,
+		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
 	) -> Result<CollectionId, DispatchError> {
 		let id = match data.mode {
-			CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, data, false)?,
+			CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, payer, data, false)?,
 			CollectionMode::Fungible(decimal_points) => {
 				// check params
 				ensure!(
 					decimal_points <= MAX_DECIMAL_POINTS,
 					pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
 				);
-				<PalletFungible<T>>::init_collection(sender, data)?
+				<PalletFungible<T>>::init_collection(sender, payer, data)?
 			}
 
 			#[cfg(feature = "refungible")]
-			CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, data)?,
+			CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, payer, data)?,
 
 			#[cfg(not(feature = "refungible"))]
 			CollectionMode::ReFungible => return unsupported!(T),
modifiedtests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -31,7 +31,7 @@
 		string memory name,
 		string memory description,
 		string memory tokenPrefix
-	) external returns (address);
+	) external payable returns (address);
 
 	/// @dev EVM selector for this function is: 0xa634a5f9,
 	///  or in textual repr: createERC721MetadataCompatibleCollection(string,string,string,string)
@@ -40,7 +40,7 @@
 		string memory description,
 		string memory tokenPrefix,
 		string memory baseUri
-	) external returns (address);
+	) external payable returns (address);
 
 	/// @dev EVM selector for this function is: 0xab173450,
 	///  or in textual repr: createRFTCollection(string,string,string)
@@ -48,7 +48,7 @@
 		string memory name,
 		string memory description,
 		string memory tokenPrefix
-	) external returns (address);
+	) external payable returns (address);
 
 	/// @dev EVM selector for this function is: 0xa5596388,
 	///  or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
@@ -57,7 +57,7 @@
 		string memory description,
 		string memory tokenPrefix,
 		string memory baseUri
-	) external returns (address);
+	) external payable returns (address);
 
 	/// Check if a collection exists
 	/// @param collectionAddress Address of the collection in question
modifiedtests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -27,7 +27,7 @@
     ],
     "name": "createERC721MetadataCompatibleCollection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
-    "stateMutability": "nonpayable",
+    "stateMutability": "payable",
     "type": "function"
   },
   {
@@ -39,7 +39,7 @@
     ],
     "name": "createERC721MetadataCompatibleRFTCollection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
-    "stateMutability": "nonpayable",
+    "stateMutability": "payable",
     "type": "function"
   },
   {
@@ -50,7 +50,7 @@
     ],
     "name": "createNonfungibleCollection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
-    "stateMutability": "nonpayable",
+    "stateMutability": "payable",
     "type": "function"
   },
   {
@@ -61,7 +61,7 @@
     ],
     "name": "createRFTCollection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
-    "stateMutability": "nonpayable",
+    "stateMutability": "payable",
     "type": "function"
   },
   {
modifiedtests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth
--- a/tests/src/eth/fractionalizer/Fractionalizer.sol
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -18,7 +18,8 @@
 	mapping(address => bool) nftCollectionAllowList;
 	mapping(address => mapping(uint256 => uint256)) public nft2rftMapping;
 	mapping(address => Token) public rft2nftMapping;
-	bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));
+	//use constant to reduce gas cost
+	bytes32 constant refungibleCollectionType = keccak256(bytes("ReFungible"));
 
 	receive() external payable onlyOwner {}
 
@@ -51,11 +52,12 @@
 	///  Throws if `msg.sender` is not owner or admin of provided RFT collection.
 	///  Can only be called by contract owner.
 	/// @param _collection address of RFT collection.
-	function setRFTCollection(address _collection) public onlyOwner {
+	function setRFTCollection(address _collection) external onlyOwner {
 		require(rftCollection == address(0), "RFT collection is already set");
 		UniqueRefungible refungibleContract = UniqueRefungible(_collection);
 		string memory collectionType = refungibleContract.uniqueCollectionType();
 
+		// compare hashed to reduce gas cost
 		require(
 			keccak256(bytes(collectionType)) == refungibleCollectionType,
 			"Wrong collection type. Collection is not refungible."
@@ -79,7 +81,7 @@
 		string calldata _name,
 		string calldata _description,
 		string calldata _tokenPrefix
-	) public onlyOwner {
+	) external onlyOwner {
 		require(rftCollection == address(0), "RFT collection is already set");
 		address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;
 		rftCollection = CollectionHelpers(collectionHelpers).createRFTCollection(_name, _description, _tokenPrefix);
@@ -90,7 +92,7 @@
 	/// @dev Can only be called by contract owner.
 	/// @param collection NFT token address.
 	/// @param status `true` to allow and `false` to disallow NFT token.
-	function setNftCollectionIsAllowed(address collection, bool status) public onlyOwner {
+	function setNftCollectionIsAllowed(address collection, bool status) external onlyOwner {
 		nftCollectionAllowList[collection] = status;
 		emit AllowListSet(collection, status);
 	}
@@ -109,7 +111,7 @@
 		address _collection,
 		uint256 _token,
 		uint128 _pieces
-	) public {
+	) external {
 		require(rftCollection != address(0), "RFT collection is not set");
 		UniqueRefungible rftCollectionContract = UniqueRefungible(rftCollection);
 		require(
@@ -148,7 +150,7 @@
 	///  Throws if `msg.sender` isn't owner of all RFT token pieces.
 	/// @param _collection RFT collection address
 	/// @param _token id of RFT token
-	function rft2nft(address _collection, uint256 _token) public {
+	function rft2nft(address _collection, uint256 _token) external {
 		require(rftCollection != address(0), "RFT collection is not set");
 		require(rftCollection == _collection, "Wrong RFT collection");
 		UniqueRefungible rftCollectionContract = UniqueRefungible(rftCollection);
modifiedtests/src/eth/payable.test.tsdiffbeforeafterboth
--- a/tests/src/eth/payable.test.ts
+++ b/tests/src/eth/payable.test.ts
@@ -140,16 +140,13 @@
   });
   
   itEth('Fee for nested calls to native methods is withdrawn from the user', async({helper}) => {
-    const CONTRACT_BALANCE = 3n * helper.balance.getOneTokenNominal();
+    const CONTRACT_BALANCE = 2n * helper.balance.getOneTokenNominal();
 
     const deployer = await helper.eth.createAccountWithBalance(donor);
     const caller = await helper.eth.createAccountWithBalance(donor);
     const contract = await deployProxyContract(helper, deployer);
-    
-    const web3 = helper.getWeb3();
-    await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), gas: helper.eth.DEFAULT_GAS});
 
-    const collectionAddress = (await contract.methods.createNonfungibleCollection().send({from: caller})).events.CollectionCreated.returnValues.collection;
+    const collectionAddress = (await contract.methods.createNonfungibleCollection().send({from: caller, value: Number(CONTRACT_BALANCE)})).events.CollectionCreated.returnValues.collection;
     const initialCallerBalance = await helper.balance.getEthereum(caller);
     const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
     await contract.methods.mintNftToken(collectionAddress).send({from: caller});
@@ -160,22 +157,18 @@
   });
   
   itEth('Fee for nested calls to create*Collection methods is withdrawn from the user and from the contract', async({helper}) => {
-    const CONTRACT_BALANCE = 3n * helper.balance.getOneTokenNominal();
-
+    const CONTRACT_BALANCE = 2n * helper.balance.getOneTokenNominal();
     const deployer = await helper.eth.createAccountWithBalance(donor);
     const caller = await helper.eth.createAccountWithBalance(donor);
     const contract = await deployProxyContract(helper, deployer);
-    
-    const web3 = helper.getWeb3();
-    await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), gas: helper.eth.DEFAULT_GAS});
 
     const initialCallerBalance = await helper.balance.getEthereum(caller);
     const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
-    await contract.methods.createNonfungibleCollection().send({from: caller});
+    await contract.methods.createNonfungibleCollection().send({from: caller, value: Number(CONTRACT_BALANCE)});
     const finalCallerBalance = await helper.balance.getEthereum(caller);
     const finalContractBalance = await helper.balance.getEthereum(contract.options.address);
     expect(finalCallerBalance < initialCallerBalance).to.be.true;
-    expect(finalContractBalance < initialContractBalance).to.be.true;
+    expect(finalContractBalance == initialContractBalance).to.be.true;
   });
 
   async function deployProxyContract(helper: EthUniqueHelper, deployer: string) {
@@ -189,6 +182,8 @@
       import {CollectionHelpers} from "../api/CollectionHelpers.sol";
       import {UniqueNFT} from "../api/UniqueNFT.sol";
 
+      error Value(uint256 value);
+
       contract ProxyContract {
         bool value = false;
         address flipper;
@@ -207,30 +202,30 @@
           Flipper(flipper).flip();
         }
 
-        function createNonfungibleCollection() public {
+        function createNonfungibleCollection() external payable {
           address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;
-		      address nftCollection = CollectionHelpers(collectionHelpers).createNonfungibleCollection("A", "B", "C");
+		      address nftCollection = CollectionHelpers(collectionHelpers).createNonfungibleCollection{value: msg.value}("A", "B", "C");
           emit CollectionCreated(nftCollection);
         }
 
-        function mintNftToken(address collectionAddress) public {
+        function mintNftToken(address collectionAddress) external  {
           UniqueNFT collection = UniqueNFT(collectionAddress);
           uint256 tokenId = collection.nextTokenId();
           collection.mint(msg.sender, tokenId);
           emit TokenMinted(tokenId);
         }
 
-        function getValue() public view returns (bool) {
+        function getValue() external view returns (bool) {
           return Flipper(flipper).getValue();
         }
       }
 
       contract Flipper {
         bool value = false;
-        function flip() public {
+        function flip() external {
           value = !value;
         }
-        function getValue() public view returns (bool) {
+        function getValue() external view returns (bool) {
           return value;
         }
       }