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
before · crates/evm-coder/procedural/src/solidity_interface.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#![allow(dead_code)]1819// NOTE: In order to understand this Rust macro better, first read this chapter20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html2223use quote::{quote, ToTokens};24use inflector::cases;25use std::fmt::Write;26use syn::{27	Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,28	MetaNameValue, PatType, PathArguments, ReturnType, Type,29	spanned::Spanned,30	parse::{Parse, ParseStream},31	parenthesized, Token, LitInt, LitStr,32};3334use crate::{35	fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,36	parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,37	snake_ident_to_screaming,38};3940struct Is {41	name: Ident,42	pascal_call_name: Ident,43	snake_call_name: Ident,44	via: Option<(Type, Ident)>,45	condition: Option<Expr>,46}47impl Is {48	fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {49		let name = &self.name;50		let pascal_call_name = &self.pascal_call_name;51		quote! {52			#name(#pascal_call_name #gen_ref)53		}54	}5556	fn expand_interface_id(&self) -> proc_macro2::TokenStream {57		let pascal_call_name = &self.pascal_call_name;58		quote! {59			interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());60		}61	}6263	fn expand_supports_interface(64		&self,65		generics: &proc_macro2::TokenStream,66	) -> proc_macro2::TokenStream {67		let pascal_call_name = &self.pascal_call_name;68		let condition = self.condition.as_ref().map(|condition| {69			quote! {70				(#condition) &&71			}72		});73		quote! {74			#condition <#pascal_call_name #generics>::supports_interface(this, interface_id)75		}76	}7778	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {79		let name = &self.name;80		quote! {81			Self::#name(call) => call.weight()82		}83	}8485	fn expand_variant_call(86		&self,87		call_name: &proc_macro2::Ident,88		generics: &proc_macro2::TokenStream,89	) -> proc_macro2::TokenStream {90		let name = &self.name;91		let pascal_call_name = &self.pascal_call_name;92		let via_typ = self93			.via94			.as_ref()95			.map(|(t, _)| quote! {#t})96			.unwrap_or_else(|| quote! {Self});97		let via_map = self98			.via99			.as_ref()100			.map(|(_, i)| quote! {.#i()})101			.unwrap_or_default();102		let condition = self.condition.as_ref().map(|condition| {103			quote! {104				if ({let this = &self; (#condition)})105			}106		});107		quote! {108			#call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {109				call,110				caller: c.caller,111				value: c.value,112			})113		}114	}115116	fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {117		let name = &self.name;118		let pascal_call_name = &self.pascal_call_name;119		quote! {120			if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {121				return Ok(Some(Self::#name(parsed_call)))122			}123		}124	}125126	fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {127		let pascal_call_name = &self.pascal_call_name;128		quote! {129			<#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);130		}131	}132133	fn expand_event_generator(&self) -> proc_macro2::TokenStream {134		let name = &self.name;135		quote! {136			#name::generate_solidity_interface(tc, is_impl);137		}138	}139}140141#[derive(Default)]142struct IsList(Vec<Is>);143impl Parse for IsList {144	fn parse(input: ParseStream) -> syn::Result<Self> {145		let mut out = vec![];146		loop {147			if input.is_empty() {148				break;149			}150			let name = input.parse::<Ident>()?;151			let lookahead = input.lookahead1();152153			let mut condition: Option<Expr> = None;154			let mut via: Option<(Type, Ident)> = None;155156			if lookahead.peek(syn::token::Paren) {157				let contents;158				parenthesized!(contents in input);159				let input = contents;160161				while !input.is_empty() {162					let lookahead = input.lookahead1();163					if lookahead.peek(Token![if]) {164						input.parse::<Token![if]>()?;165						let contents;166						parenthesized!(contents in input);167						let contents = contents.parse::<Expr>()?;168169						if condition.replace(contents).is_some() {170							return Err(syn::Error::new(input.span(), "condition is already set"));171						}172					} else if lookahead.peek(kw::via) {173						input.parse::<kw::via>()?;174						let contents;175						parenthesized!(contents in input);176177						let method = contents.parse::<Ident>()?;178						contents.parse::<kw::returns>()?;179						let ty = contents.parse::<Type>()?;180181						if via.replace((ty, method)).is_some() {182							return Err(syn::Error::new(input.span(), "via is already set"));183						}184					} else {185						return Err(lookahead.error());186					}187188					if input.peek(Token![,]) {189						input.parse::<Token![,]>()?;190					} else if !input.is_empty() {191						return Err(syn::Error::new(input.span(), "expected end"));192					}193				}194			} else if lookahead.peek(Token![,]) || input.is_empty() {195				// Pass196			} else {197				return Err(lookahead.error());198			};199			out.push(Is {200				pascal_call_name: pascal_ident_to_call(&name),201				snake_call_name: pascal_ident_to_snake_call(&name),202				name,203				via,204				condition,205			});206			if input.peek(Token![,]) {207				input.parse::<Token![,]>()?;208				continue;209			} else {210				break;211			}212		}213		Ok(Self(out))214	}215}216217pub struct InterfaceInfo {218	name: Ident,219	is: IsList,220	inline_is: IsList,221	events: IsList,222	expect_selector: Option<u32>,223}224impl Parse for InterfaceInfo {225	fn parse(input: ParseStream) -> syn::Result<Self> {226		let mut name = None;227		let mut is = None;228		let mut inline_is = None;229		let mut events = None;230		let mut expect_selector = None;231		// TODO: create proc-macro to optimize proc-macro boilerplate? :D232		loop {233			let lookahead = input.lookahead1();234			if lookahead.peek(kw::name) {235				let k = input.parse::<kw::name>()?;236				input.parse::<Token![=]>()?;237				if name.replace(input.parse::<Ident>()?).is_some() {238					return Err(syn::Error::new(k.span(), "name is already set"));239				}240			} else if lookahead.peek(kw::is) {241				let k = input.parse::<kw::is>()?;242				let contents;243				parenthesized!(contents in input);244				if is.replace(contents.parse::<IsList>()?).is_some() {245					return Err(syn::Error::new(k.span(), "is is already set"));246				}247			} else if lookahead.peek(kw::inline_is) {248				let k = input.parse::<kw::inline_is>()?;249				let contents;250				parenthesized!(contents in input);251				if inline_is.replace(contents.parse::<IsList>()?).is_some() {252					return Err(syn::Error::new(k.span(), "inline_is is already set"));253				}254			} else if lookahead.peek(kw::events) {255				let k = input.parse::<kw::events>()?;256				let contents;257				parenthesized!(contents in input);258				if events.replace(contents.parse::<IsList>()?).is_some() {259					return Err(syn::Error::new(k.span(), "events is already set"));260				}261			} else if lookahead.peek(kw::expect_selector) {262				let k = input.parse::<kw::expect_selector>()?;263				input.parse::<Token![=]>()?;264				let value = input.parse::<LitInt>()?;265				if expect_selector266					.replace(value.base10_parse::<u32>()?)267					.is_some()268				{269					return Err(syn::Error::new(k.span(), "expect_selector is already set"));270				}271			} else if input.is_empty() {272				break;273			} else {274				return Err(lookahead.error());275			}276			if input.peek(Token![,]) {277				input.parse::<Token![,]>()?;278			} else {279				break;280			}281		}282		Ok(Self {283			name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,284			is: is.unwrap_or_default(),285			inline_is: inline_is.unwrap_or_default(),286			events: events.unwrap_or_default(),287			expect_selector,288		})289	}290}291292struct MethodInfo {293	rename_selector: Option<String>,294}295impl Parse for MethodInfo {296	fn parse(input: ParseStream) -> syn::Result<Self> {297		let mut rename_selector = None;298		let lookahead = input.lookahead1();299		if lookahead.peek(kw::rename_selector) {300			let k = input.parse::<kw::rename_selector>()?;301			input.parse::<Token![=]>()?;302			if rename_selector303				.replace(input.parse::<LitStr>()?.value())304				.is_some()305			{306				return Err(syn::Error::new(k.span(), "rename_selector is already set"));307			}308		}309		Ok(Self { rename_selector })310	}311}312313enum AbiType {314	// type315	Plain(Ident),316	// (type1,type2)317	Tuple(Vec<AbiType>),318	// type[]319	Vec(Box<AbiType>),320	// type[20]321	Array(Box<AbiType>, usize),322}323impl AbiType {324	fn try_from(value: &Type) -> syn::Result<Self> {325		let value = Self::try_maybe_special_from(value)?;326		if value.is_special() {327			return Err(syn::Error::new(value.span(), "unexpected special type"));328		}329		Ok(value)330	}331	fn try_maybe_special_from(value: &Type) -> syn::Result<Self> {332		match value {333			Type::Array(arr) => {334				let wrapped = AbiType::try_from(&arr.elem)?;335				match &arr.len {336					Expr::Lit(l) => match &l.lit {337						Lit::Int(i) => {338							let num = i.base10_parse::<usize>()?;339							Ok(AbiType::Array(Box::new(wrapped), num as usize))340						}341						_ => Err(syn::Error::new(arr.len.span(), "should be int literal")),342					},343					_ => Err(syn::Error::new(arr.len.span(), "should be literal")),344				}345			}346			Type::Path(_) => {347				let path = parse_path(value)?;348				let segment = parse_path_segment(path)?;349				if segment.ident == "Vec" {350					let args = match &segment.arguments {351						PathArguments::AngleBracketed(e) => e,352						_ => {353							return Err(syn::Error::new(354								segment.arguments.span(),355								"missing Vec generic",356							))357						}358					};359					let args = &args.args;360					if args.len() != 1 {361						return Err(syn::Error::new(362							args.span(),363							"expected only one generic for vec",364						));365					}366					let arg = args.first().expect("first arg");367368					let ty = match arg {369						GenericArgument::Type(ty) => ty,370						_ => {371							return Err(syn::Error::new(372								arg.span(),373								"expected first generic to be type",374							))375						}376					};377378					let wrapped = AbiType::try_from(ty)?;379					Ok(Self::Vec(Box::new(wrapped)))380				} else {381					if !segment.arguments.is_empty() {382						return Err(syn::Error::new(383							segment.arguments.span(),384							"unexpected generic arguments for non-vec type",385						));386					}387					Ok(Self::Plain(segment.ident.clone()))388				}389			}390			Type::Tuple(t) => {391				let mut out = Vec::with_capacity(t.elems.len());392				for el in t.elems.iter() {393					out.push(AbiType::try_from(el)?)394				}395				Ok(Self::Tuple(out))396			}397			_ => Err(syn::Error::new(398				value.span(),399				"unexpected type, only arrays, plain types and tuples are supported",400			)),401		}402	}403	fn is_value(&self) -> bool {404		matches!(self, Self::Plain(v) if v == "value")405	}406	fn is_caller(&self) -> bool {407		matches!(self, Self::Plain(v) if v == "caller")408	}409	fn is_special(&self) -> bool {410		self.is_caller() || self.is_value()411	}412	fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {413		match self {414			AbiType::Plain(t) => {415				write!(buf, "{}", t)416			}417			AbiType::Tuple(t) => {418				write!(buf, "(")?;419				for (i, t) in t.iter().enumerate() {420					if i != 0 {421						write!(buf, ",")?;422					}423					t.selector_ty_buf(buf)?;424				}425				write!(buf, ")")426			}427			AbiType::Vec(v) => {428				v.selector_ty_buf(buf)?;429				write!(buf, "[]")430			}431			AbiType::Array(v, len) => {432				v.selector_ty_buf(buf)?;433				write!(buf, "[{}]", len)434			}435		}436	}437	fn selector_ty(&self) -> String {438		let mut out = String::new();439		self.selector_ty_buf(&mut out).expect("no fmt error");440		out441	}442}443impl ToTokens for AbiType {444	fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {445		match self {446			AbiType::Plain(t) => tokens.extend(quote! {#t}),447			AbiType::Tuple(t) => {448				tokens.extend(quote! {(449					#(#t),*450				)});451			}452			AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),453			AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),454		}455	}456}457458struct MethodArg {459	name: Ident,460	camel_name: String,461	ty: AbiType,462}463impl MethodArg {464	fn try_from(value: &PatType) -> syn::Result<Self> {465		let name = parse_ident_from_pat(&value.pat)?.clone();466		Ok(Self {467			camel_name: cases::camelcase::to_camel_case(&name.to_string()),468			name,469			ty: AbiType::try_maybe_special_from(&value.ty)?,470		})471	}472	fn is_value(&self) -> bool {473		self.ty.is_value()474	}475	fn is_caller(&self) -> bool {476		self.ty.is_caller()477	}478	fn is_special(&self) -> bool {479		self.ty.is_special()480	}481	fn selector_ty(&self) -> String {482		assert!(!self.is_special());483		self.ty.selector_ty()484	}485486	fn expand_call_def(&self) -> proc_macro2::TokenStream {487		assert!(!self.is_special());488		let name = &self.name;489		let ty = &self.ty;490491		quote! {492			#name: #ty493		}494	}495496	fn expand_parse(&self) -> proc_macro2::TokenStream {497		assert!(!self.is_special());498		let name = &self.name;499		quote! {500			#name: reader.abi_read()?501		}502	}503504	fn expand_call_arg(&self) -> proc_macro2::TokenStream {505		if self.is_value() {506			quote! {507				c.value.clone()508			}509		} else if self.is_caller() {510			quote! {511				c.caller.clone()512			}513		} else {514			let name = &self.name;515			quote! {516				#name517			}518		}519	}520521	fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {522		let camel_name = &self.camel_name.to_string();523		let ty = &self.ty;524		quote! {525			<NamedArgument<#ty>>::new(#camel_name)526		}527	}528}529530#[derive(PartialEq)]531enum Mutability {532	Mutable,533	View,534	Pure,535}536537/// Group all keywords for this macro. Usage example:538/// #[solidity_interface(name = "B", inline_is(A))]539mod kw {540	syn::custom_keyword!(weight);541542	syn::custom_keyword!(via);543	syn::custom_keyword!(returns);544	syn::custom_keyword!(name);545	syn::custom_keyword!(is);546	syn::custom_keyword!(inline_is);547	syn::custom_keyword!(events);548	syn::custom_keyword!(expect_selector);549550	syn::custom_keyword!(rename_selector);551}552553/// Rust methods are parsed into this structure when Solidity code is generated554struct Method {555	name: Ident,556	camel_name: String,557	pascal_name: Ident,558	screaming_name: Ident,559	selector_str: String,560	selector: u32,561	args: Vec<MethodArg>,562	has_normal_args: bool,563	mutability: Mutability,564	result: Type,565	weight: Option<Expr>,566	docs: Vec<String>,567}568impl Method {569	fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {570		let mut info = MethodInfo {571			rename_selector: None,572		};573		let mut docs = Vec::new();574		let mut weight = None;575		for attr in &value.attrs {576			let ident = parse_ident_from_path(&attr.path, false)?;577			if ident == "solidity" {578				info = attr.parse_args::<MethodInfo>()?;579			} else if ident == "doc" {580				let args = attr.parse_meta().unwrap();581				let value = match args {582					Meta::NameValue(MetaNameValue {583						lit: Lit::Str(str), ..584					}) => str.value(),585					_ => unreachable!(),586				};587				docs.push(value);588			} else if ident == "weight" {589				weight = Some(attr.parse_args::<Expr>()?);590			}591		}592		let ident = &value.sig.ident;593		let ident_str = ident.to_string();594		if !cases::snakecase::is_snake_case(&ident_str) {595			return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));596		}597598		let mut mutability = Mutability::Pure;599600		if let Some(FnArg::Receiver(receiver)) = value601			.sig602			.inputs603			.iter()604			.find(|arg| matches!(arg, FnArg::Receiver(_)))605		{606			if receiver.reference.is_none() {607				return Err(syn::Error::new(608					receiver.span(),609					"receiver should be by ref",610				));611			}612			if receiver.mutability.is_some() {613				mutability = Mutability::Mutable;614			} else {615				mutability = Mutability::View;616			}617		}618		let mut args = Vec::new();619		for typ in value620			.sig621			.inputs622			.iter()623			.filter(|arg| matches!(arg, FnArg::Typed(_)))624		{625			let typ = match typ {626				FnArg::Typed(typ) => typ,627				_ => unreachable!(),628			};629			args.push(MethodArg::try_from(typ)?);630		}631632		if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {633			return Err(syn::Error::new(634				args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),635				"payable function should be mutable",636			));637		}638639		let result = match &value.sig.output {640			ReturnType::Type(_, ty) => ty,641			_ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),642		};643		let result = parse_result_ok(result)?;644645		let camel_name = info646			.rename_selector647			.unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));648		let mut selector_str = camel_name.clone();649		selector_str.push('(');650		let mut has_normal_args = false;651		for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {652			if i != 0 {653				selector_str.push(',');654			}655			write!(selector_str, "{}", arg.selector_ty()).unwrap();656			has_normal_args = true;657		}658		selector_str.push(')');659		let selector = fn_selector_str(&selector_str);660661		Ok(Self {662			name: ident.clone(),663			camel_name,664			pascal_name: snake_ident_to_pascal(ident),665			screaming_name: snake_ident_to_screaming(ident),666			selector_str,667			selector,668			args,669			has_normal_args,670			mutability,671			result: result.clone(),672			weight,673			docs,674		})675	}676	fn expand_call_def(&self) -> proc_macro2::TokenStream {677		let defs = self678			.args679			.iter()680			.filter(|a| !a.is_special())681			.map(|a| a.expand_call_def());682		let pascal_name = &self.pascal_name;683		let docs = &self.docs;684685		if self.has_normal_args {686			quote! {687				#(#[doc = #docs])*688				#[allow(missing_docs)]689				#pascal_name {690					#(691						#defs,692					)*693				}694			}695		} else {696			quote! {#pascal_name}697		}698	}699700	fn expand_const(&self) -> proc_macro2::TokenStream {701		let screaming_name = &self.screaming_name;702		let selector = u32::to_be_bytes(self.selector);703		let selector_str = &self.selector_str;704		quote! {705			#[doc = #selector_str]706			const #screaming_name: ::evm_coder::types::bytes4 = [#(#selector,)*];707		}708	}709710	fn expand_interface_id(&self) -> proc_macro2::TokenStream {711		let screaming_name = &self.screaming_name;712		quote! {713			interface_id ^= u32::from_be_bytes(Self::#screaming_name);714		}715	}716717	fn expand_parse(&self) -> proc_macro2::TokenStream {718		let pascal_name = &self.pascal_name;719		let screaming_name = &self.screaming_name;720		if self.has_normal_args {721			let parsers = self722				.args723				.iter()724				.filter(|a| !a.is_special())725				.map(|a| a.expand_parse());726			quote! {727				Self::#screaming_name => return Ok(Some(Self::#pascal_name {728					#(729						#parsers,730					)*731				}))732			}733		} else {734			quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }735		}736	}737738	fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {739		let pascal_name = &self.pascal_name;740		let name = &self.name;741742		let matcher = if self.has_normal_args {743			let names = self744				.args745				.iter()746				.filter(|a| !a.is_special())747				.map(|a| &a.name);748749			quote! {{750				#(751					#names,752				)*753			}}754		} else {755			quote! {}756		};757758		let receiver = match self.mutability {759			Mutability::Mutable | Mutability::View => quote! {self.},760			Mutability::Pure => quote! {Self::},761		};762		let args = self.args.iter().map(|a| a.expand_call_arg());763764		quote! {765			#call_name::#pascal_name #matcher => {766				let result = #receiver #name(767					#(768						#args,769					)*770				)?;771				(&result).to_result()772			}773		}774	}775776	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {777		let pascal_name = &self.pascal_name;778		if let Some(weight) = &self.weight {779			let matcher = if self.has_normal_args {780				let names = self781					.args782					.iter()783					.filter(|a| !a.is_special())784					.map(|a| &a.name);785786				quote! {{787					#(788						#names,789					)*790				}}791			} else {792				quote! {}793			};794			quote! {795				Self::#pascal_name #matcher => (#weight).into()796			}797		} else {798			let matcher = if self.has_normal_args {799				quote! {{..}}800			} else {801				quote! {}802			};803			quote! {804				Self::#pascal_name #matcher => ().into()805			}806		}807	}808809	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {810		let camel_name = &self.camel_name;811		let mutability = match self.mutability {812			Mutability::Mutable => quote! {SolidityMutability::Mutable},813			Mutability::View => quote! { SolidityMutability::View },814			Mutability::Pure => quote! {SolidityMutability::Pure},815		};816		let result = &self.result;817818		let args = self819			.args820			.iter()821			.filter(|a| !a.is_special())822			.map(MethodArg::expand_solidity_argument);823		let docs = &self.docs;824		let selector_str = &self.selector_str;825		let selector = self.selector;826827		quote! {828			SolidityFunction {829				docs: &[#(#docs),*],830				selector_str: #selector_str,831				selector: #selector,832				name: #camel_name,833				mutability: #mutability,834				args: (835					#(836						#args,837					)*838				),839				result: <UnnamedArgument<#result>>::default(),840			}841		}842	}843}844845fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {846	if gen.params.is_empty() {847		return quote! {};848	}849	let params = gen.params.iter().map(|p| match p {850		syn::GenericParam::Type(id) => {851			let v = &id.ident;852			quote! {#v}853		}854		syn::GenericParam::Lifetime(lt) => {855			let v = &lt.lifetime;856			quote! {#v}857		}858		syn::GenericParam::Const(c) => {859			let i = &c.ident;860			quote! {#i}861		}862	});863	quote! { #(#params),* }864}865fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {866	if gen.params.is_empty() {867		return quote! {};868	}869	let list = generics_list(gen);870	quote! { <#list> }871}872fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {873	let list = generics_list(gen);874	if gen.params.len() == 1 {875		quote! {#list}876	} else {877		quote! { (#list) }878	}879}880881pub struct SolidityInterface {882	generics: Generics,883	name: Box<syn::Type>,884	info: InterfaceInfo,885	methods: Vec<Method>,886	docs: Vec<String>,887}888impl SolidityInterface {889	pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {890		let mut methods = Vec::new();891892		for item in &value.items {893			if let ImplItem::Method(method) = item {894				methods.push(Method::try_from(method)?)895			}896		}897		let mut docs = vec![];898		for attr in &value.attrs {899			let ident = parse_ident_from_path(&attr.path, false)?;900			if ident == "doc" {901				let args = attr.parse_meta().unwrap();902				let value = match args {903					Meta::NameValue(MetaNameValue {904						lit: Lit::Str(str), ..905					}) => str.value(),906					_ => unreachable!(),907				};908				docs.push(value);909			}910		}911		Ok(Self {912			generics: value.generics.clone(),913			name: value.self_ty.clone(),914			info,915			methods,916			docs,917		})918	}919	pub fn expand(self) -> proc_macro2::TokenStream {920		let name = self.name;921922		let solidity_name = self.info.name.to_string();923		let call_name = pascal_ident_to_call(&self.info.name);924		let generics = self.generics;925		let gen_ref = generics_reference(&generics);926		let gen_data = generics_data(&generics);927		let gen_where = &generics.where_clause;928929		let call_sub = self930			.info931			.inline_is932			.0933			.iter()934			.chain(self.info.is.0.iter())935			.map(|c| Is::expand_call_def(c, &gen_ref));936		let call_parse = self937			.info938			.inline_is939			.0940			.iter()941			.chain(self.info.is.0.iter())942			.map(|is| Is::expand_parse(is, &gen_ref));943		let call_variants = self944			.info945			.inline_is946			.0947			.iter()948			.chain(self.info.is.0.iter())949			.map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));950		let weight_variants = self951			.info952			.inline_is953			.0954			.iter()955			.chain(self.info.is.0.iter())956			.map(Is::expand_variant_weight);957958		let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);959		let supports_interface = self960			.info961			.is962			.0963			.iter()964			.map(|is| Is::expand_supports_interface(is, &gen_ref));965966		let calls = self.methods.iter().map(Method::expand_call_def);967		let consts = self.methods.iter().map(Method::expand_const);968		let interface_id = self.methods.iter().map(Method::expand_interface_id);969		let parsers = self.methods.iter().map(Method::expand_parse);970		let call_variants_this = self971			.methods972			.iter()973			.map(|m| Method::expand_variant_call(m, &call_name));974		let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);975		let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);976977		// TODO: Inline inline_is978		let solidity_is = self979			.info980			.is981			.0982			.iter()983			.chain(self.info.inline_is.0.iter())984			.map(|is| is.name.to_string());985		let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());986		let solidity_generators = self987			.info988			.is989			.0990			.iter()991			.chain(self.info.inline_is.0.iter())992			.map(|is| Is::expand_generator(is, &gen_ref));993		let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);994995		let docs = &self.docs;996997		if let Some(expect_selector) = &self.info.expect_selector {998			if !self.info.inline_is.0.is_empty() {999				return syn::Error::new(1000					name.span(),1001					"expect_selector is not compatible with inline_is",1002				)1003				.to_compile_error();1004			}1005			let selector = self1006				.methods1007				.iter()1008				.map(|m| m.selector)1009				.fold(0, |a, b| a ^ b);10101011			if *expect_selector != selector {1012				let mut methods = String::new();1013				for meth in self.methods.iter() {1014					write!(methods, "\n- {}", meth.selector_str).expect("write to string");1015				}1016				return syn::Error::new(name.span(), format!("expected selector mismatch, expected {expect_selector:0>8x}, but implementation has {selector:0>8x}{methods}")).to_compile_error();1017			}1018		}1019		// let methods = self.methods.iter().map(Method::solidity_def);10201021		quote! {1022			#[derive(Debug)]1023			#(#[doc = #docs])*1024			pub enum #call_name #gen_ref {1025				/// Inherited method1026				ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),1027				#(1028					#calls,1029				)*1030				#(1031					#call_sub,1032				)*1033			}1034			impl #gen_ref #call_name #gen_ref {1035				#(1036					#consts1037				)*1038				/// Return this call ERC165 selector1039				pub fn interface_id() -> ::evm_coder::types::bytes4 {1040					let mut interface_id = 0;1041					#(#interface_id)*1042					#(#inline_interface_id)*1043					u32::to_be_bytes(interface_id)1044				}1045				/// Generate solidity definitions for methods described in this interface1046				pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {1047					use evm_coder::solidity::*;1048					use core::fmt::Write;1049					let interface = SolidityInterface {1050						docs: &[#(#docs),*],1051						name: #solidity_name,1052						selector: Self::interface_id(),1053						is: &["Dummy", "ERC165", #(1054							#solidity_is,1055						)* #(1056							#solidity_events_is,1057						)* ],1058						functions: (#(1059							#solidity_functions,1060						)*),1061					};10621063					let mut out = ::evm_coder::types::string::new();1064					if #solidity_name.starts_with("Inline") {1065						out.push_str("/// @dev inlined interface\n");1066					}1067					let _ = interface.format(is_impl, &mut out, tc);1068					tc.collect(out);1069					#(1070						#solidity_event_generators1071					)*1072					#(1073						#solidity_generators1074					)*1075					if is_impl {1076						tc.collect("/// @dev common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());1077					} else {1078						tc.collect("/// @dev common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());1079					}1080				}1081			}1082			impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1083				fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1084					use ::evm_coder::abi::AbiRead;1085					match method_id {1086						::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1087							::evm_coder::ERC165Call::parse(method_id, reader)?1088							.map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1089						),1090						#(1091							#parsers,1092						)*1093						_ => {},1094					}1095					#(1096						#call_parse1097					)else*1098					return Ok(None);1099				}1100			}1101			impl #generics #call_name #gen_ref1102			#gen_where1103			{1104				/// Is this contract implements specified ERC165 selector1105				pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1106					interface_id != u32::to_be_bytes(0xffffff) && (1107						interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1108						interface_id == Self::interface_id()1109						#(1110							|| #supports_interface1111						)*1112					)1113				}1114			}1115			impl #generics ::evm_coder::Weighted for #call_name #gen_ref1116			#gen_where1117			{1118				#[allow(unused_variables)]1119				fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1120					match self {1121						#(1122							#weight_variants,1123						)*1124						// TODO: It should be very cheap, but not free1125						Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => 100u64.into(),1126						#(1127							#weight_variants_this,1128						)*1129					}1130				}1131			}1132			impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1133			#gen_where1134			{1135				#[allow(unreachable_code)] // In case of no inner calls1136				fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1137					use ::evm_coder::abi::AbiWrite;1138					match c.call {1139						#(1140							#call_variants,1141						)*1142						#call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1143							let mut writer = ::evm_coder::abi::AbiWriter::default();1144							writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1145							return Ok(writer.into());1146						}1147						_ => {},1148					}1149					let mut writer = ::evm_coder::abi::AbiWriter::default();1150					match c.call {1151						#(1152							#call_variants_this,1153						)*1154						_ => Err(::evm_coder::execution::Error::from("method is not available").into()),1155					}1156				}1157			}1158		}1159	}1160}
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
--- 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;
         }
       }