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

difftreelog

feat calculate signature in compile time

Trubnikov Sergey2022-10-11parent: #4d4a023.patch.diff
in: master

11 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1096,6 +1096,26 @@
 checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"
 
 [[package]]
+name = "const_format"
+version = "0.2.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "939dc9e2eb9077e0679d2ce32de1ded8531779360b003b4a972a7a39ec263495"
+dependencies = [
+ "const_format_proc_macros",
+]
+
+[[package]]
+name = "const_format_proc_macros"
+version = "0.2.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef196d5d972878a48da7decb7686eded338b4858fbabeed513d63a7c98b2b82d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-xid",
+]
+
+[[package]]
 name = "constant_time_eq"
 version = "0.1.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2353,6 +2373,7 @@
 version = "0.1.3"
 dependencies = [
  "concat-idents",
+ "const_format",
  "ethereum",
  "evm-coder-procedural",
  "evm-core 0.35.0 (git+https://github.com/uniquenetwork/evm?branch=unique-polkadot-v0.9.30)",
@@ -2362,6 +2383,7 @@
  "impl-trait-for-tuples",
  "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27-fee-limit)",
  "primitive-types",
+ "sha3-const",
  "similar-asserts",
  "sp-std 4.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30)",
 ]
@@ -11085,6 +11107,12 @@
 ]
 
 [[package]]
+name = "sha3-const"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af9625d558d174dbdc711248b479271c0fdca39e9d3d67f6e890b3d4251fbf8e"
+
+[[package]]
 name = "sharded-slab"
 version = "0.1.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
modifiedcrates/evm-coder/Cargo.tomldiffbeforeafterboth
--- a/crates/evm-coder/Cargo.toml
+++ b/crates/evm-coder/Cargo.toml
@@ -5,6 +5,10 @@
 edition = "2021"
 
 [dependencies]
+const_format = { version = "0.2.26", default-features = false }
+sha3-const = { version = "0.1.0", default-features = false }
+# Ethereum uses keccak (=sha3) for selectors
+# sha3 = "0.10.1"
 # evm-coder reexports those proc-macro
 evm-coder-procedural = { path = "./procedural" }
 # Evm uses primitive-types for H160, H256 and others
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
@@ -20,6 +20,7 @@
 // about Procedural Macros in Rust book:
 // https://doc.rust-lang.org/reference/procedural-macros.html
 
+use proc_macro2::{TokenStream, Group};
 use quote::{quote, ToTokens};
 use inflector::cases;
 use std::fmt::Write;
@@ -328,6 +329,7 @@
 	}
 }
 
+#[derive(Debug)]
 enum AbiType {
 	// type
 	Plain(Ident),
@@ -473,6 +475,7 @@
 	}
 }
 
+#[derive(Debug)]
 struct MethodArg {
 	name: Ident,
 	camel_name: String,
@@ -722,13 +725,25 @@
 		}
 	}
 
+	fn expand_selector(&self) -> proc_macro2::TokenStream {
+		let custom_signature = self.expand_custom_signature();
+		quote! {
+			 {
+				let a = ::evm_coder::sha3_const::Keccak256::new()
+					.update(#custom_signature.as_bytes())
+					.finalize();
+				[a[0], a[1], a[2], a[3]]
+			}
+		}
+	}
+
 	fn expand_const(&self) -> proc_macro2::TokenStream {
 		let screaming_name = &self.screaming_name;
-		let selector = u32::to_be_bytes(self.selector);
 		let selector_str = &self.selector_str;
+		let selector = &self.expand_selector();
 		quote! {
 			#[doc = #selector_str]
-			const #screaming_name: ::evm_coder::types::bytes4 = [#(#selector,)*];
+			const #screaming_name: ::evm_coder::types::bytes4 = #selector;
 		}
 	}
 
@@ -831,6 +846,59 @@
 		}
 	}
 
