git.delta.rocks / unique-network / refs/commits / 15e4512df81d

difftreelog

source

crates/evm-coder/src/lib.rs12.4 KiBsourcehistory
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#![doc = include_str!("../README.md")]18// #![deny(missing_docs)]19#![warn(missing_docs)]20#![macro_use]21#![cfg_attr(not(feature = "std"), no_std)]22#[cfg(not(feature = "std"))]23extern crate alloc;2425use abi::{AbiRead, AbiReader, AbiWriter};26pub use evm_coder_procedural::{event_topic, fn_selector};27pub mod abi;28pub use events::{ToLog, ToTopic};29use execution::DispatchInfo;30pub mod execution;31#[macro_use]32pub mod custom_signature;3334/// Derives call enum implementing [`crate::Callable`], [`crate::Weighted`]35/// and [`crate::Call`] from impl block.36///37/// ## Macro syntax38///39/// `#[solidity_interface(name, is, inline_is, events)]`40/// - *name* - used in generated code, and for Call enum name41/// - *is* - used to provide inheritance in Solidity42/// - *inline_is* - same as `is`, but ERC165::SupportsInterface will work differently: For `is` SupportsInterface(A) will return true43///   if A is one of the interfaces the contract is inherited from (e.g. B is created as `is(A)`). If B is created as `inline_is(A)`44///   SupportsInterface(A) will internally create a new interface that combines all methods of A and B, so SupportsInterface(A) will return45///   false.46///47/// `#[weight(value)]`48/// Can be added to every method of impl block, used for deriving [`crate::Weighted`], which49/// is used by substrate bridge.50/// - *value*: expression, which evaluates to weight required to call this method.51/// This expression can use call arguments to calculate non-constant execution time.52/// This expression should evaluate faster than actual execution does, and may provide worse case53/// than one is called.54///55/// `#[solidity_interface(rename_selector)]`56/// - *rename_selector* - by default, selector name will be generated by transforming method name57/// from snake_case to camelCase. Use this option, if other naming convention is required.58/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name59/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`60/// explicitly.61///62/// Both contract and contract methods may have doccomments, which will end up in a generated63/// solidity interface file, thus you should use [solidity syntax](https://docs.soliditylang.org/en/latest/natspec-format.html) for writing documentation in this macro64///65/// ## Example66///67/// ```ignore68/// struct SuperContract;69/// struct InlineContract;70/// struct Contract;71///72/// #[derive(ToLog)]73/// enum ContractEvents {74///     Event(#[indexed] uint32),75/// }76///77/// /// @dev This contract provides function to multiply two numbers78/// #[solidity_interface(name = MyContract, is(SuperContract), inline_is(InlineContract))]79/// impl Contract {80///     /// Multiply two numbers81///     /// @param a First number82///     /// @param b Second number83///     /// @return uint32 Product of two passed numbers84///     /// @dev This function returns error in case of overflow85///     #[weight(200 + a + b)]86///     #[solidity_interface(rename_selector = "mul")]87///     fn mul(&mut self, a: uint32, b: uint32) -> Result<uint32> {88///         Ok(a.checked_mul(b).ok_or("overflow")?)89///     }90/// }91/// ```92pub use evm_coder_procedural::solidity_interface;93/// See [`solidity_interface`]94pub use evm_coder_procedural::solidity;95/// See [`solidity_interface`]96pub use evm_coder_procedural::weight;97pub use const_format;98pub use sha3_const;99100/// Derives [`ToLog`] for enum101///102/// Selectors will be derived from variant names, there is currently no way to have custom naming103/// for them104///105/// `#[indexed]`106/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data107pub use evm_coder_procedural::ToLog;108109// Api of those modules shouldn't be consumed directly, it is only exported for usage in proc macros110#[doc(hidden)]111pub mod events;112#[doc(hidden)]113pub mod solidity;114115/// Solidity type definitions (aliases from solidity name to rust type)116/// To be used in [`solidity_interface`] definitions, to make sure there is no117/// type conflict between Rust code and generated definitions118pub mod types {119	#![allow(non_camel_case_types, missing_docs)]120121	#[cfg(not(feature = "std"))]122	use alloc::{vec::Vec};123	use pallet_evm::account::CrossAccountId;124	use primitive_types::{U256, H160, H256};125	use core::str::from_utf8;126127	use crate::custom_signature::SIGNATURE_SIZE_LIMIT;128129	pub trait Signature {130		const SIGNATURE: [u8; SIGNATURE_SIZE_LIMIT];131		const SIGNATURE_LEN: usize;132133		fn as_str() -> &'static str {134			from_utf8(&Self::SIGNATURE[..Self::SIGNATURE_LEN]).expect("bad utf-8")135		}136	}137138	impl Signature for bool {139		make_signature!(new fixed("bool"));140	}141142	macro_rules! define_simple_type {143		(type $ident:ident = $ty:ty) => {144			pub type $ident = $ty;145			impl Signature for $ty {146				make_signature!(new fixed(stringify!($ident)));147			}148		};149	}150151	define_simple_type!(type address = H160);152153	define_simple_type!(type uint8 = u8);154	define_simple_type!(type uint16 = u16);155	define_simple_type!(type uint32 = u32);156	define_simple_type!(type uint64 = u64);157	define_simple_type!(type uint128 = u128);158	define_simple_type!(type uint256 = U256);159	define_simple_type!(type bytes4 = [u8; 4]);160161	define_simple_type!(type topic = H256);162163	#[cfg(not(feature = "std"))]164	define_simple_type!(type string = ::alloc::string::String);165	#[cfg(feature = "std")]166	define_simple_type!(type string = ::std::string::String);167168	#[derive(Default, Debug)]169	pub struct bytes(pub Vec<u8>);170	impl Signature for bytes {171		make_signature!(new fixed("bytes"));172	}173174	/// Solidity doesn't have `void` type, however we have special implementation175	/// for empty tuple return type176	pub type void = ();177178	//#region Special types179	/// Makes function payable180	pub type value = U256;181	/// Makes function caller-sensitive182	pub type caller = address;183	//#endregion184185	/// Ethereum typed call message, similar to solidity186	/// `msg` object.187	pub struct Msg<C> {188		pub call: C,189		/// Address of user, which called this contract.190		pub caller: H160,191		/// Payment amount to contract.192		/// Contract should reject payment, if target call is not payable,193		/// and there is no `receiver()` function defined.194		pub value: U256,195	}196197	impl From<Vec<u8>> for bytes {198		fn from(src: Vec<u8>) -> Self {199			Self(src)200		}201	}202203	#[allow(clippy::from_over_into)]204	impl Into<Vec<u8>> for bytes {205		fn into(self) -> Vec<u8> {206			self.0207		}208	}209210	impl bytes {211		#[must_use]212		pub fn len(&self) -> usize {213			self.0.len()214		}215216		#[must_use]217		pub fn is_empty(&self) -> bool {218			self.len() == 0219		}220	}221222	#[derive(Debug)]223	pub struct EthCrossAccount {224		pub(crate) eth: address,225		pub(crate) sub: uint256,226	}227228	impl EthCrossAccount {229		pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self230		where231			T: pallet_evm::account::Config,232			T::AccountId: AsRef<[u8; 32]>,233		{234			if cross_account_id.is_canonical_substrate() {235				Self {236					eth: Default::default(),237					sub: convert_cross_account_to_uint256::<T>(cross_account_id),238				}239			} else {240				Self {241					eth: *cross_account_id.as_eth(),242					sub: Default::default(),243				}244			}245		}246247		pub fn into_sub_cross_account<T>(&self) -> crate::execution::Result<T::CrossAccountId>248		where249			T: pallet_evm::account::Config,250			T::AccountId: From<[u8; 32]>,251		{252			if self.eth == Default::default() && self.sub == Default::default() {253				Err("All fields of cross account is zeroed".into())254			} else if self.eth == Default::default() {255				Ok(convert_uint256_to_cross_account::<T>(self.sub))256			} else if self.sub == Default::default() {257				Ok(T::CrossAccountId::from_eth(self.eth))258			} else {259				Err("All fields of cross account is non zeroed".into())260			}261		}262	}263264	impl Signature for EthCrossAccount {265		make_signature!(new fixed("(address,uint256)"));266	}267268	/// Convert `CrossAccountId` to `uint256`.269	pub fn convert_cross_account_to_uint256<T: pallet_evm::account::Config>(270		from: &T::CrossAccountId,271	) -> uint256272	where273		T::AccountId: AsRef<[u8; 32]>,274	{275		let slice = from.as_sub().as_ref();276		uint256::from_big_endian(slice)277	}278279	/// Convert `uint256` to `CrossAccountId`.280	pub fn convert_uint256_to_cross_account<T: pallet_evm::account::Config>(281		from: uint256,282	) -> T::CrossAccountId283	where284		T::AccountId: From<[u8; 32]>,285	{286		let mut new_admin_arr = [0_u8; 32];287		from.to_big_endian(&mut new_admin_arr);288		let account_id = T::AccountId::from(new_admin_arr);289		T::CrossAccountId::from_sub(account_id)290	}291}292293/// Parseable EVM call, this trait should be implemented with [`solidity_interface`] macro294pub trait Call: Sized {295	/// Parse call buffer into typed call enum296	fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>>;297}298299/// Intended to be used as `#[weight]` output type300/// Should be same between evm-coder and substrate to avoid confusion301///302/// Isn't same thing as gas, some mapping is required between those types303pub type Weight = frame_support::weights::Weight;304305/// In substrate, we have benchmarking, which allows306/// us to not rely on gas metering, but instead predict amount of gas to execute call307pub trait Weighted: Call {308	/// Predict weight of this call309	fn weight(&self) -> DispatchInfo;310}311312/// Type callable with ethereum message, may be implemented by [`solidity_interface`] macro313/// on interface implementation, or for externally-owned real EVM contract314pub trait Callable<C: Call> {315	/// Call contract using specified call data316	fn call(&mut self, call: types::Msg<C>) -> execution::ResultWithPostInfo<AbiWriter>;317}318319/// Implementation of ERC165 is implicitly generated for all interfaces in [`solidity_interface`],320/// this structure holds parsed data for ERC165Call subvariant321///322/// Note: no [`Callable`] implementation is provided, call implementation is inlined into every323/// implementing contract324///325/// See <https://eips.ethereum.org/EIPS/eip-165>326#[derive(Debug)]327pub enum ERC165Call {328	/// ERC165 provides single method, which returns true, if contract329	/// implements specified interface330	SupportsInterface {331		/// Requested interface332		interface_id: types::bytes4,333	},334}335336impl ERC165Call {337	/// ERC165 selector is provided by standard338	pub const INTERFACE_ID: types::bytes4 = u32::to_be_bytes(0x01ffc9a7);339}340341impl Call for ERC165Call {342	fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>> {343		if selector != Self::INTERFACE_ID {344			return Ok(None);345		}346		Ok(Some(Self::SupportsInterface {347			interface_id: input.abi_read()?,348		}))349	}350}351352/// Generate "tests", which will generate solidity code on execution and print it to stdout353/// Script at .maintain/scripts/generate_api.sh can split this output from test runtime354///355/// This macro receives type usage as second argument, but you can use anything as generics,356/// because no bounds are implied357#[macro_export]358macro_rules! generate_stubgen {359	($name:ident, $decl:ty, $is_impl:literal) => {360		#[test]361		#[ignore]362		fn $name() {363			use evm_coder::solidity::TypeCollector;364			let mut out = TypeCollector::new();365			<$decl>::generate_solidity_interface(&mut out, $is_impl);366			println!("=== SNIP START ===");367			println!("// SPDX-License-Identifier: OTHER");368			println!("// This code is automatically generated");369			println!();370			println!("pragma solidity >=0.8.0 <0.9.0;");371			println!();372			for b in out.finish() {373				println!("{}", b);374			}375			println!("=== SNIP END ===");376		}377	};378}379380#[cfg(test)]381mod tests {382	use super::*;383384	#[test]385	fn function_selector_generation() {386		assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);387	}388389	// #[test]390	// fn function_selector_generation_1() {391	// 	assert_eq!(392	// 		fn_selector!(transferFromCrossAccountToCrossAccount(393	// 			EthCrossAccount,394	// 			EthCrossAccount,395	// 			uint256396	// 		)),397	// 		2543295963398	// 	);399	// }400401	#[test]402	fn event_topic_generation() {403		assert_eq!(404			hex::encode(&event_topic!(Transfer(address, address, uint256))[..]),405			"ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",406		);407	}408}