difftreelog
misk: Documentation, test fixes, refactor
in: master
12 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1096,26 +1096,6 @@
checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"
[[package]]
-name = "const_format"
-version = "0.2.30"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7309d9b4d3d2c0641e018d449232f2e28f1b22933c137f157d3dbc14228b8c0e"
-dependencies = [
- "const_format_proc_macros",
-]
-
-[[package]]
-name = "const_format_proc_macros"
-version = "0.2.29"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d897f47bf7270cf70d370f8f98c1abb6d2d4cf60a6845d30e05bfb90c6568650"
-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"
@@ -2373,7 +2353,6 @@
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)",
crates/evm-coder/Cargo.tomldiffbeforeafterboth--- a/crates/evm-coder/Cargo.toml
+++ b/crates/evm-coder/Cargo.toml
@@ -5,7 +5,6 @@
edition = "2021"
[dependencies]
-const_format = { version = "0.2.26", default-features = false }
sha3-const = { version = "0.1.1", default-features = false }
# Ethereum uses keccak (=sha3) for selectors
# sha3 = "0.10.1"
crates/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,7 +20,7 @@
// about Procedural Macros in Rust book:
// https://doc.rust-lang.org/reference/procedural-macros.html
-use proc_macro2::{TokenStream, token_stream};
+use proc_macro2::TokenStream;
use quote::{quote, ToTokens, format_ident};
use inflector::cases;
use std::fmt::Write;
crates/evm-coder/src/custom_signature.rsdiffbeforeafterboth--- a/crates/evm-coder/src/custom_signature.rs
+++ b/crates/evm-coder/src/custom_signature.rs
@@ -1,23 +1,140 @@
+//! # A module for custom signature support.
+//!
+//! ## Overview
+//! This module allows you to create arbitrary signatures for types and functions in compile time.
+//!
+//! ### Type signatures
+//! To create the desired type signature, you need to create your own trait with the `SIGNATURE` constant.
+//! Then in the implementation, for the required type, use the macro [`make_signature`]
+//! #### Example
+//! ```
+//! use std::str::from_utf8;
+//! use evm_coder::make_signature;
+//! use evm_coder::custom_signature::{
+//! SignatureUnit,
+//! SIGNATURE_SIZE_LIMIT
+//! };
+//!
+//! // Create trait for our signature
+//! trait SoliditySignature {
+//! const SIGNATURE: SignatureUnit;
+//!
+//! fn name() -> &'static str {
+//! from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+//! }
+//! }
+//!
+//! // Make signatures for some types
+//! impl SoliditySignature for u8 {
+//! make_signature!(new fixed("uint8"));
+//! }
+//! impl SoliditySignature for u32 {
+//! make_signature!(new fixed("uint32"));
+//! }
+//! impl<T: SoliditySignature> SoliditySignature for Vec<T> {
+//! make_signature!(new nameof(T) fixed("[]"));
+//! }
+//! impl<A: SoliditySignature, B: SoliditySignature> SoliditySignature for (A, B) {
+//! make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
+//! }
+//! impl<A: SoliditySignature> SoliditySignature for (A,) {
+//! make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));
+//! }
+//!
+//! assert_eq!(u8::name(), "uint8");
+//! assert_eq!(<Vec<u8>>::name(), "uint8[]");
+//! assert_eq!(<(u32, u8)>::name(), "(uint32,uint8)");
+//! ```
+//!
+//! ### Function signatures
+//! To create a function signature, the macro [`make_signature`] is also used, which accepts
+//! settings for the function format [`SignaturePreferences`] and function parameters [`SignatureUnit`]
+//! #### Example
+//! ```
+//! use core::str::from_utf8;
+//! use evm_coder::{
+//! make_signature,
+//! custom_signature::{
+//! SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+//! },
+//! };
+//! // Trait for our signature
+//! trait SoliditySignature {
+//! const SIGNATURE: SignatureUnit;
+//!
+//! fn name() -> &'static str {
+//! from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+//! }
+//! }
+//!
+//! // Make signatures for some types
+//! impl SoliditySignature for u8 {
+//! make_signature!(new fixed("uint8"));
+//! }
+//! impl<T: SoliditySignature> SoliditySignature for Vec<T> {
+//! make_signature!(new nameof(T) fixed("[]"));
+//! }
+//!
+//! // Function signature settings
+//! const SIGNATURE_PREFERENCES: SignaturePreferences = SignaturePreferences {
+//! open_name: Some(SignatureUnit::new("some_funk")),
+//! open_delimiter: Some(SignatureUnit::new("(")),
+//! param_delimiter: Some(SignatureUnit::new(",")),
+//! close_delimiter: Some(SignatureUnit::new(")")),
+//! close_name: None,
+//! };
+//!
+//! // Create functions signatures
+//! fn make_func_without_args() {
+//! const SIG: FunctionSignature = make_signature!(
+//! new fn(SIGNATURE_PREFERENCES),
+//! );
+//! let name = SIG.as_str();
+//! similar_asserts::assert_eq!(name, "some_funk()");
+//! }
+//!
+//! fn make_func_with_3_args() {
+//! const SIG: FunctionSignature = make_signature!(
+//! new fn(SIGNATURE_PREFERENCES),
+//! (<u8>::SIGNATURE),
+//! (<u8>::SIGNATURE),
+//! (<Vec<u8>>::SIGNATURE),
+//! );
+//! let name = SIG.as_str();
+//! similar_asserts::assert_eq!(name, "some_funk(uint8,uint8,uint8[])");
+//! }
+//! ```
use core::str::from_utf8;
+/// The maximum length of the signature.
pub const SIGNATURE_SIZE_LIMIT: usize = 256;
+/// Function signature formatting preferences.
#[derive(Debug)]
pub struct SignaturePreferences {
+ /// The name of the function before the list of parameters: `*some*(param1,param2)func`
pub open_name: Option<SignatureUnit>,
+ /// Opening separator: `some*(*param1,param2)func`
pub open_delimiter: Option<SignatureUnit>,
+ /// Parameters separator: `some(param1*,*param2)func`
pub param_delimiter: Option<SignatureUnit>,
+ /// Closinging separator: `some(param1,param2*)*func`
pub close_delimiter: Option<SignatureUnit>,
+ /// The name of the function after the list of parameters: `some(param1,param2)*func*`
pub close_name: Option<SignatureUnit>,
}
+/// Constructs and stores the signature of the function.
#[derive(Debug)]
pub struct FunctionSignature {
+ /// Storage for function signature.
pub unit: SignatureUnit,
preferences: SignaturePreferences,
}
impl FunctionSignature {
+ /// Start constructing the signature. It is written to the storage
+ /// [`SignaturePreferences::open_name`] and [`SignaturePreferences::open_delimiter`].
pub const fn new(preferences: SignaturePreferences) -> FunctionSignature {
let mut dst = [0_u8; SIGNATURE_SIZE_LIMIT];
let mut dst_offset = 0;
@@ -36,6 +153,8 @@
}
}
+ /// Add a function parameter to the signature. It is written to the storage
+ /// `param` [`SignatureUnit`] and [`SignaturePreferences::param_delimiter`].
pub const fn add_param(
signature: FunctionSignature,
param: SignatureUnit,
@@ -55,6 +174,8 @@
}
}
+ /// Complete signature construction. It is written to the storage
+ /// [`SignaturePreferences::close_delimiter`] and [`SignaturePreferences::close_name`].
pub const fn done(signature: FunctionSignature, owerride: bool) -> FunctionSignature {
let mut dst = signature.unit.data;
let mut dst_offset = signature.unit.len - if owerride { 1 } else { 0 };
@@ -73,18 +194,23 @@
}
}
+ /// Represent the signature as `&str'.
pub fn as_str(&self) -> &str {
from_utf8(&self.unit.data[..self.unit.len]).expect("bad utf-8")
}
}
+/// Storage for the signature or its elements.
#[derive(Debug)]
pub struct SignatureUnit {
+ /// Signature data.
pub data: [u8; SIGNATURE_SIZE_LIMIT],
+ /// The actual size of the data.
pub len: usize,
}
impl SignatureUnit {
+ /// Create a signature from `&str'.
pub const fn new(name: &'static str) -> SignatureUnit {
let mut signature = [0_u8; SIGNATURE_SIZE_LIMIT];
let name = name.as_bytes();
@@ -98,9 +224,23 @@
}
}
+/// ### Macro to create signatures of types and functions.
+///
+/// Format for creating a type of signature:
+/// ```ignore
+/// make_signature!(new fixed("uint8")); // Simple type
+/// make_signature!(new fixed("(") nameof(u8) fixed(",") nameof(u8) fixed(")")); // Composite type
+/// ```
+/// Format for creating a function of the function:
+/// ```ignore
+/// const SIG: FunctionSignature = make_signature!(
+/// new fn(SIGNATURE_PREFERENCES),
+/// (u8::SIGNATURE),
+/// (<(u8,u8)>::SIGNATURE),
+/// );
+/// ```
#[macro_export]
-#[allow(missing_docs)]
-macro_rules! make_signature { // May be "define_signature"?
+macro_rules! make_signature {
(new fn($func:expr)$(,)+) => {
{
let fs = FunctionSignature::new($func);
@@ -283,10 +423,13 @@
assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));
}
- // This test must NOT compile!
+ // This test must NOT compile with "index out of bounds"!
// #[test]
// fn over_max_size() {
- // assert_eq!(<Vec<MaxSize>>::name(), "!".repeat(SIZE_LIMIT) + "[]");
+ // assert_eq!(
+ // <Vec<MaxSize>>::name(),
+ // "!".repeat(SIGNATURE_SIZE_LIMIT) + "[]"
+ // );
// }
#[test]
crates/evm-coder/src/lib.rsdiffbeforeafterboth1// 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::{SignatureUnit, SIGNATURE_SIZE_LIMIT};128129 pub trait Signature {130 const SIGNATURE: SignatureUnit;131132 fn as_str() -> &'static str {133 from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")134 }135 }136137 impl Signature for bool {138 make_signature!(new fixed("bool"));139 }140141 macro_rules! define_simple_type {142 (type $ident:ident = $ty:ty) => {143 pub type $ident = $ty;144 impl Signature for $ty {145 make_signature!(new fixed(stringify!($ident)));146 }147 };148 }149150 define_simple_type!(type address = H160);151152 define_simple_type!(type uint8 = u8);153 define_simple_type!(type uint16 = u16);154 define_simple_type!(type uint32 = u32);155 define_simple_type!(type uint64 = u64);156 define_simple_type!(type uint128 = u128);157 define_simple_type!(type uint256 = U256);158 define_simple_type!(type bytes4 = [u8; 4]);159160 define_simple_type!(type topic = H256);161162 #[cfg(not(feature = "std"))]163 define_simple_type!(type string = ::alloc::string::String);164 #[cfg(feature = "std")]165 define_simple_type!(type string = ::std::string::String);166167 #[derive(Default, Debug)]168 pub struct bytes(pub Vec<u8>);169 impl Signature for bytes {170 make_signature!(new fixed("bytes"));171 }172173 /// Solidity doesn't have `void` type, however we have special implementation174 /// for empty tuple return type175 pub type void = ();176177 //#region Special types178 /// Makes function payable179 pub type value = U256;180 /// Makes function caller-sensitive181 pub type caller = address;182 //#endregion183184 /// Ethereum typed call message, similar to solidity185 /// `msg` object.186 pub struct Msg<C> {187 pub call: C,188 /// Address of user, which called this contract.189 pub caller: H160,190 /// Payment amount to contract.191 /// Contract should reject payment, if target call is not payable,192 /// and there is no `receiver()` function defined.193 pub value: U256,194 }195196 impl From<Vec<u8>> for bytes {197 fn from(src: Vec<u8>) -> Self {198 Self(src)199 }200 }201202 #[allow(clippy::from_over_into)]203 impl Into<Vec<u8>> for bytes {204 fn into(self) -> Vec<u8> {205 self.0206 }207 }208209 impl bytes {210 #[must_use]211 pub fn len(&self) -> usize {212 self.0.len()213 }214215 #[must_use]216 pub fn is_empty(&self) -> bool {217 self.len() == 0218 }219 }220221 #[derive(Debug, Default)]222 pub struct EthCrossAccount {223 pub(crate) eth: address,224 pub(crate) sub: uint256,225 }226227 impl EthCrossAccount {228 pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self229 where230 T: pallet_evm::account::Config,231 T::AccountId: AsRef<[u8; 32]>,232 {233 if cross_account_id.is_canonical_substrate() {234 Self {235 eth: Default::default(),236 sub: convert_cross_account_to_uint256::<T>(cross_account_id),237 }238 } else {239 Self {240 eth: *cross_account_id.as_eth(),241 sub: Default::default(),242 }243 }244 }245246 pub fn into_sub_cross_account<T>(&self) -> crate::execution::Result<T::CrossAccountId>247 where248 T: pallet_evm::account::Config,249 T::AccountId: From<[u8; 32]>,250 {251 if self.eth == Default::default() && self.sub == Default::default() {252 Err("All fields of cross account is zeroed".into())253 } else if self.eth == Default::default() {254 Ok(convert_uint256_to_cross_account::<T>(self.sub))255 } else if self.sub == Default::default() {256 Ok(T::CrossAccountId::from_eth(self.eth))257 } else {258 Err("All fields of cross account is non zeroed".into())259 }260 }261 }262263 impl Signature for EthCrossAccount {264 make_signature!(new fixed("(address,uint256)"));265 }266267 /// Convert `CrossAccountId` to `uint256`.268 pub fn convert_cross_account_to_uint256<T: pallet_evm::account::Config>(269 from: &T::CrossAccountId,270 ) -> uint256271 where272 T::AccountId: AsRef<[u8; 32]>,273 {274 let slice = from.as_sub().as_ref();275 uint256::from_big_endian(slice)276 }277278 /// Convert `uint256` to `CrossAccountId`.279 pub fn convert_uint256_to_cross_account<T: pallet_evm::account::Config>(280 from: uint256,281 ) -> T::CrossAccountId282 where283 T::AccountId: From<[u8; 32]>,284 {285 let mut new_admin_arr = [0_u8; 32];286 from.to_big_endian(&mut new_admin_arr);287 let account_id = T::AccountId::from(new_admin_arr);288 T::CrossAccountId::from_sub(account_id)289 }290}291292/// Parseable EVM call, this trait should be implemented with [`solidity_interface`] macro293pub trait Call: Sized {294 /// Parse call buffer into typed call enum295 fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>>;296}297298/// Intended to be used as `#[weight]` output type299/// Should be same between evm-coder and substrate to avoid confusion300///301/// Isn't same thing as gas, some mapping is required between those types302pub type Weight = frame_support::weights::Weight;303304/// In substrate, we have benchmarking, which allows305/// us to not rely on gas metering, but instead predict amount of gas to execute call306pub trait Weighted: Call {307 /// Predict weight of this call308 fn weight(&self) -> DispatchInfo;309}310311/// Type callable with ethereum message, may be implemented by [`solidity_interface`] macro312/// on interface implementation, or for externally-owned real EVM contract313pub trait Callable<C: Call> {314 /// Call contract using specified call data315 fn call(&mut self, call: types::Msg<C>) -> execution::ResultWithPostInfo<AbiWriter>;316}317318/// Implementation of ERC165 is implicitly generated for all interfaces in [`solidity_interface`],319/// this structure holds parsed data for ERC165Call subvariant320///321/// Note: no [`Callable`] implementation is provided, call implementation is inlined into every322/// implementing contract323///324/// See <https://eips.ethereum.org/EIPS/eip-165>325#[derive(Debug)]326pub enum ERC165Call {327 /// ERC165 provides single method, which returns true, if contract328 /// implements specified interface329 SupportsInterface {330 /// Requested interface331 interface_id: types::bytes4,332 },333}334335impl ERC165Call {336 /// ERC165 selector is provided by standard337 pub const INTERFACE_ID: types::bytes4 = u32::to_be_bytes(0x01ffc9a7);338}339340impl Call for ERC165Call {341 fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>> {342 if selector != Self::INTERFACE_ID {343 return Ok(None);344 }345 Ok(Some(Self::SupportsInterface {346 interface_id: input.abi_read()?,347 }))348 }349}350351/// Generate "tests", which will generate solidity code on execution and print it to stdout352/// Script at .maintain/scripts/generate_api.sh can split this output from test runtime353///354/// This macro receives type usage as second argument, but you can use anything as generics,355/// because no bounds are implied356#[macro_export]357macro_rules! generate_stubgen {358 ($name:ident, $decl:ty, $is_impl:literal) => {359 #[test]360 #[ignore]361 fn $name() {362 use evm_coder::solidity::TypeCollector;363 let mut out = TypeCollector::new();364 <$decl>::generate_solidity_interface(&mut out, $is_impl);365 println!("=== SNIP START ===");366 println!("// SPDX-License-Identifier: OTHER");367 println!("// This code is automatically generated");368 println!();369 println!("pragma solidity >=0.8.0 <0.9.0;");370 println!();371 for b in out.finish() {372 println!("{}", b);373 }374 println!("=== SNIP END ===");375 }376 };377}378379#[cfg(test)]380mod tests {381 use super::*;382383 #[test]384 fn function_selector_generation() {385 assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);386 }387388 // #[test]389 // fn function_selector_generation_1() {390 // assert_eq!(391 // fn_selector!(transferFromCrossAccountToCrossAccount(392 // EthCrossAccount,393 // EthCrossAccount,394 // uint256395 // )),396 // 2543295963397 // );398 // }399400 #[test]401 fn event_topic_generation() {402 assert_eq!(403 hex::encode(&event_topic!(Transfer(address, address, uint256))[..]),404 "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",405 );406 }407}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#![macro_use]20#![cfg_attr(not(feature = "std"), no_std)]21#[cfg(not(feature = "std"))]22extern crate alloc;2324use abi::{AbiRead, AbiReader, AbiWriter};25pub use evm_coder_procedural::{event_topic, fn_selector};26pub mod abi;27pub use events::{ToLog, ToTopic};28use execution::DispatchInfo;29pub mod execution;30#[macro_use]31pub mod custom_signature;3233/// Derives call enum implementing [`crate::Callable`], [`crate::Weighted`]34/// and [`crate::Call`] from impl block.35///36/// ## Macro syntax37///38/// `#[solidity_interface(name, is, inline_is, events)]`39/// - *name* - used in generated code, and for Call enum name40/// - *is* - used to provide inheritance in Solidity41/// - *inline_is* - same as `is`, but ERC165::SupportsInterface will work differently: For `is` SupportsInterface(A) will return true42/// 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)`43/// SupportsInterface(A) will internally create a new interface that combines all methods of A and B, so SupportsInterface(A) will return44/// false.45///46/// `#[weight(value)]`47/// Can be added to every method of impl block, used for deriving [`crate::Weighted`], which48/// is used by substrate bridge.49/// - *value*: expression, which evaluates to weight required to call this method.50/// This expression can use call arguments to calculate non-constant execution time.51/// This expression should evaluate faster than actual execution does, and may provide worse case52/// than one is called.53///54/// `#[solidity_interface(rename_selector)]`55/// - *rename_selector* - by default, selector name will be generated by transforming method name56/// from snake_case to camelCase. Use this option, if other naming convention is required.57/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name58/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`59/// explicitly.60///61/// Both contract and contract methods may have doccomments, which will end up in a generated62/// solidity interface file, thus you should use [solidity syntax](https://docs.soliditylang.org/en/latest/natspec-format.html) for writing documentation in this macro63///64/// ## Example65///66/// ```ignore67/// struct SuperContract;68/// struct InlineContract;69/// struct Contract;70///71/// #[derive(ToLog)]72/// enum ContractEvents {73/// Event(#[indexed] uint32),74/// }75///76/// /// @dev This contract provides function to multiply two numbers77/// #[solidity_interface(name = MyContract, is(SuperContract), inline_is(InlineContract))]78/// impl Contract {79/// /// Multiply two numbers80/// /// @param a First number81/// /// @param b Second number82/// /// @return uint32 Product of two passed numbers83/// /// @dev This function returns error in case of overflow84/// #[weight(200 + a + b)]85/// #[solidity_interface(rename_selector = "mul")]86/// fn mul(&mut self, a: uint32, b: uint32) -> Result<uint32> {87/// Ok(a.checked_mul(b).ok_or("overflow")?)88/// }89/// }90/// ```91pub use evm_coder_procedural::solidity_interface;92/// See [`solidity_interface`]93pub use evm_coder_procedural::solidity;94/// See [`solidity_interface`]95pub use evm_coder_procedural::weight;96pub use sha3_const;9798/// Derives [`ToLog`] for enum99///100/// Selectors will be derived from variant names, there is currently no way to have custom naming101/// for them102///103/// `#[indexed]`104/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data105pub use evm_coder_procedural::ToLog;106107// Api of those modules shouldn't be consumed directly, it is only exported for usage in proc macros108#[doc(hidden)]109pub mod events;110#[doc(hidden)]111pub mod solidity;112113/// Solidity type definitions (aliases from solidity name to rust type)114/// To be used in [`solidity_interface`] definitions, to make sure there is no115/// type conflict between Rust code and generated definitions116pub mod types {117 #![allow(non_camel_case_types, missing_docs)]118119 #[cfg(not(feature = "std"))]120 use alloc::{vec::Vec};121 use pallet_evm::account::CrossAccountId;122 use primitive_types::{U256, H160, H256};123 use core::str::from_utf8;124125 use crate::custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT};126127 pub trait Signature {128 const SIGNATURE: SignatureUnit;129130 fn as_str() -> &'static str {131 from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")132 }133 }134135 impl Signature for bool {136 make_signature!(new fixed("bool"));137 }138139 macro_rules! define_simple_type {140 (type $ident:ident = $ty:ty) => {141 pub type $ident = $ty;142 impl Signature for $ty {143 make_signature!(new fixed(stringify!($ident)));144 }145 };146 }147148 define_simple_type!(type address = H160);149150 define_simple_type!(type uint8 = u8);151 define_simple_type!(type uint16 = u16);152 define_simple_type!(type uint32 = u32);153 define_simple_type!(type uint64 = u64);154 define_simple_type!(type uint128 = u128);155 define_simple_type!(type uint256 = U256);156 define_simple_type!(type bytes4 = [u8; 4]);157158 define_simple_type!(type topic = H256);159160 #[cfg(not(feature = "std"))]161 define_simple_type!(type string = ::alloc::string::String);162 #[cfg(feature = "std")]163 define_simple_type!(type string = ::std::string::String);164165 #[derive(Default, Debug)]166 pub struct bytes(pub Vec<u8>);167 impl Signature for bytes {168 make_signature!(new fixed("bytes"));169 }170171 /// Solidity doesn't have `void` type, however we have special implementation172 /// for empty tuple return type173 pub type void = ();174175 //#region Special types176 /// Makes function payable177 pub type value = U256;178 /// Makes function caller-sensitive179 pub type caller = address;180 //#endregion181182 /// Ethereum typed call message, similar to solidity183 /// `msg` object.184 pub struct Msg<C> {185 pub call: C,186 /// Address of user, which called this contract.187 pub caller: H160,188 /// Payment amount to contract.189 /// Contract should reject payment, if target call is not payable,190 /// and there is no `receiver()` function defined.191 pub value: U256,192 }193194 impl From<Vec<u8>> for bytes {195 fn from(src: Vec<u8>) -> Self {196 Self(src)197 }198 }199200 #[allow(clippy::from_over_into)]201 impl Into<Vec<u8>> for bytes {202 fn into(self) -> Vec<u8> {203 self.0204 }205 }206207 impl bytes {208 #[must_use]209 pub fn len(&self) -> usize {210 self.0.len()211 }212213 #[must_use]214 pub fn is_empty(&self) -> bool {215 self.len() == 0216 }217 }218219 #[derive(Debug, Default)]220 pub struct EthCrossAccount {221 pub(crate) eth: address,222 pub(crate) sub: uint256,223 }224225 impl EthCrossAccount {226 pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self227 where228 T: pallet_evm::account::Config,229 T::AccountId: AsRef<[u8; 32]>,230 {231 if cross_account_id.is_canonical_substrate() {232 Self {233 eth: Default::default(),234 sub: convert_cross_account_to_uint256::<T>(cross_account_id),235 }236 } else {237 Self {238 eth: *cross_account_id.as_eth(),239 sub: Default::default(),240 }241 }242 }243244 pub fn into_sub_cross_account<T>(&self) -> crate::execution::Result<T::CrossAccountId>245 where246 T: pallet_evm::account::Config,247 T::AccountId: From<[u8; 32]>,248 {249 if self.eth == Default::default() && self.sub == Default::default() {250 Err("All fields of cross account is zeroed".into())251 } else if self.eth == Default::default() {252 Ok(convert_uint256_to_cross_account::<T>(self.sub))253 } else if self.sub == Default::default() {254 Ok(T::CrossAccountId::from_eth(self.eth))255 } else {256 Err("All fields of cross account is non zeroed".into())257 }258 }259 }260261 impl Signature for EthCrossAccount {262 make_signature!(new fixed("(address,uint256)"));263 }264265 /// Convert `CrossAccountId` to `uint256`.266 pub fn convert_cross_account_to_uint256<T: pallet_evm::account::Config>(267 from: &T::CrossAccountId,268 ) -> uint256269 where270 T::AccountId: AsRef<[u8; 32]>,271 {272 let slice = from.as_sub().as_ref();273 uint256::from_big_endian(slice)274 }275276 /// Convert `uint256` to `CrossAccountId`.277 pub fn convert_uint256_to_cross_account<T: pallet_evm::account::Config>(278 from: uint256,279 ) -> T::CrossAccountId280 where281 T::AccountId: From<[u8; 32]>,282 {283 let mut new_admin_arr = [0_u8; 32];284 from.to_big_endian(&mut new_admin_arr);285 let account_id = T::AccountId::from(new_admin_arr);286 T::CrossAccountId::from_sub(account_id)287 }288}289290/// Parseable EVM call, this trait should be implemented with [`solidity_interface`] macro291pub trait Call: Sized {292 /// Parse call buffer into typed call enum293 fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>>;294}295296/// Intended to be used as `#[weight]` output type297/// Should be same between evm-coder and substrate to avoid confusion298///299/// Isn't same thing as gas, some mapping is required between those types300pub type Weight = frame_support::weights::Weight;301302/// In substrate, we have benchmarking, which allows303/// us to not rely on gas metering, but instead predict amount of gas to execute call304pub trait Weighted: Call {305 /// Predict weight of this call306 fn weight(&self) -> DispatchInfo;307}308309/// Type callable with ethereum message, may be implemented by [`solidity_interface`] macro310/// on interface implementation, or for externally-owned real EVM contract311pub trait Callable<C: Call> {312 /// Call contract using specified call data313 fn call(&mut self, call: types::Msg<C>) -> execution::ResultWithPostInfo<AbiWriter>;314}315316/// Implementation of ERC165 is implicitly generated for all interfaces in [`solidity_interface`],317/// this structure holds parsed data for ERC165Call subvariant318///319/// Note: no [`Callable`] implementation is provided, call implementation is inlined into every320/// implementing contract321///322/// See <https://eips.ethereum.org/EIPS/eip-165>323#[derive(Debug)]324pub enum ERC165Call {325 /// ERC165 provides single method, which returns true, if contract326 /// implements specified interface327 SupportsInterface {328 /// Requested interface329 interface_id: types::bytes4,330 },331}332333impl ERC165Call {334 /// ERC165 selector is provided by standard335 pub const INTERFACE_ID: types::bytes4 = u32::to_be_bytes(0x01ffc9a7);336}337338impl Call for ERC165Call {339 fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>> {340 if selector != Self::INTERFACE_ID {341 return Ok(None);342 }343 Ok(Some(Self::SupportsInterface {344 interface_id: input.abi_read()?,345 }))346 }347}348349/// Generate "tests", which will generate solidity code on execution and print it to stdout350/// Script at .maintain/scripts/generate_api.sh can split this output from test runtime351///352/// This macro receives type usage as second argument, but you can use anything as generics,353/// because no bounds are implied354#[macro_export]355macro_rules! generate_stubgen {356 ($name:ident, $decl:ty, $is_impl:literal) => {357 #[test]358 #[ignore]359 fn $name() {360 use evm_coder::solidity::TypeCollector;361 let mut out = TypeCollector::new();362 <$decl>::generate_solidity_interface(&mut out, $is_impl);363 println!("=== SNIP START ===");364 println!("// SPDX-License-Identifier: OTHER");365 println!("// This code is automatically generated");366 println!();367 println!("pragma solidity >=0.8.0 <0.9.0;");368 println!();369 for b in out.finish() {370 println!("{}", b);371 }372 println!("=== SNIP END ===");373 }374 };375}376377#[cfg(test)]378mod tests {379 use super::*;380381 #[test]382 fn function_selector_generation() {383 assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);384 }385386 #[test]387 fn event_topic_generation() {388 assert_eq!(389 hex::encode(&event_topic!(Transfer(address, address, uint256))[..]),390 "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",391 );392 }393}crates/evm-coder/tests/conditional_is.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/conditional_is.rs
+++ b/crates/evm-coder/tests/conditional_is.rs
@@ -1,4 +1,11 @@
use evm_coder::{types::*, solidity_interface, execution::Result};
+use evm_coder::{
+ make_signature,
+ custom_signature::{
+ SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+ },
+ types::Signature,
+};
pub struct Contract(bool);
crates/evm-coder/tests/generics.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/generics.rs
+++ b/crates/evm-coder/tests/generics.rs
@@ -16,6 +16,12 @@
use std::marker::PhantomData;
use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
+use evm_coder::{
+ make_signature,
+ custom_signature::{
+ SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+ },
+};
pub struct Generic<T>(PhantomData<T>);
crates/evm-coder/tests/random.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/random.rs
+++ b/crates/evm-coder/tests/random.rs
@@ -17,6 +17,13 @@
#![allow(dead_code)] // This test only checks that macros is not panicking
use evm_coder::{ToLog, execution::Result, solidity_interface, types::*, solidity, weight};
+use evm_coder::{
+ make_signature,
+ custom_signature::{
+ SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+ },
+ types::Signature,
+};
pub struct Impls;
crates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/solidity_generation.rs
+++ b/crates/evm-coder/tests/solidity_generation.rs
@@ -15,6 +15,13 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
+use evm_coder::{
+ make_signature,
+ custom_signature::{
+ SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+ },
+ types::Signature,
+};
pub struct ERC20;
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -116,8 +116,8 @@
await checkInterface(helper, '0x780e9d63', true, true);
});
- itEth('ERC721UniqueExtensions - 0x244543ee - support', async ({helper}) => {
- await checkInterface(helper, '0x244543ee', true, true);
+ itEth('ERC721UniqueExtensions support', async ({helper}) => {
+ expect(await contract(helper).methods.supportsInterface('0xb76006ac').call()).to.be.true;
});
itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -410,14 +410,13 @@
});
itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
- const alice = privateKey('//Alice');
- const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+ const collection = await helper.nft.mintCollection(donor, {name: 'A', description: 'B', tokenPrefix: 'C'});
const owner = privateKey('//Bob');
- const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+ const spender = await helper.eth.createAccountWithBalance(donor, 100n);
const receiver = privateKey('//Charlie');
- const token = await collection.mintToken(alice, {Substrate: owner.address});
+ const token = await collection.mintToken(donor, {Substrate: owner.address});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'nft');
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -295,14 +295,13 @@
});
itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
- const alice = privateKey('//Alice');
- const collection = await helper.rft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+ const collection = await helper.rft.mintCollection(donor, {name: 'A', description: 'B', tokenPrefix: 'C'});
const owner = privateKey('//Bob');
- const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+ const spender = await helper.eth.createAccountWithBalance(donor, 100n);
const receiver = privateKey('//Charlie');
- const token = await collection.mintToken(alice, 100n, {Substrate: owner.address});
+ const token = await collection.mintToken(donor, 100n, {Substrate: owner.address});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'rft');