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
before · crates/evm-coder/src/solidity.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//! Implementation detail of [`crate::solidity_interface`] macro code-generation.18//! You should not rely on any public item from this module, as it is only intended to be used19//! by procedural macro, API and output format may be changed at any time.20//!21//! Purpose of this module is to receive solidity contract definition in module-specified22//! format, and then output string, representing interface of this contract in solidity language2324#[cfg(not(feature = "std"))]25use alloc::{string::String, vec::Vec, collections::BTreeMap, format};26#[cfg(feature = "std")]27use std::collections::BTreeMap;28use core::{29	fmt::{self, Write},30	marker::PhantomData,31	cell::{Cell, RefCell},32	cmp::Reverse,33};34use impl_trait_for_tuples::impl_for_tuples;35use crate::types::*;3637#[derive(Default)]38pub struct TypeCollector {39	/// Code => id40	/// id ordering is required to perform topo-sort on the resulting data41	structs: RefCell<BTreeMap<string, usize>>,42	anonymous: RefCell<BTreeMap<Vec<string>, usize>>,43	id: Cell<usize>,44}45impl TypeCollector {46	pub fn new() -> Self {47		Self::default()48	}49	pub fn collect(&self, item: string) {50		let id = self.next_id();51		self.structs.borrow_mut().insert(item, id);52	}53	pub fn next_id(&self) -> usize {54		let v = self.id.get();55		self.id.set(v + 1);56		v57	}58	pub fn collect_tuple<T: SolidityTupleType>(&self) -> String {59		let names = T::names(self);60		if let Some(id) = self.anonymous.borrow().get(&names).cloned() {61			return format!("Tuple{}", id);62		}63		let id = self.next_id();64		let mut str = String::new();65		writeln!(str, "/// @dev anonymous struct").unwrap();66		writeln!(str, "struct Tuple{} {{", id).unwrap();67		for (i, name) in names.iter().enumerate() {68			writeln!(str, "\t{} field_{};", name, i).unwrap();69		}70		writeln!(str, "}}").unwrap();71		self.collect(str);72		self.anonymous.borrow_mut().insert(names, id);73		format!("Tuple{}", id)74	}75	pub fn finish(self) -> Vec<string> {76		let mut data = self.structs.into_inner().into_iter().collect::<Vec<_>>();77		data.sort_by_key(|(_, id)| Reverse(*id));78		data.into_iter().map(|(code, _)| code).collect()79	}80}8182pub trait SolidityTypeName: 'static {83	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;84	/// "simple" types are stored inline, no `memory` modifier should be used in solidity85	fn is_simple() -> bool;86	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;87	/// Specialization88	fn is_void() -> bool {89		false90	}91}92macro_rules! solidity_type_name {93    ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {94        $(95            impl SolidityTypeName for $ty {96                fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {97                    write!(writer, $name)98                }99				fn is_simple() -> bool {100					$simple101				}102				fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {103					write!(writer, $default)104				}105            }106        )*107    };108}109110solidity_type_name! {111	uint8 => "uint8" true = "0",112	uint32 => "uint32" true = "0",113	uint64 => "uint64" true = "0",114	uint128 => "uint128" true = "0",115	uint256 => "uint256" true = "0",116	bytes4 => "bytes4" true = "bytes4(0)",117	address => "address" true = "0x0000000000000000000000000000000000000000",118	string => "string" false = "\"\"",119	bytes => "bytes" false = "hex\"\"",120	bool => "bool" true = "false",121}122impl SolidityTypeName for void {123	fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {124		Ok(())125	}126	fn is_simple() -> bool {127		true128	}129	fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {130		Ok(())131	}132	fn is_void() -> bool {133		true134	}135}136137mod sealed {138	/// Not every type should be directly placed in vec.139	/// Vec encoding is not memory efficient, as every item will be padded140	/// to 32 bytes.141	/// Instead you should use specialized types (`bytes` in case of `Vec<u8>`)142	pub trait CanBePlacedInVec {}143}144145impl sealed::CanBePlacedInVec for uint256 {}146impl sealed::CanBePlacedInVec for string {}147impl sealed::CanBePlacedInVec for address {}148149impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {150	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {151		T::solidity_name(writer, tc)?;152		write!(writer, "[]")153	}154	fn is_simple() -> bool {155		false156	}157	fn solidity_default(writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {158		write!(writer, "[]")159	}160}161162pub trait SolidityTupleType {163	fn names(tc: &TypeCollector) -> Vec<String>;164	fn len() -> usize;165}166167macro_rules! count {168    () => (0usize);169    ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));170}171172macro_rules! impl_tuples {173	($($ident:ident)+) => {174		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}175		impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {176			fn names(tc: &TypeCollector) -> Vec<string> {177				let mut collected = Vec::with_capacity(Self::len());178				$({179					let mut out = string::new();180					$ident::solidity_name(&mut out, tc).expect("no fmt error");181					collected.push(out);182				})*;183				collected184			}185186			fn len() -> usize {187				count!($($ident)*)188			}189		}190		impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {191			fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {192				write!(writer, "{}", tc.collect_tuple::<Self>())193			}194			fn is_simple() -> bool {195				false196			}197			#[allow(unused_assignments)]198			fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {199				write!(writer, "{}(", tc.collect_tuple::<Self>())?;200				let mut first = true;201				$(202					if !first {203						write!(writer, ",")?;204					} else {205						first = false;206					}207					<$ident>::solidity_default(writer, tc)?;208				)*209				write!(writer, ")")210			}211		}212	};213}214215impl_tuples! {A}216impl_tuples! {A B}217impl_tuples! {A B C}218impl_tuples! {A B C D}219impl_tuples! {A B C D E}220impl_tuples! {A B C D E F}221impl_tuples! {A B C D E F G}222impl_tuples! {A B C D E F G H}223impl_tuples! {A B C D E F G H I}224impl_tuples! {A B C D E F G H I J}225226pub trait SolidityArguments {227	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;228	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;229	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;230	fn is_empty(&self) -> bool {231		self.len() == 0232	}233	fn len(&self) -> usize;234}235236#[derive(Default)]237pub struct UnnamedArgument<T>(PhantomData<*const T>);238239impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {240	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {241		if !T::is_void() {242			T::solidity_name(writer, tc)?;243			if !T::is_simple() {244				write!(writer, " memory")?;245			}246			Ok(())247		} else {248			Ok(())249		}250	}251	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {252		Ok(())253	}254	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {255		T::solidity_default(writer, tc)256	}257	fn len(&self) -> usize {258		if T::is_void() {259			0260		} else {261			1262		}263	}264}265266pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);267268impl<T> NamedArgument<T> {269	pub fn new(name: &'static str) -> Self {270		Self(name, Default::default())271	}272}273274impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {275	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {276		if !T::is_void() {277			T::solidity_name(writer, tc)?;278			if !T::is_simple() {279				write!(writer, " memory")?;280			}281			write!(writer, " {}", self.0)282		} else {283			Ok(())284		}285	}286	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {287		writeln!(writer, "\t\t{};", self.0)288	}289	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {290		T::solidity_default(writer, tc)291	}292	fn len(&self) -> usize {293		if T::is_void() {294			0295		} else {296			1297		}298	}299}300301pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);302303impl<T> SolidityEventArgument<T> {304	pub fn new(indexed: bool, name: &'static str) -> Self {305		Self(indexed, name, Default::default())306	}307}308309impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {310	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {311		if !T::is_void() {312			T::solidity_name(writer, tc)?;313			if self.0 {314				write!(writer, " indexed")?;315			}316			write!(writer, " {}", self.1)317		} else {318			Ok(())319		}320	}321	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {322		writeln!(writer, "\t\t{};", self.1)323	}324	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {325		T::solidity_default(writer, tc)326	}327	fn len(&self) -> usize {328		if T::is_void() {329			0330		} else {331			1332		}333	}334}335336impl SolidityArguments for () {337	fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {338		Ok(())339	}340	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {341		Ok(())342	}343	fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {344		Ok(())345	}346	fn len(&self) -> usize {347		0348	}349}350351#[impl_for_tuples(1, 12)]352impl SolidityArguments for Tuple {353	for_tuples!( where #( Tuple: SolidityArguments ),* );354355	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {356		let mut first = true;357		for_tuples!( #(358            if !Tuple.is_empty() {359                if !first {360                    write!(writer, ", ")?;361                }362                first = false;363                Tuple.solidity_name(writer, tc)?;364            }365        )* );366		Ok(())367	}368	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {369		for_tuples!( #(370            Tuple.solidity_get(writer)?;371        )* );372		Ok(())373	}374	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {375		if self.is_empty() {376			Ok(())377		} else if self.len() == 1 {378			for_tuples!( #(379				Tuple.solidity_default(writer, tc)?;380			)* );381			Ok(())382		} else {383			write!(writer, "(")?;384			let mut first = true;385			for_tuples!( #(386				if !Tuple.is_empty() {387					if !first {388						write!(writer, ", ")?;389					}390					first = false;391					Tuple.solidity_default(writer, tc)?;392				}393			)* );394			write!(writer, ")")?;395			Ok(())396		}397	}398	fn len(&self) -> usize {399		for_tuples!( #( Tuple.len() )+* )400	}401}402403pub trait SolidityFunctions {404	fn solidity_name(405		&self,406		is_impl: bool,407		writer: &mut impl fmt::Write,408		tc: &TypeCollector,409	) -> fmt::Result;410}411412pub enum SolidityMutability {413	Pure,414	View,415	Mutable,416}417pub struct SolidityFunction<A, R> {418	pub docs: &'static [&'static str],419	pub selector_str: &'static str,420	pub selector: u32,421	pub name: &'static str,422	pub args: A,423	pub result: R,424	pub mutability: SolidityMutability,425}426impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {427	fn solidity_name(428		&self,429		is_impl: bool,430		writer: &mut impl fmt::Write,431		tc: &TypeCollector,432	) -> fmt::Result {433		for doc in self.docs {434			writeln!(writer, "\t///{}", doc)?;435		}436		writeln!(437			writer,438			"\t/// @dev EVM selector for this function is: 0x{:0>8x},",439			self.selector440		)?;441		writeln!(writer, "\t///  or in textual repr: {}", self.selector_str)?;442		write!(writer, "\tfunction {}(", self.name)?;443		self.args.solidity_name(writer, tc)?;444		write!(writer, ")")?;445		if is_impl {446			write!(writer, " public")?;447		} else {448			write!(writer, " external")?;449		}450		match &self.mutability {451			SolidityMutability::Pure => write!(writer, " pure")?,452			SolidityMutability::View => write!(writer, " view")?,453			SolidityMutability::Mutable => {}454		}455		if !self.result.is_empty() {456			write!(writer, " returns (")?;457			self.result.solidity_name(writer, tc)?;458			write!(writer, ")")?;459		}460		if is_impl {461			writeln!(writer, " {{")?;462			writeln!(writer, "\t\trequire(false, stub_error);")?;463			self.args.solidity_get(writer)?;464			match &self.mutability {465				SolidityMutability::Pure => {}466				SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,467				SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,468			}469			if !self.result.is_empty() {470				write!(writer, "\t\treturn ")?;471				self.result.solidity_default(writer, tc)?;472				writeln!(writer, ";")?;473			}474			writeln!(writer, "\t}}")?;475		} else {476			writeln!(writer, ";")?;477		}478		Ok(())479	}480}481482#[impl_for_tuples(0, 48)]483impl SolidityFunctions for Tuple {484	for_tuples!( where #( Tuple: SolidityFunctions ),* );485486	fn solidity_name(487		&self,488		is_impl: bool,489		writer: &mut impl fmt::Write,490		tc: &TypeCollector,491	) -> fmt::Result {492		let mut first = false;493		for_tuples!( #(494            Tuple.solidity_name(is_impl, writer, tc)?;495        )* );496		Ok(())497	}498}499500pub struct SolidityInterface<F: SolidityFunctions> {501	pub docs: &'static [&'static str],502	pub selector: bytes4,503	pub name: &'static str,504	pub is: &'static [&'static str],505	pub functions: F,506}507508impl<F: SolidityFunctions> SolidityInterface<F> {509	pub fn format(510		&self,511		is_impl: bool,512		out: &mut impl fmt::Write,513		tc: &TypeCollector,514	) -> fmt::Result {515		const ZERO_BYTES: [u8; 4] = [0; 4];516		for doc in self.docs {517			writeln!(out, "///{}", doc)?;518		}519		if self.selector != ZERO_BYTES {520			writeln!(521				out,522				"/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",523				u32::from_be_bytes(self.selector)524			)?;525		}526		if is_impl {527			write!(out, "contract ")?;528		} else {529			write!(out, "interface ")?;530		}531		write!(out, "{}", self.name)?;532		if !self.is.is_empty() {533			write!(out, " is")?;534			for (i, n) in self.is.iter().enumerate() {535				if i != 0 {536					write!(out, ",")?;537				}538				write!(out, " {}", n)?;539			}540		}541		writeln!(out, " {{")?;542		self.functions.solidity_name(is_impl, out, tc)?;543		writeln!(out, "}}")?;544		Ok(())545	}546}547548pub struct SolidityEvent<A> {549	pub name: &'static str,550	pub args: A,551}552553impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {554	fn solidity_name(555		&self,556		_is_impl: bool,557		writer: &mut impl fmt::Write,558		tc: &TypeCollector,559	) -> fmt::Result {560		write!(writer, "\tevent {}(", self.name)?;561		self.args.solidity_name(writer, tc)?;562		writeln!(writer, ");")563	}564}
after · crates/evm-coder/src/solidity.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//! Implementation detail of [`crate::solidity_interface`] macro code-generation.18//! You should not rely on any public item from this module, as it is only intended to be used19//! by procedural macro, API and output format may be changed at any time.20//!21//! Purpose of this module is to receive solidity contract definition in module-specified22//! format, and then output string, representing interface of this contract in solidity language2324#[cfg(not(feature = "std"))]25use alloc::{string::String, vec::Vec, collections::BTreeMap, format};26#[cfg(feature = "std")]27use std::collections::BTreeMap;28use core::{29	fmt::{self, Write},30	marker::PhantomData,31	cell::{Cell, RefCell},32	cmp::Reverse,33};34use impl_trait_for_tuples::impl_for_tuples;35use crate::types::*;3637#[derive(Default)]38pub struct TypeCollector {39	/// Code => id40	/// id ordering is required to perform topo-sort on the resulting data41	structs: RefCell<BTreeMap<string, usize>>,42	anonymous: RefCell<BTreeMap<Vec<string>, usize>>,43	id: Cell<usize>,44}45impl TypeCollector {46	pub fn new() -> Self {47		Self::default()48	}49	pub fn collect(&self, item: string) {50		let id = self.next_id();51		self.structs.borrow_mut().insert(item, id);52	}53	pub fn next_id(&self) -> usize {54		let v = self.id.get();55		self.id.set(v + 1);56		v57	}58	pub fn collect_tuple<T: SolidityTupleType>(&self) -> String {59		let names = T::names(self);60		if let Some(id) = self.anonymous.borrow().get(&names).cloned() {61			return format!("Tuple{}", id);62		}63		let id = self.next_id();64		let mut str = String::new();65		writeln!(str, "/// @dev anonymous struct").unwrap();66		writeln!(str, "struct Tuple{} {{", id).unwrap();67		for (i, name) in names.iter().enumerate() {68			writeln!(str, "\t{} field_{};", name, i).unwrap();69		}70		writeln!(str, "}}").unwrap();71		self.collect(str);72		self.anonymous.borrow_mut().insert(names, id);73		format!("Tuple{}", id)74	}75	pub fn finish(self) -> Vec<string> {76		let mut data = self.structs.into_inner().into_iter().collect::<Vec<_>>();77		data.sort_by_key(|(_, id)| Reverse(*id));78		data.into_iter().map(|(code, _)| code).collect()79	}80}8182pub trait SolidityTypeName: 'static {83	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;84	/// "simple" types are stored inline, no `memory` modifier should be used in solidity85	fn is_simple() -> bool;86	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;87	/// Specialization88	fn is_void() -> bool {89		false90	}91}92macro_rules! solidity_type_name {93    ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {94        $(95            impl SolidityTypeName for $ty {96                fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {97                    write!(writer, $name)98                }99				fn is_simple() -> bool {100					$simple101				}102				fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {103					write!(writer, $default)104				}105            }106        )*107    };108}109110solidity_type_name! {111	uint8 => "uint8" true = "0",112	uint32 => "uint32" true = "0",113	uint64 => "uint64" true = "0",114	uint128 => "uint128" true = "0",115	uint256 => "uint256" true = "0",116	bytes4 => "bytes4" true = "bytes4(0)",117	address => "address" true = "0x0000000000000000000000000000000000000000",118	string => "string" false = "\"\"",119	bytes => "bytes" false = "hex\"\"",120	bool => "bool" true = "false",121}122impl SolidityTypeName for void {123	fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {124		Ok(())125	}126	fn is_simple() -> bool {127		true128	}129	fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {130		Ok(())131	}132	fn is_void() -> bool {133		true134	}135}136137mod sealed {138	/// Not every type should be directly placed in vec.139	/// Vec encoding is not memory efficient, as every item will be padded140	/// to 32 bytes.141	/// Instead you should use specialized types (`bytes` in case of `Vec<u8>`)142	pub trait CanBePlacedInVec {}143}144145impl sealed::CanBePlacedInVec for uint256 {}146impl sealed::CanBePlacedInVec for string {}147impl sealed::CanBePlacedInVec for address {}148149impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {150	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {151		T::solidity_name(writer, tc)?;152		write!(writer, "[]")153	}154	fn is_simple() -> bool {155		false156	}157	fn solidity_default(writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {158		write!(writer, "[]")159	}160}161162pub trait SolidityTupleType {163	fn names(tc: &TypeCollector) -> Vec<String>;164	fn len() -> usize;165}166167macro_rules! count {168    () => (0usize);169    ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));170}171172macro_rules! impl_tuples {173	($($ident:ident)+) => {174		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}175		impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {176			fn names(tc: &TypeCollector) -> Vec<string> {177				let mut collected = Vec::with_capacity(Self::len());178				$({179					let mut out = string::new();180					$ident::solidity_name(&mut out, tc).expect("no fmt error");181					collected.push(out);182				})*;183				collected184			}185186			fn len() -> usize {187				count!($($ident)*)188			}189		}190		impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {191			fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {192				write!(writer, "{}", tc.collect_tuple::<Self>())193			}194			fn is_simple() -> bool {195				false196			}197			#[allow(unused_assignments)]198			fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {199				write!(writer, "{}(", tc.collect_tuple::<Self>())?;200				let mut first = true;201				$(202					if !first {203						write!(writer, ",")?;204					} else {205						first = false;206					}207					<$ident>::solidity_default(writer, tc)?;208				)*209				write!(writer, ")")210			}211		}212	};213}214215impl_tuples! {A}216impl_tuples! {A B}217impl_tuples! {A B C}218impl_tuples! {A B C D}219impl_tuples! {A B C D E}220impl_tuples! {A B C D E F}221impl_tuples! {A B C D E F G}222impl_tuples! {A B C D E F G H}223impl_tuples! {A B C D E F G H I}224impl_tuples! {A B C D E F G H I J}225226pub trait SolidityArguments {227	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;228	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;229	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;230	fn is_empty(&self) -> bool {231		self.len() == 0232	}233	fn len(&self) -> usize;234}235236#[derive(Default)]237pub struct UnnamedArgument<T>(PhantomData<*const T>);238239impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {240	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {241		if !T::is_void() {242			T::solidity_name(writer, tc)?;243			if !T::is_simple() {244				write!(writer, " memory")?;245			}246			Ok(())247		} else {248			Ok(())249		}250	}251	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {252		Ok(())253	}254	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {255		T::solidity_default(writer, tc)256	}257	fn len(&self) -> usize {258		if T::is_void() {259			0260		} else {261			1262		}263	}264}265266pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);267268impl<T> NamedArgument<T> {269	pub fn new(name: &'static str) -> Self {270		Self(name, Default::default())271	}272}273274impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {275	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {276		if !T::is_void() {277			T::solidity_name(writer, tc)?;278			if !T::is_simple() {279				write!(writer, " memory")?;280			}281			write!(writer, " {}", self.0)282		} else {283			Ok(())284		}285	}286	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {287		writeln!(writer, "\t\t{};", self.0)288	}289	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {290		T::solidity_default(writer, tc)291	}292	fn len(&self) -> usize {293		if T::is_void() {294			0295		} else {296			1297		}298	}299}300301pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);302303impl<T> SolidityEventArgument<T> {304	pub fn new(indexed: bool, name: &'static str) -> Self {305		Self(indexed, name, Default::default())306	}307}308309impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {310	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {311		if !T::is_void() {312			T::solidity_name(writer, tc)?;313			if self.0 {314				write!(writer, " indexed")?;315			}316			write!(writer, " {}", self.1)317		} else {318			Ok(())319		}320	}321	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {322		writeln!(writer, "\t\t{};", self.1)323	}324	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {325		T::solidity_default(writer, tc)326	}327	fn len(&self) -> usize {328		if T::is_void() {329			0330		} else {331			1332		}333	}334}335336impl SolidityArguments for () {337	fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {338		Ok(())339	}340	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {341		Ok(())342	}343	fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {344		Ok(())345	}346	fn len(&self) -> usize {347		0348	}349}350351#[impl_for_tuples(1, 12)]352impl SolidityArguments for Tuple {353	for_tuples!( where #( Tuple: SolidityArguments ),* );354355	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {356		let mut first = true;357		for_tuples!( #(358            if !Tuple.is_empty() {359                if !first {360                    write!(writer, ", ")?;361                }362                first = false;363                Tuple.solidity_name(writer, tc)?;364            }365        )* );366		Ok(())367	}368	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {369		for_tuples!( #(370            Tuple.solidity_get(writer)?;371        )* );372		Ok(())373	}374	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {375		if self.is_empty() {376			Ok(())377		} else if self.len() == 1 {378			for_tuples!( #(379				Tuple.solidity_default(writer, tc)?;380			)* );381			Ok(())382		} else {383			write!(writer, "(")?;384			let mut first = true;385			for_tuples!( #(386				if !Tuple.is_empty() {387					if !first {388						write!(writer, ", ")?;389					}390					first = false;391					Tuple.solidity_default(writer, tc)?;392				}393			)* );394			write!(writer, ")")?;395			Ok(())396		}397	}398	fn len(&self) -> usize {399		for_tuples!( #( Tuple.len() )+* )400	}401}402403pub trait SolidityFunctions {404	fn solidity_name(405		&self,406		is_impl: bool,407		writer: &mut impl fmt::Write,408		tc: &TypeCollector,409	) -> fmt::Result;410}411412pub enum SolidityMutability {413	Pure,414	View,415	Mutable,416}417pub struct SolidityFunction<A, R> {418	pub docs: &'static [&'static str],419	pub selector_str: &'static str,420	pub selector: u32,421	pub name: &'static str,422	pub args: A,423	pub result: R,424	pub mutability: SolidityMutability,425	pub is_payable: bool,426}427impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {428	fn solidity_name(429		&self,430		is_impl: bool,431		writer: &mut impl fmt::Write,432		tc: &TypeCollector,433	) -> fmt::Result {434		for doc in self.docs {435			writeln!(writer, "\t///{}", doc)?;436		}437		writeln!(438			writer,439			"\t/// @dev EVM selector for this function is: 0x{:0>8x},",440			self.selector441		)?;442		writeln!(writer, "\t///  or in textual repr: {}", self.selector_str)?;443		write!(writer, "\tfunction {}(", self.name)?;444		self.args.solidity_name(writer, tc)?;445		write!(writer, ")")?;446		if is_impl {447			write!(writer, " public")?;448		} else {449			write!(writer, " external")?;450		}451		match &self.mutability {452			SolidityMutability::Pure => write!(writer, " pure")?,453			SolidityMutability::View => write!(writer, " view")?,454			SolidityMutability::Mutable => {}455		}456		if self.is_payable {457			write!(writer, " payable")?;458		}459		if !self.result.is_empty() {460			write!(writer, " returns (")?;461			self.result.solidity_name(writer, tc)?;462			write!(writer, ")")?;463		}464		if is_impl {465			writeln!(writer, " {{")?;466			writeln!(writer, "\t\trequire(false, stub_error);")?;467			self.args.solidity_get(writer)?;468			match &self.mutability {469				SolidityMutability::Pure => {}470				SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,471				SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,472			}473			if !self.result.is_empty() {474				write!(writer, "\t\treturn ")?;475				self.result.solidity_default(writer, tc)?;476				writeln!(writer, ";")?;477			}478			writeln!(writer, "\t}}")?;479		} else {480			writeln!(writer, ";")?;481		}482		Ok(())483	}484}485486#[impl_for_tuples(0, 48)]487impl SolidityFunctions for Tuple {488	for_tuples!( where #( Tuple: SolidityFunctions ),* );489490	fn solidity_name(491		&self,492		is_impl: bool,493		writer: &mut impl fmt::Write,494		tc: &TypeCollector,495	) -> fmt::Result {496		let mut first = false;497		for_tuples!( #(498            Tuple.solidity_name(is_impl, writer, tc)?;499        )* );500		Ok(())501	}502}503504pub struct SolidityInterface<F: SolidityFunctions> {505	pub docs: &'static [&'static str],506	pub selector: bytes4,507	pub name: &'static str,508	pub is: &'static [&'static str],509	pub functions: F,510}511512impl<F: SolidityFunctions> SolidityInterface<F> {513	pub fn format(514		&self,515		is_impl: bool,516		out: &mut impl fmt::Write,517		tc: &TypeCollector,518	) -> fmt::Result {519		const ZERO_BYTES: [u8; 4] = [0; 4];520		for doc in self.docs {521			writeln!(out, "///{}", doc)?;522		}523		if self.selector != ZERO_BYTES {524			writeln!(525				out,526				"/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",527				u32::from_be_bytes(self.selector)528			)?;529		}530		if is_impl {531			write!(out, "contract ")?;532		} else {533			write!(out, "interface ")?;534		}535		write!(out, "{}", self.name)?;536		if !self.is.is_empty() {537			write!(out, " is")?;538			for (i, n) in self.is.iter().enumerate() {539				if i != 0 {540					write!(out, ",")?;541				}542				write!(out, " {}", n)?;543			}544		}545		writeln!(out, " {{")?;546		self.functions.solidity_name(is_impl, out, tc)?;547		writeln!(out, "}}")?;548		Ok(())549	}550}551552pub struct SolidityEvent<A> {553	pub name: &'static str,554	pub args: A,555}556557impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {558	fn solidity_name(559		&self,560		_is_impl: bool,561		writer: &mut impl fmt::Write,562		tc: &TypeCollector,563	) -> fmt::Result {564		write!(writer, "\tevent {}(", self.name)?;565		self.args.solidity_name(writer, tc)?;566		writeln!(writer, ");")567	}568}
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
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -210,18 +210,21 @@
 	/// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.
 	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())
 	}
 
 	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
 	pub fn init_foreign_collection(
 		owner: T::CrossAccountId,
+		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
 	) -> Result<CollectionId, DispatchError> {
 		let id = <PalletCommon<T>>::init_collection(
 			owner,
+			payer,
 			data,
 			CollectionFlags {
 				foreign: true,
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;
         }
       }