+	fn expand_custom_signature(&self) -> proc_macro2::TokenStream {
+		let mut first_comma = true;
+		let mut custom_signature = TokenStream::new();
+		let mut template = self.camel_name.clone() + "(";
+		self.args
+			.iter()
+			.filter_map(|a| {
+				if a.is_special() {
+					return None;
+				};
+
+				match a.ty {
+					AbiType::Plain(ref ident) => Some(ident),
+					_ => None,
+				}
+			})
+			.for_each(|ident| {
+				if !first_comma {
+					custom_signature.extend(quote!(,));
+					template.push(',');
+				} else {
+					first_comma = false;
+				};
+				template.push_str("{}");
+				let ident_str = ident.to_string();
+				match ident_str.as_str() {
+					"address" | "uint8" | "uint16" | "uint32" | "uint64" | "uint128"
+					| "uint256" | "bytes4" | "topic" | "string" | "bytes" | "void" | "caller"
+					| "bool" | "" => {
+						custom_signature.extend(quote!(#ident_str));
+					}
+					_ => {
+						custom_signature.extend(quote! {
+							#ident::SIGNATURE_STRING
+						});
+					}
+				}
+			});
+
+		template.push(')');
+		let mut template = quote!(#template);
+		template.extend(quote!(,));
+		template.extend(custom_signature);
+		let custom_signature_group = Group::new(proc_macro2::Delimiter::Parenthesis, template);
+		let mut custom_signature = quote! {
+			::evm_coder::const_format::formatcp!
+		};
+		custom_signature.extend(custom_signature_group.to_token_stream());
+
+		// println!("!!!!! {}", custom_signature);
+		custom_signature
+	}
+
 	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
 		let camel_name = &self.camel_name;
 		let mutability = match self.mutability {
@@ -847,15 +915,17 @@
 			.map(MethodArg::expand_solidity_argument);
 		let docs = &self.docs;
 		let selector_str = &self.selector_str;
-		let selector = self.selector;
+		let selector = &self.expand_selector();
 		let hide = self.hide;
+		let custom_signature = self.expand_custom_signature();
 		let is_payable = self.has_value_args;
 		quote! {
 			SolidityFunction {
 				docs: &[#(#docs),*],
 				selector_str: #selector_str,
-				selector: #selector,
 				hide: #hide,
+				selector: u32::from_be_bytes(#selector),
+				custom_signature: #custom_signature,
 				name: #camel_name,
 				mutability: #mutability,
 				is_payable: #is_payable,
modifiedcrates/evm-coder/src/lib.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -90,6 +90,8 @@
 pub use evm_coder_procedural::solidity;
 /// See [`solidity_interface`]
 pub use evm_coder_procedural::weight;
+pub use const_format;
+pub use sha3_const;
 
 /// Derives [`ToLog`] for enum
 ///
@@ -227,6 +229,14 @@
 		}
 	}
 
+	impl SignatureString for EthCrossAccount {
+		const SIGNATURE_STRING: &'static str = "(address,uint256)";
+	}
+
+	pub trait SignatureString {
+		const SIGNATURE_STRING: &'static str;
+	}
+
 	/// Convert `CrossAccountId` to `uint256`.
 	pub fn convert_cross_account_to_uint256<T: pallet_evm::account::Config>(
 		from: &T::CrossAccountId,
@@ -348,6 +358,18 @@
 		assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);
 	}
 
+	// #[test]
+	// fn function_selector_generation_1() {
+	// 	assert_eq!(
+	// 		fn_selector!(transferFromCrossAccountToCrossAccount(
+	// 			EthCrossAccount,
+	// 			EthCrossAccount,
+	// 			uint256
+	// 		)),
+	// 		2543295963
+	// 	);
+	// }
+
 	#[test]
 	fn event_topic_generation() {
 		assert_eq!(
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 collect_struct<T: StructCollect>(&self) -> String {76		self.collect(<T as StructCollect>::declaration());77		<T as StructCollect>::name()78	}79	pub fn finish(self) -> Vec<string> {80		let mut data = self.structs.into_inner().into_iter().collect::<Vec<_>>();81		data.sort_by_key(|(_, id)| Reverse(*id));82		data.into_iter().map(|(code, _)| code).collect()83	}84}8586pub trait StructCollect: 'static {87	/// Structure name.88	fn name() -> String;89	/// Structure declaration.90	fn declaration() -> String;91}9293pub trait SolidityTypeName: 'static {94	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;95	/// "simple" types are stored inline, no `memory` modifier should be used in solidity96	fn is_simple() -> bool;97	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;98	/// Specialization99	fn is_void() -> bool {100		false101	}102}103macro_rules! solidity_type_name {104    ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {105        $(106            impl SolidityTypeName for $ty {107                fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {108                    write!(writer, $name)109                }110				fn is_simple() -> bool {111					$simple112				}113				fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {114					write!(writer, $default)115				}116            }117        )*118    };119}120121solidity_type_name! {122	uint8 => "uint8" true = "0",123	uint32 => "uint32" true = "0",124	uint64 => "uint64" true = "0",125	uint128 => "uint128" true = "0",126	uint256 => "uint256" true = "0",127	bytes4 => "bytes4" true = "bytes4(0)",128	address => "address" true = "0x0000000000000000000000000000000000000000",129	string => "string" false = "\"\"",130	bytes => "bytes" false = "hex\"\"",131	bool => "bool" true = "false",132}133impl SolidityTypeName for void {134	fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {135		Ok(())136	}137	fn is_simple() -> bool {138		true139	}140	fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {141		Ok(())142	}143	fn is_void() -> bool {144		true145	}146}147148mod sealed {149	/// Not every type should be directly placed in vec.150	/// Vec encoding is not memory efficient, as every item will be padded151	/// to 32 bytes.152	/// Instead you should use specialized types (`bytes` in case of `Vec<u8>`)153	pub trait CanBePlacedInVec {}154}155156impl sealed::CanBePlacedInVec for uint256 {}157impl sealed::CanBePlacedInVec for string {}158impl sealed::CanBePlacedInVec for address {}159impl sealed::CanBePlacedInVec for EthCrossAccount {}160161impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {162	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {163		T::solidity_name(writer, tc)?;164		write!(writer, "[]")165	}166	fn is_simple() -> bool {167		false168	}169	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {170		write!(writer, "new ")?;171		T::solidity_name(writer, tc)?;172		write!(writer, "[](0)")173	}174}175176impl SolidityTupleType for EthCrossAccount {177	fn names(tc: &TypeCollector) -> Vec<string> {178		let mut collected = Vec::with_capacity(Self::len());179		{180			let mut out = string::new();181			address::solidity_name(&mut out, tc).expect("no fmt error");182			collected.push(out);183		}184		{185			let mut out = string::new();186			uint256::solidity_name(&mut out, tc).expect("no fmt error");187			collected.push(out);188		}189		collected190	}191192	fn len() -> usize {193		2194	}195}196impl SolidityTypeName for EthCrossAccount {197	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {198		write!(writer, "{}", tc.collect_struct::<Self>())199	}200201	fn is_simple() -> bool {202		false203	}204205	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {206		write!(writer, "{}(", tc.collect_tuple::<Self>())?;207		address::solidity_default(writer, tc)?;208		write!(writer, ",")?;209		uint256::solidity_default(writer, tc)?;210		write!(writer, ")")211	}212}213214impl StructCollect for EthCrossAccount {215	fn name() -> String {216		"EthCrossAccount".into()217	}218219	fn declaration() -> String {220		let mut str = String::new();221		writeln!(str, "/// @dev Cross account struct").unwrap();222		writeln!(str, "struct {} {{", Self::name()).unwrap();223		writeln!(str, "\taddress eth;").unwrap();224		writeln!(str, "\tuint256 sub;").unwrap();225		writeln!(str, "}}").unwrap();226		str227	}228}229230pub trait SolidityTupleType {231	fn names(tc: &TypeCollector) -> Vec<String>;232	fn len() -> usize;233}234235macro_rules! count {236    () => (0usize);237    ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));238}239240macro_rules! impl_tuples {241	($($ident:ident)+) => {242		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}243		impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {244			fn names(tc: &TypeCollector) -> Vec<string> {245				let mut collected = Vec::with_capacity(Self::len());246				$({247					let mut out = string::new();248					$ident::solidity_name(&mut out, tc).expect("no fmt error");249					collected.push(out);250				})*;251				collected252			}253254			fn len() -> usize {255				count!($($ident)*)256			}257		}258		impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {259			fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {260				write!(writer, "{}", tc.collect_tuple::<Self>())261			}262			fn is_simple() -> bool {263				false264			}265			#[allow(unused_assignments)]266			fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {267				write!(writer, "{}(", tc.collect_tuple::<Self>())?;268				let mut first = true;269				$(270					if !first {271						write!(writer, ",")?;272					} else {273						first = false;274					}275					<$ident>::solidity_default(writer, tc)?;276				)*277				write!(writer, ")")278			}279		}280	};281}282283impl_tuples! {A}284impl_tuples! {A B}285impl_tuples! {A B C}286impl_tuples! {A B C D}287impl_tuples! {A B C D E}288impl_tuples! {A B C D E F}289impl_tuples! {A B C D E F G}290impl_tuples! {A B C D E F G H}291impl_tuples! {A B C D E F G H I}292impl_tuples! {A B C D E F G H I J}293294pub trait SolidityArguments {295	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;296	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result;297	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;298	fn is_empty(&self) -> bool {299		self.len() == 0300	}301	fn len(&self) -> usize;302}303304#[derive(Default)]305pub struct UnnamedArgument<T>(PhantomData<*const T>);306307impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {308	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {309		if !T::is_void() {310			T::solidity_name(writer, tc)?;311			if !T::is_simple() {312				write!(writer, " memory")?;313			}314			Ok(())315		} else {316			Ok(())317		}318	}319	fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {320		Ok(())321	}322	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {323		T::solidity_default(writer, tc)324	}325	fn len(&self) -> usize {326		if T::is_void() {327			0328		} else {329			1330		}331	}332}333334pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);335336impl<T> NamedArgument<T> {337	pub fn new(name: &'static str) -> Self {338		Self(name, Default::default())339	}340}341342impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {343	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {344		if !T::is_void() {345			T::solidity_name(writer, tc)?;346			if !T::is_simple() {347				write!(writer, " memory")?;348			}349			write!(writer, " {}", self.0)350		} else {351			Ok(())352		}353	}354	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {355		writeln!(writer, "\t{prefix}\t{};", self.0)356	}357	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {358		T::solidity_default(writer, tc)359	}360	fn len(&self) -> usize {361		if T::is_void() {362			0363		} else {364			1365		}366	}367}368369pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);370371impl<T> SolidityEventArgument<T> {372	pub fn new(indexed: bool, name: &'static str) -> Self {373		Self(indexed, name, Default::default())374	}375}376377impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {378	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {379		if !T::is_void() {380			T::solidity_name(writer, tc)?;381			if self.0 {382				write!(writer, " indexed")?;383			}384			write!(writer, " {}", self.1)385		} else {386			Ok(())387		}388	}389	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {390		writeln!(writer, "\t{prefix}\t{};", self.1)391	}392	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {393		T::solidity_default(writer, tc)394	}395	fn len(&self) -> usize {396		if T::is_void() {397			0398		} else {399			1400		}401	}402}403404impl SolidityArguments for () {405	fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {406		Ok(())407	}408	fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {409		Ok(())410	}411	fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {412		Ok(())413	}414	fn len(&self) -> usize {415		0416	}417}418419#[impl_for_tuples(1, 12)]420impl SolidityArguments for Tuple {421	for_tuples!( where #( Tuple: SolidityArguments ),* );422423	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {424		let mut first = true;425		for_tuples!( #(426            if !Tuple.is_empty() {427                if !first {428                    write!(writer, ", ")?;429                }430                first = false;431                Tuple.solidity_name(writer, tc)?;432            }433        )* );434		Ok(())435	}436	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {437		for_tuples!( #(438            Tuple.solidity_get(prefix, writer)?;439        )* );440		Ok(())441	}442	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {443		if self.is_empty() {444			Ok(())445		} else if self.len() == 1 {446			for_tuples!( #(447				Tuple.solidity_default(writer, tc)?;448			)* );449			Ok(())450		} else {451			write!(writer, "(")?;452			let mut first = true;453			for_tuples!( #(454				if !Tuple.is_empty() {455					if !first {456						write!(writer, ", ")?;457					}458					first = false;459					Tuple.solidity_default(writer, tc)?;460				}461			)* );462			write!(writer, ")")?;463			Ok(())464		}465	}466	fn len(&self) -> usize {467		for_tuples!( #( Tuple.len() )+* )468	}469}470471pub trait SolidityFunctions {472	fn solidity_name(473		&self,474		is_impl: bool,475		writer: &mut impl fmt::Write,476		tc: &TypeCollector,477	) -> fmt::Result;478}479480pub enum SolidityMutability {481	Pure,482	View,483	Mutable,484}485pub struct SolidityFunction<A, R> {486	pub docs: &'static [&'static str],487	pub selector_str: &'static str,488	pub selector: u32,489	pub hide: bool,490	pub name: &'static str,491	pub args: A,492	pub result: R,493	pub mutability: SolidityMutability,494	pub is_payable: bool,495}496impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {497	fn solidity_name(498		&self,499		is_impl: bool,500		writer: &mut impl fmt::Write,501		tc: &TypeCollector,502	) -> fmt::Result {503		let hide_comment = self.hide.then(|| "// ").unwrap_or("");504		for doc in self.docs {505			writeln!(writer, "\t{hide_comment}///{}", doc)?;506		}507		writeln!(508			writer,509			"\t{hide_comment}/// @dev EVM selector for this function is: 0x{:0>8x},",510			self.selector511		)?;512		writeln!(513			writer,514			"\t{hide_comment}///  or in textual repr: {}",515			self.selector_str516		)?;517		write!(writer, "\t{hide_comment}function {}(", self.name)?;518		self.args.solidity_name(writer, tc)?;519		write!(writer, ")")?;520		if is_impl {521			write!(writer, " public")?;522		} else {523			write!(writer, " external")?;524		}525		match &self.mutability {526			SolidityMutability::Pure => write!(writer, " pure")?,527			SolidityMutability::View => write!(writer, " view")?,528			SolidityMutability::Mutable => {}529		}530		if self.is_payable {531			write!(writer, " payable")?;532		}533		if !self.result.is_empty() {534			write!(writer, " returns (")?;535			self.result.solidity_name(writer, tc)?;536			write!(writer, ")")?;537		}538		if is_impl {539			writeln!(writer, " {{")?;540			writeln!(writer, "\t{hide_comment}\trequire(false, stub_error);")?;541			self.args.solidity_get(hide_comment, writer)?;542			match &self.mutability {543				SolidityMutability::Pure => {}544				SolidityMutability::View => writeln!(writer, "\t{hide_comment}\tdummy;")?,545				SolidityMutability::Mutable => writeln!(writer, "\t{hide_comment}\tdummy = 0;")?,546			}547			if !self.result.is_empty() {548				write!(writer, "\t{hide_comment}\treturn ")?;549				self.result.solidity_default(writer, tc)?;550				writeln!(writer, ";")?;551			}552			writeln!(writer, "\t{hide_comment}}}")?;553		} else {554			writeln!(writer, ";")?;555		}556		if self.hide {557			writeln!(writer, "// FORMATTING: FORCE NEWLINE")?;558		}559		Ok(())560	}561}562563#[impl_for_tuples(0, 48)]564impl SolidityFunctions for Tuple {565	for_tuples!( where #( Tuple: SolidityFunctions ),* );566567	fn solidity_name(568		&self,569		is_impl: bool,570		writer: &mut impl fmt::Write,571		tc: &TypeCollector,572	) -> fmt::Result {573		let mut first = false;574		for_tuples!( #(575            Tuple.solidity_name(is_impl, writer, tc)?;576        )* );577		Ok(())578	}579}580581pub struct SolidityInterface<F: SolidityFunctions> {582	pub docs: &'static [&'static str],583	pub selector: bytes4,584	pub name: &'static str,585	pub is: &'static [&'static str],586	pub functions: F,587}588589impl<F: SolidityFunctions> SolidityInterface<F> {590	pub fn format(591		&self,592		is_impl: bool,593		out: &mut impl fmt::Write,594		tc: &TypeCollector,595	) -> fmt::Result {596		const ZERO_BYTES: [u8; 4] = [0; 4];597		for doc in self.docs {598			writeln!(out, "///{}", doc)?;599		}600		if self.selector != ZERO_BYTES {601			writeln!(602				out,603				"/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",604				u32::from_be_bytes(self.selector)605			)?;606		}607		if is_impl {608			write!(out, "contract ")?;609		} else {610			write!(out, "interface ")?;611		}612		write!(out, "{}", self.name)?;613		if !self.is.is_empty() {614			write!(out, " is")?;615			for (i, n) in self.is.iter().enumerate() {616				if i != 0 {617					write!(out, ",")?;618				}619				write!(out, " {}", n)?;620			}621		}622		writeln!(out, " {{")?;623		self.functions.solidity_name(is_impl, out, tc)?;624		writeln!(out, "}}")?;625		Ok(())626	}627}628629pub struct SolidityEvent<A> {630	pub name: &'static str,631	pub args: A,632}633634impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {635	fn solidity_name(636		&self,637		_is_impl: bool,638		writer: &mut impl fmt::Write,639		tc: &TypeCollector,640	) -> fmt::Result {641		write!(writer, "\tevent {}(", self.name)?;642		self.args.solidity_name(writer, tc)?;643		writeln!(writer, ");")644	}645}
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 FunctionSelectorMaker {39	pub name: string,40	pub args: Vec<fn() -> string>,41}4243#[derive(Default)]44pub struct TypeCollector {45	/// Code => id46	/// id ordering is required to perform topo-sort on the resulting data47	structs: RefCell<BTreeMap<string, usize>>,48	anonymous: RefCell<BTreeMap<Vec<string>, usize>>,49	id: Cell<usize>,50}51impl TypeCollector {52	pub fn new() -> Self {53		Self::default()54	}55	pub fn collect(&self, item: string) {56		let id = self.next_id();57		self.structs.borrow_mut().insert(item, id);58	}59	pub fn next_id(&self) -> usize {60		let v = self.id.get();61		self.id.set(v + 1);62		v63	}64	pub fn collect_tuple<T: SolidityTupleType>(&self) -> String {65		let names = T::names(self);66		if let Some(id) = self.anonymous.borrow().get(&names).cloned() {67			return format!("Tuple{}", id);68		}69		let id = self.next_id();70		let mut str = String::new();71		writeln!(str, "/// @dev anonymous struct").unwrap();72		writeln!(str, "struct Tuple{} {{", id).unwrap();73		for (i, name) in names.iter().enumerate() {74			writeln!(str, "\t{} field_{};", name, i).unwrap();75		}76		writeln!(str, "}}").unwrap();77		self.collect(str);78		self.anonymous.borrow_mut().insert(names, id);79		format!("Tuple{}", id)80	}81	pub fn collect_struct<T: StructCollect>(&self) -> String {82		self.collect(<T as StructCollect>::declaration());83		<T as StructCollect>::name()84	}85	pub fn finish(self) -> Vec<string> {86		let mut data = self.structs.into_inner().into_iter().collect::<Vec<_>>();87		data.sort_by_key(|(_, id)| Reverse(*id));88		data.into_iter().map(|(code, _)| code).collect()89	}90}9192pub trait StructCollect: 'static {93	/// Structure name.94	fn name() -> String;95	/// Structure declaration.96	fn declaration() -> String;97}9899pub trait SolidityTypeName: 'static {100	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;101	/// "simple" types are stored inline, no `memory` modifier should be used in solidity102	fn is_simple() -> bool;103	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;104	/// Specialization105	fn is_void() -> bool {106		false107	}108}109macro_rules! solidity_type_name {110    ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {111        $(112            impl SolidityTypeName for $ty {113                fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {114                    write!(writer, $name)115                }116				fn is_simple() -> bool {117					$simple118				}119				fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {120					write!(writer, $default)121				}122            }123        )*124    };125}126127solidity_type_name! {128	uint8 => "uint8" true = "0",129	uint32 => "uint32" true = "0",130	uint64 => "uint64" true = "0",131	uint128 => "uint128" true = "0",132	uint256 => "uint256" true = "0",133	bytes4 => "bytes4" true = "bytes4(0)",134	address => "address" true = "0x0000000000000000000000000000000000000000",135	string => "string" false = "\"\"",136	bytes => "bytes" false = "hex\"\"",137	bool => "bool" true = "false",138}139impl SolidityTypeName for void {140	fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {141		Ok(())142	}143	fn is_simple() -> bool {144		true145	}146	fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {147		Ok(())148	}149	fn is_void() -> bool {150		true151	}152}153154mod sealed {155	/// Not every type should be directly placed in vec.156	/// Vec encoding is not memory efficient, as every item will be padded157	/// to 32 bytes.158	/// Instead you should use specialized types (`bytes` in case of `Vec<u8>`)159	pub trait CanBePlacedInVec {}160}161162impl sealed::CanBePlacedInVec for uint256 {}163impl sealed::CanBePlacedInVec for string {}164impl sealed::CanBePlacedInVec for address {}165impl sealed::CanBePlacedInVec for EthCrossAccount {}166167impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {168	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {169		T::solidity_name(writer, tc)?;170		write!(writer, "[]")171	}172	fn is_simple() -> bool {173		false174	}175	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {176		write!(writer, "new ")?;177		T::solidity_name(writer, tc)?;178		write!(writer, "[](0)")179	}180}181182impl SolidityTupleType for EthCrossAccount {183	fn names(tc: &TypeCollector) -> Vec<string> {184		let mut collected = Vec::with_capacity(Self::len());185		{186			let mut out = string::new();187			address::solidity_name(&mut out, tc).expect("no fmt error");188			collected.push(out);189		}190		{191			let mut out = string::new();192			uint256::solidity_name(&mut out, tc).expect("no fmt error");193			collected.push(out);194		}195		collected196	}197198	fn len() -> usize {199		2200	}201}202impl SolidityTypeName for EthCrossAccount {203	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {204		write!(writer, "{}", tc.collect_struct::<Self>())205	}206207	fn is_simple() -> bool {208		false209	}210211	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {212		write!(writer, "{}(", tc.collect_tuple::<Self>())?;213		address::solidity_default(writer, tc)?;214		write!(writer, ",")?;215		uint256::solidity_default(writer, tc)?;216		write!(writer, ")")217	}218}219220impl StructCollect for EthCrossAccount {221	fn name() -> String {222		"EthCrossAccount".into()223	}224225	fn declaration() -> String {226		let mut str = String::new();227		writeln!(str, "/// @dev Cross account struct").unwrap();228		writeln!(str, "struct {} {{", Self::name()).unwrap();229		writeln!(str, "\taddress eth;").unwrap();230		writeln!(str, "\tuint256 sub;").unwrap();231		writeln!(str, "}}").unwrap();232		str233	}234}235236pub trait SolidityTupleType {237	fn names(tc: &TypeCollector) -> Vec<String>;238	fn len() -> usize;239}240241macro_rules! count {242    () => (0usize);243    ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));244}245246macro_rules! impl_tuples {247	($($ident:ident)+) => {248		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}249		impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {250			fn names(tc: &TypeCollector) -> Vec<string> {251				let mut collected = Vec::with_capacity(Self::len());252				$({253					let mut out = string::new();254					$ident::solidity_name(&mut out, tc).expect("no fmt error");255					collected.push(out);256				})*;257				collected258			}259260			fn len() -> usize {261				count!($($ident)*)262			}263		}264		impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {265			fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {266				write!(writer, "{}", tc.collect_tuple::<Self>())267			}268			fn is_simple() -> bool {269				false270			}271			#[allow(unused_assignments)]272			fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {273				write!(writer, "{}(", tc.collect_tuple::<Self>())?;274				let mut first = true;275				$(276					if !first {277						write!(writer, ",")?;278					} else {279						first = false;280					}281					<$ident>::solidity_default(writer, tc)?;282				)*283				write!(writer, ")")284			}285		}286	};287}288289impl_tuples! {A}290impl_tuples! {A B}291impl_tuples! {A B C}292impl_tuples! {A B C D}293impl_tuples! {A B C D E}294impl_tuples! {A B C D E F}295impl_tuples! {A B C D E F G}296impl_tuples! {A B C D E F G H}297impl_tuples! {A B C D E F G H I}298impl_tuples! {A B C D E F G H I J}299300pub trait SolidityArguments {301	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;302	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result;303	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;304	fn is_empty(&self) -> bool {305		self.len() == 0306	}307	fn len(&self) -> usize;308}309310#[derive(Default)]311pub struct UnnamedArgument<T>(PhantomData<*const T>);312313impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {314	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {315		if !T::is_void() {316			T::solidity_name(writer, tc)?;317			if !T::is_simple() {318				write!(writer, " memory")?;319			}320			Ok(())321		} else {322			Ok(())323		}324	}325	fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {326		Ok(())327	}328	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {329		T::solidity_default(writer, tc)330	}331	fn len(&self) -> usize {332		if T::is_void() {333			0334		} else {335			1336		}337	}338}339340pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);341342impl<T> NamedArgument<T> {343	pub fn new(name: &'static str) -> Self {344		Self(name, Default::default())345	}346}347348impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {349	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {350		if !T::is_void() {351			T::solidity_name(writer, tc)?;352			if !T::is_simple() {353				write!(writer, " memory")?;354			}355			write!(writer, " {}", self.0)356		} else {357			Ok(())358		}359	}360	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {361		writeln!(writer, "\t{prefix}\t{};", self.0)362	}363	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {364		T::solidity_default(writer, tc)365	}366	fn len(&self) -> usize {367		if T::is_void() {368			0369		} else {370			1371		}372	}373}374375pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);376377impl<T> SolidityEventArgument<T> {378	pub fn new(indexed: bool, name: &'static str) -> Self {379		Self(indexed, name, Default::default())380	}381}382383impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {384	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {385		if !T::is_void() {386			T::solidity_name(writer, tc)?;387			if self.0 {388				write!(writer, " indexed")?;389			}390			write!(writer, " {}", self.1)391		} else {392			Ok(())393		}394	}395	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {396		writeln!(writer, "\t{prefix}\t{};", self.1)397	}398	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {399		T::solidity_default(writer, tc)400	}401	fn len(&self) -> usize {402		if T::is_void() {403			0404		} else {405			1406		}407	}408}409410impl SolidityArguments for () {411	fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {412		Ok(())413	}414	fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {415		Ok(())416	}417	fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {418		Ok(())419	}420	fn len(&self) -> usize {421		0422	}423}424425#[impl_for_tuples(1, 12)]426impl SolidityArguments for Tuple {427	for_tuples!( where #( Tuple: SolidityArguments ),* );428429	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {430		let mut first = true;431		for_tuples!( #(432            if !Tuple.is_empty() {433                if !first {434                    write!(writer, ", ")?;435                }436                first = false;437                Tuple.solidity_name(writer, tc)?;438            }439        )* );440		Ok(())441	}442	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {443		for_tuples!( #(444            Tuple.solidity_get(prefix, writer)?;445        )* );446		Ok(())447	}448	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {449		if self.is_empty() {450			Ok(())451		} else if self.len() == 1 {452			for_tuples!( #(453				Tuple.solidity_default(writer, tc)?;454			)* );455			Ok(())456		} else {457			write!(writer, "(")?;458			let mut first = true;459			for_tuples!( #(460				if !Tuple.is_empty() {461					if !first {462						write!(writer, ", ")?;463					}464					first = false;465					Tuple.solidity_default(writer, tc)?;466				}467			)* );468			write!(writer, ")")?;469			Ok(())470		}471	}472	fn len(&self) -> usize {473		for_tuples!( #( Tuple.len() )+* )474	}475}476477pub trait SolidityFunctions {478	fn solidity_name(479		&self,480		is_impl: bool,481		writer: &mut impl fmt::Write,482		tc: &TypeCollector,483	) -> fmt::Result;484}485486pub enum SolidityMutability {487	Pure,488	View,489	Mutable,490}491492// fn fn_selector_str(input: &str) -> u32 {493// 	use sha3::Digest;494// 	let mut hasher = sha3::Keccak256::new();495// 	hasher.update(input.as_bytes());496// 	let result = hasher.finalize();497498// 	let mut selector_bytes = [0; 4];499// 	selector_bytes.copy_from_slice(&result[0..4]);500501// 	u32::from_be_bytes(selector_bytes)502// }503504pub struct SolidityFunction<A, R> {505	pub docs: &'static [&'static str],506	pub selector_str: &'static str,507	pub selector: u32,508	pub hide: bool,509	pub custom_signature: &'static str,510	pub name: &'static str,511	pub args: A,512	pub result: R,513	pub mutability: SolidityMutability,514	pub is_payable: bool,515}516impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {517	fn solidity_name(518		&self,519		is_impl: bool,520		writer: &mut impl fmt::Write,521		tc: &TypeCollector,522	) -> fmt::Result {523		let hide_comment = self.hide.then(|| "// ").unwrap_or("");524		for doc in self.docs {525			writeln!(writer, "\t{hide_comment}///{}", doc)?;526		}527		writeln!(528			writer,529			"\t{hide_comment}/// @dev EVM selector for this function is: 0x{:0>8x},",530			self.selector531		)?;532		writeln!(533			writer,534			"\t{hide_comment}///  or in textual repr: {}",535			self.custom_signature536		)?;537		write!(writer, "\t{hide_comment}function {}(", self.name)?;538		self.args.solidity_name(writer, tc)?;539		write!(writer, ")")?;540		if is_impl {541			write!(writer, " public")?;542		} else {543			write!(writer, " external")?;544		}545		match &self.mutability {546			SolidityMutability::Pure => write!(writer, " pure")?,547			SolidityMutability::View => write!(writer, " view")?,548			SolidityMutability::Mutable => {}549		}550		if self.is_payable {551			write!(writer, " payable")?;552		}553		if !self.result.is_empty() {554			write!(writer, " returns (")?;555			self.result.solidity_name(writer, tc)?;556			write!(writer, ")")?;557		}558		if is_impl {559			writeln!(writer, " {{")?;560			writeln!(writer, "\t{hide_comment}\trequire(false, stub_error);")?;561			self.args.solidity_get(hide_comment, writer)?;562			match &self.mutability {563				SolidityMutability::Pure => {}564				SolidityMutability::View => writeln!(writer, "\t{hide_comment}\tdummy;")?,565				SolidityMutability::Mutable => writeln!(writer, "\t{hide_comment}\tdummy = 0;")?,566			}567			if !self.result.is_empty() {568				write!(writer, "\t{hide_comment}\treturn ")?;569				self.result.solidity_default(writer, tc)?;570				writeln!(writer, ";")?;571			}572			writeln!(writer, "\t{hide_comment}}}")?;573		} else {574			writeln!(writer, ";")?;575		}576		if self.hide {577			writeln!(writer, "// FORMATTING: FORCE NEWLINE")?;578		}579		Ok(())580	}581}582583#[impl_for_tuples(0, 48)]584impl SolidityFunctions for Tuple {585	for_tuples!( where #( Tuple: SolidityFunctions ),* );586587	fn solidity_name(588		&self,589		is_impl: bool,590		writer: &mut impl fmt::Write,591		tc: &TypeCollector,592	) -> fmt::Result {593		let mut first = false;594		for_tuples!( #(595            Tuple.solidity_name(is_impl, writer, tc)?;596        )* );597		Ok(())598	}599}600601pub struct SolidityInterface<F: SolidityFunctions> {602	pub docs: &'static [&'static str],603	pub selector: bytes4,604	pub name: &'static str,605	pub is: &'static [&'static str],606	pub functions: F,607}608609impl<F: SolidityFunctions> SolidityInterface<F> {610	pub fn format(611		&self,612		is_impl: bool,613		out: &mut impl fmt::Write,614		tc: &TypeCollector,615	) -> fmt::Result {616		const ZERO_BYTES: [u8; 4] = [0; 4];617		for doc in self.docs {618			writeln!(out, "///{}", doc)?;619		}620		if self.selector != ZERO_BYTES {621			writeln!(622				out,623				"/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",624				u32::from_be_bytes(self.selector)625			)?;626		}627		if is_impl {628			write!(out, "contract ")?;629		} else {630			write!(out, "interface ")?;631		}632		write!(out, "{}", self.name)?;633		if !self.is.is_empty() {634			write!(out, " is")?;635			for (i, n) in self.is.iter().enumerate() {636				if i != 0 {637					write!(out, ",")?;638				}639				write!(out, " {}", n)?;640			}641		}642		writeln!(out, " {{")?;643		self.functions.solidity_name(is_impl, out, tc)?;644		writeln!(out, "}}")?;645		Ok(())646	}647}648649pub struct SolidityEvent<A> {650	pub name: &'static str,651	pub args: A,652}653654impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {655	fn solidity_name(656		&self,657		_is_impl: bool,658		writer: &mut impl fmt::Write,659		tc: &TypeCollector,660	) -> fmt::Result {661		write!(writer, "\tevent {}(", self.name)?;662		self.args.solidity_name(writer, tc)?;663		writeln!(writer, ");")664	}665}
modifiedpallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth
--- a/pallets/evm-contract-helpers/Cargo.toml
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -27,7 +27,7 @@
 evm-coder = { default-features = false, path = '../../crates/evm-coder' }
 pallet-common = { default-features = false, path = '../../pallets/common' }
 pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
-pallet-evm-transaction-payment = {  default-features = false, path = '../../pallets/evm-transaction-payment' }
+pallet-evm-transaction-payment = { default-features = false, path = '../../pallets/evm-transaction-payment' }
 up-data-structs = { default-features = false, path = '../../primitives/data-structs', features = [
     'serde1',
 ] }
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -16,6 +16,8 @@
 
 //! Implementation of magic contract
 
+extern crate alloc;
+use alloc::{format, string::ToString};
 use core::marker::PhantomData;
 use evm_coder::{
 	abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -16,6 +16,8 @@
 
 //! ERC-20 standart support implementation.
 
+extern crate alloc;
+use alloc::{format, string::ToString};
 use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
 use core::convert::TryInto;
 use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -20,6 +20,7 @@
 //! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
 
 extern crate alloc;
+use alloc::{format, string::ToString};
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
modifiedpallets/refungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -26,7 +26,9 @@
 struct-versioning = { path = "../../crates/struct-versioning" }
 up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
 ethereum = { version = "0.12.0", default-features = false }
-scale-info = { version = "2.0.1", default-features = false, features = ["derive",] }
+scale-info = { version = "2.0.1", default-features = false, features = [
+    "derive",
+] }
 derivative = { version = "2.2.0", features = ["use_core"] }
 
 [features]
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,6 +21,7 @@
 
 extern crate alloc;
 
+use alloc::{format, string::ToString};
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,