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#![cfg_attr(not(feature = "std"), no_std)]20#[cfg(not(feature = "std"))]21extern crate alloc;2223use abi::{AbiRead, AbiReader, AbiWriter};24pub use evm_coder_procedural::{event_topic, fn_selector};25pub mod abi;26pub use events::{ToLog, ToTopic};27use execution::DispatchInfo;28pub mod execution;2930/// Derives call enum implementing [`crate::Callable`], [`crate::Weighted`]31/// and [`crate::Call`] from impl block.32///33/// ## Macro syntax34///35/// `#[solidity_interface(name, is, inline_is, events)]`36/// - *name* - used in generated code, and for Call enum name37/// - *is* - used to provide inheritance in Solidity38/// - *inline_is* - same as `is`, but ERC165::SupportsInterface will work differently: For `is` SupportsInterface(A) will return true39/// 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)`40/// SupportsInterface(A) will internally create a new interface that combines all methods of A and B, so SupportsInterface(A) will return41/// false.42///43/// `#[weight(value)]`44/// Can be added to every method of impl block, used for deriving [`crate::Weighted`], which45/// is used by substrate bridge.46/// - *value*: expression, which evaluates to weight required to call this method.47/// This expression can use call arguments to calculate non-constant execution time.48/// This expression should evaluate faster than actual execution does, and may provide worse case49/// than one is called.50///51/// `#[solidity_interface(rename_selector)]`52/// - *rename_selector* - by default, selector name will be generated by transforming method name53/// from snake_case to camelCase. Use this option, if other naming convention is required.54/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name55/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`56/// explicitly.57///58/// Both contract and contract methods may have doccomments, which will end up in a generated59/// solidity interface file, thus you should use [solidity syntax](https://docs.soliditylang.org/en/latest/natspec-format.html) for writing documentation in this macro60///61/// ## Example62///63/// ```ignore64/// struct SuperContract;65/// struct InlineContract;66/// struct Contract;67///68/// #[derive(ToLog)]69/// enum ContractEvents {70/// Event(#[indexed] uint32),71/// }72///73/// /// @dev This contract provides function to multiply two numbers74/// #[solidity_interface(name = MyContract, is(SuperContract), inline_is(InlineContract))]75/// impl Contract {76/// /// Multiply two numbers77/// /// @param a First number78/// /// @param b Second number79/// /// @return uint32 Product of two passed numbers80/// /// @dev This function returns error in case of overflow81/// #[weight(200 + a + b)]82/// #[solidity_interface(rename_selector = "mul")]83/// fn mul(&mut self, a: uint32, b: uint32) -> Result<uint32> {84/// Ok(a.checked_mul(b).ok_or("overflow")?)85/// }86/// }87/// ```88pub use evm_coder_procedural::solidity_interface;89/// See [`solidity_interface`]90pub use evm_coder_procedural::solidity;91/// See [`solidity_interface`]92pub use evm_coder_procedural::weight;9394/// Derives [`ToLog`] for enum95///96/// Selectors will be derived from variant names, there is currently no way to have custom naming97/// for them98///99/// `#[indexed]`100/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data101pub use evm_coder_procedural::ToLog;102103// Api of those modules shouldn't be consumed directly, it is only exported for usage in proc macros104#[doc(hidden)]105pub mod events;106#[doc(hidden)]107pub mod solidity;108109/// Solidity type definitions (aliases from solidity name to rust type)110/// To be used in [`solidity_interface`] definitions, to make sure there is no111/// type conflict between Rust code and generated definitions112pub mod types {113 #![allow(non_camel_case_types, missing_docs)]114115 #[cfg(not(feature = "std"))]116 use alloc::{vec::Vec};117 use pallet_evm::account::CrossAccountId;118 use primitive_types::{U256, H160, H256};119120 pub type address = H160;121122 pub type uint8 = u8;123 pub type uint16 = u16;124 pub type uint32 = u32;125 pub type uint64 = u64;126 pub type uint128 = u128;127 pub type uint256 = U256;128129 pub type bytes4 = [u8; 4];130131 pub type topic = H256;132133 #[cfg(not(feature = "std"))]134 pub type string = ::alloc::string::String;135 #[cfg(feature = "std")]136 pub type string = ::std::string::String;137138 #[derive(Default, Debug)]139 pub struct bytes(pub Vec<u8>);140141 /// Solidity doesn't have `void` type, however we have special implementation142 /// for empty tuple return type143 pub type void = ();144145 //#region Special types146 /// Makes function payable147 pub type value = U256;148 /// Makes function caller-sensitive149 pub type caller = address;150 //#endregion151152 /// Ethereum typed call message, similar to solidity153 /// `msg` object.154 pub struct Msg<C> {155 pub call: C,156 /// Address of user, which called this contract.157 pub caller: H160,158 /// Payment amount to contract.159 /// Contract should reject payment, if target call is not payable,160 /// and there is no `receiver()` function defined.161 pub value: U256,162 }163164 impl From<Vec<u8>> for bytes {165 fn from(src: Vec<u8>) -> Self {166 Self(src)167 }168 }169170 impl Into<Vec<u8>> for bytes {171 fn into(self) -> Vec<u8> {172 self.0173 }174 }175176 impl bytes {177 #[must_use]178 pub fn len(&self) -> usize {179 self.0.len()180 }181182 #[must_use]183 pub fn is_empty(&self) -> bool {184 self.len() == 0185 }186 }187188 #[derive(Debug)]189 pub struct EthCrossAccount {190 pub(crate) eth: address,191 pub(crate) sub: uint256,192 }193194 impl EthCrossAccount {195 pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self196 where197 T: pallet_evm::account::Config,198 T::AccountId: AsRef<[u8; 32]>,199 {200 if cross_account_id.is_canonical_substrate() {201 Self {202 eth: Default::default(),203 sub: convert_cross_account_to_uint256::<T>(cross_account_id),204 }205 } else {206 Self {207 eth: *cross_account_id.as_eth(),208 sub: Default::default(),209 }210 }211 }212213 pub fn into_sub_cross_account<T>(&self) -> crate::execution::Result<T::CrossAccountId>214 where215 T: pallet_evm::account::Config,216 T::AccountId: From<[u8; 32]>,217 {218 if self.eth == Default::default() && self.sub == Default::default() {219 Err("All fields of cross account is zeroed".into())220 } else if self.eth == Default::default() {221 Ok(convert_uint256_to_cross_account::<T>(self.sub))222 } else if self.sub == Default::default() {223 Ok(T::CrossAccountId::from_eth(self.eth))224 } else {225 Err("All fields of cross account is non zeroed".into())226 }227 }228 }229230 /// Convert `CrossAccountId` to `uint256`.231 pub fn convert_cross_account_to_uint256<T: pallet_evm::account::Config>(232 from: &T::CrossAccountId,233 ) -> uint256234 where235 T::AccountId: AsRef<[u8; 32]>,236 {237 let slice = from.as_sub().as_ref();238 uint256::from_big_endian(slice)239 }240241 /// Convert `uint256` to `CrossAccountId`.242 pub fn convert_uint256_to_cross_account<T: pallet_evm::account::Config>(243 from: uint256,244 ) -> T::CrossAccountId245 where246 T::AccountId: From<[u8; 32]>,247 {248 let mut new_admin_arr = [0_u8; 32];249 from.to_big_endian(&mut new_admin_arr);250 let account_id = T::AccountId::from(new_admin_arr);251 T::CrossAccountId::from_sub(account_id)252 }253}254255/// Parseable EVM call, this trait should be implemented with [`solidity_interface`] macro256pub trait Call: Sized {257 /// Parse call buffer into typed call enum258 fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>>;259}260261/// Intended to be used as `#[weight]` output type262/// Should be same between evm-coder and substrate to avoid confusion263///264/// Isn't same thing as gas, some mapping is required between those types265pub type Weight = frame_support::weights::Weight;266267/// In substrate, we have benchmarking, which allows268/// us to not rely on gas metering, but instead predict amount of gas to execute call269pub trait Weighted: Call {270 /// Predict weight of this call271 fn weight(&self) -> DispatchInfo;272}273274/// Type callable with ethereum message, may be implemented by [`solidity_interface`] macro275/// on interface implementation, or for externally-owned real EVM contract276pub trait Callable<C: Call> {277 /// Call contract using specified call data278 fn call(&mut self, call: types::Msg<C>) -> execution::ResultWithPostInfo<AbiWriter>;279}280281/// Implementation of ERC165 is implicitly generated for all interfaces in [`solidity_interface`],282/// this structure holds parsed data for ERC165Call subvariant283///284/// Note: no [`Callable`] implementation is provided, call implementation is inlined into every285/// implementing contract286///287/// See <https://eips.ethereum.org/EIPS/eip-165>288#[derive(Debug)]289pub enum ERC165Call {290 /// ERC165 provides single method, which returns true, if contract291 /// implements specified interface292 SupportsInterface {293 /// Requested interface294 interface_id: types::bytes4,295 },296}297298impl ERC165Call {299 /// ERC165 selector is provided by standard300 pub const INTERFACE_ID: types::bytes4 = u32::to_be_bytes(0x01ffc9a7);301}302303impl Call for ERC165Call {304 fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>> {305 if selector != Self::INTERFACE_ID {306 return Ok(None);307 }308 Ok(Some(Self::SupportsInterface {309 interface_id: input.abi_read()?,310 }))311 }312}313314/// Generate "tests", which will generate solidity code on execution and print it to stdout315/// Script at .maintain/scripts/generate_api.sh can split this output from test runtime316///317/// This macro receives type usage as second argument, but you can use anything as generics,318/// because no bounds are implied319#[macro_export]320macro_rules! generate_stubgen {321 ($name:ident, $decl:ty, $is_impl:literal) => {322 #[test]323 #[ignore]324 fn $name() {325 use evm_coder::solidity::TypeCollector;326 let mut out = TypeCollector::new();327 <$decl>::generate_solidity_interface(&mut out, $is_impl);328 println!("=== SNIP START ===");329 println!("// SPDX-License-Identifier: OTHER");330 println!("// This code is automatically generated");331 println!();332 println!("pragma solidity >=0.8.0 <0.9.0;");333 println!();334 for b in out.finish() {335 println!("{}", b);336 }337 println!("=== SNIP END ===");338 }339 };340}341342#[cfg(test)]343mod tests {344 use super::*;345346 #[test]347 fn function_selector_generation() {348 assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);349 }350351 #[test]352 fn event_topic_generation() {353 assert_eq!(354 hex::encode(&event_topic!(Transfer(address, address, uint256))[..]),355 "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",356 );357 }358}difftreelog
source
crates/evm-coder/src/lib.rs11.2 KiBsourcehistory