difftreelog
refactor unify function and type signature handling
in: master
12 files changed
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
@@ -24,8 +24,8 @@
use quote::{quote, format_ident};
use inflector::cases;
use syn::{
- Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
- MetaNameValue, PatType, PathArguments, ReturnType, Type,
+ Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,
+ PatType, ReturnType, Type,
spanned::Spanned,
parse::{Parse, ParseStream},
parenthesized, Token, LitInt, LitStr,
@@ -601,12 +601,12 @@
let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);
let custom_signature = self.expand_custom_signature();
quote! {
- const #screaming_name_signature: ::evm_coder::custom_signature::FunctionSignature = #custom_signature;
+ const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;
const #screaming_name: ::evm_coder::types::bytes4 = {
let mut sum = ::evm_coder::sha3_const::Keccak256::new();
let mut pos = 0;
- while pos < Self::#screaming_name_signature.unit.len {
- sum = sum.update(&[Self::#screaming_name_signature.unit.data[pos]; 1]);
+ while pos < Self::#screaming_name_signature.len {
+ sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);
pos += 1;
}
let a = sum.finalize();
@@ -710,192 +710,28 @@
};
quote! {
Self::#pascal_name #matcher => ().into()
- }
- }
- }
-
- fn expand_type(ty: &Type, token_stream: &mut proc_macro2::TokenStream, read_signature: bool) {
- match ty {
- Type::Path(tp) => {
- if let Some(qself) = &tp.qself {
- panic!("no receiver expected {:?}", qself.ty.span());
- }
- let path = &tp.path;
- if path.segments.len() != 1 {
- panic!("expected path to have only one segment {:?}", path.span());
- }
- let last_segment = path.segments.last().unwrap();
-
- if last_segment.ident == "Vec" {
- let args = match &last_segment.arguments {
- PathArguments::AngleBracketed(e) => e,
- _ => {
- panic!("missing Vec generic {:?}", last_segment.arguments.span());
- }
- };
- let args = &args.args;
- if args.len() != 1 {
- panic!("expected only one generic for vec {:?}", args.span());
- }
- let arg = args.first().expect("first arg");
-
- let ty = match arg {
- GenericArgument::Type(ty) => ty,
- _ => {
- panic!("expected first generic to be type {:?}", arg.span());
- }
- };
-
- let mut vec_token = proc_macro2::TokenStream::new();
- Self::expand_type(ty, &mut vec_token, false);
- vec_token = if read_signature {
- quote! { (<Vec<#vec_token>>::SIGNATURE) }
- } else {
- quote! { <Vec<#vec_token>> }
- };
- token_stream.extend(vec_token);
- } else {
- if !last_segment.arguments.is_empty() {
- panic!(
- "unexpected generic arguments for non-vec type {:?}",
- last_segment.arguments.span()
- );
- }
-
- let ident = &last_segment.ident;
- let plain_token = if read_signature {
- quote! {
- (<#ident>::SIGNATURE)
- }
- } else {
- quote! {
- #ident
- }
- };
-
- token_stream.extend(plain_token);
- }
- }
-
- Type::Tuple(tt) => {
- // for ty in tt.elems.iter() {
- // out.push(AbiType::try_from(ty)?)
- // }
-
- let mut tuple_types = proc_macro2::TokenStream::new();
- let mut is_first = true;
-
- for ty in tt.elems.iter() {
- if is_first {
- is_first = false
- } else {
- tuple_types.extend(quote!(,));
- }
- Self::expand_type(ty, &mut tuple_types, false);
- }
- tuple_types = if read_signature {
- quote! { (<(#tuple_types)>::SIGNATURE) }
- } else {
- quote! { (#tuple_types) }
- };
- token_stream.extend(tuple_types);
}
-
- // Type::Array(arr) => {
- // let wrapped = AbiType::try_from(&arr.elem)?;
- // match &arr.len {
- // Expr::Lit(l) => match &l.lit {
- // Lit::Int(i) => {
- // let num = i.base10_parse::<usize>()?;
- // Ok(AbiType::Array(Box::new(wrapped), num as usize))
- // }
- // _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),
- // },
- // _ => Err(syn::Error::new(arr.len.span(), "should be literal")),
- // }
- // }
- _ => panic!("Unexpected type {ty:?}"),
}
- // match ty {
- // AbiType::Plain(ref ident) => {
- // let plain_token = if read_signature {
- // quote! {
- // (<#ident>::SIGNATURE)
- // }
- // } else {
- // quote! {
- // #ident
- // }
- // };
-
- // token_stream.extend(plain_token);
- // }
-
- // AbiType::Tuple(ref tuple_type) => {
- // let mut tuple_types = proc_macro2::TokenStream::new();
- // let mut is_first = true;
-
- // for ty in tuple_type {
- // if is_first {
- // is_first = false
- // } else {
- // tuple_types.extend(quote!(,));
- // }
- // Self::expand_type(ty, &mut tuple_types, false);
- // }
- // tuple_types = if read_signature {
- // quote! { (<(#tuple_types)>::SIGNATURE) }
- // } else {
- // quote! { (#tuple_types) }
- // };
- // token_stream.extend(tuple_types);
- // }
-
- // AbiType::Vec(ref vec_type) => {
- // let mut vec_token = proc_macro2::TokenStream::new();
- // Self::expand_type(vec_type.as_ref(), &mut vec_token, false);
- // vec_token = if read_signature {
- // quote! { (<Vec<#vec_token>>::SIGNATURE) }
- // } else {
- // quote! { <Vec<#vec_token>> }
- // };
- // token_stream.extend(vec_token);
- // }
-
- // AbiType::Array(_, _) => todo!("Array eth signature"),
- // };
}
fn expand_custom_signature(&self) -> proc_macro2::TokenStream {
- let mut token_stream = TokenStream::new();
+ let mut args = TokenStream::new();
let mut is_first = true;
- for arg in &self.args {
- if arg.is_special() {
- continue;
- }
-
- if is_first {
- is_first = false;
- } else {
- token_stream.extend(quote!(,));
- }
- Self::expand_type(&arg.ty, &mut token_stream, true);
+ for arg in self.args.iter().filter(|a| !a.is_special()) {
+ is_first = false;
+ let ty = &arg.ty;
+ args.extend(quote! {nameof(#ty)});
+ args.extend(quote! {fixed(",")})
}
+ // Remove trailing comma
if !is_first {
- token_stream.extend(quote!(,));
+ args.extend(quote! {shift_left(1)})
}
let func_name = self.camel_name.clone();
- let func_name = quote!(SignaturePreferences {
- open_name: Some(SignatureUnit::new(#func_name)),
- open_delimiter: Some(SignatureUnit::new("(")),
- param_delimiter: Some(SignatureUnit::new(",")),
- close_delimiter: Some(SignatureUnit::new(")")),
- close_name: None,
- });
- quote!({ ::evm_coder::make_signature!(new fn(#func_name), #token_stream) })
+ quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }
}
fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
@@ -916,12 +752,6 @@
let screaming_name = &self.screaming_name;
let hide = self.hide;
let custom_signature = self.expand_custom_signature();
- let custom_signature = quote!(
- {
- const cs: FunctionSignature = #custom_signature;
- cs
- }
- );
let is_payable = self.has_value_args;
quote! {
crates/evm-coder/src/abi.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi.rs
+++ b/crates/evm-coder/src/abi.rs
@@ -27,7 +27,7 @@
execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},
types::*,
make_signature,
- custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT},
+ custom_signature::{SignatureUnit},
};
use crate::execution::Result;
@@ -428,7 +428,7 @@
}
impl<R: Signature> Signature for Vec<R> {
- make_signature!(new nameof(R) fixed("[]"));
+ const SIGNATURE: SignatureUnit = make_signature!(new nameof(R) fixed("[]"));
}
impl sealed::CanBePlacedInVec for EthCrossAccount {}
@@ -522,7 +522,7 @@
where
$($ident: Signature,)+
{
- make_signature!(
+ const SIGNATURE: SignatureUnit = make_signature!(
new fixed("(")
$(nameof($ident) fixed(","))+
shift_left(1)
@@ -758,13 +758,13 @@
1ACF2D55
0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
-
+
0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
000000000000000000000000000000000000000000000000000000000000000A // uint256
-
+
000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
0000000000000000000000000000000000000000000000000000000000000014 // uint256
-
+
0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
000000000000000000000000000000000000000000000000000000000000001E // uint256
"
crates/evm-coder/src/custom_signature.rsdiffbeforeafterboth--- a/crates/evm-coder/src/custom_signature.rs
+++ b/crates/evm-coder/src/custom_signature.rs
@@ -74,132 +74,11 @@
//! 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;
- if let Some(ref name) = preferences.open_name {
- crate::make_signature!(@copy(name.data, dst, name.len, dst_offset));
- }
- if let Some(ref delimiter) = preferences.open_delimiter {
- crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
- }
- FunctionSignature {
- unit: SignatureUnit {
- data: dst,
- len: dst_offset,
- },
- preferences,
- }
- }
-
- /// 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,
- ) -> FunctionSignature {
- let mut dst = signature.unit.data;
- let mut dst_offset = signature.unit.len;
- crate::make_signature!(@copy(param.data, dst, param.len, dst_offset));
- if let Some(ref delimiter) = signature.preferences.param_delimiter {
- crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
- }
- FunctionSignature {
- unit: SignatureUnit {
- data: dst,
- len: dst_offset,
- },
- ..signature
- }
- }
-
- /// 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 };
- if let Some(ref delimiter) = signature.preferences.close_delimiter {
- crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
- }
- if let Some(ref name) = signature.preferences.close_name {
- crate::make_signature!(@copy(name.data, dst, name.len, dst_offset));
- }
- FunctionSignature {
- unit: SignatureUnit {
- data: dst,
- len: dst_offset,
- },
- ..signature
- }
- }
-
- /// 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 {
@@ -222,6 +101,10 @@
len: name_len,
}
}
+ /// String conversion
+ pub fn as_str(&self) -> Option<&str> {
+ core::str::from_utf8(&self.data[0..self.len]).ok()
+ }
}
/// ### Macro to create signatures of types and functions.
@@ -231,85 +114,52 @@
/// 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]
macro_rules! make_signature {
- (new fn($func:expr)$(,)*) => {
- {
- let fs = FunctionSignature::new($func);
- let fs = FunctionSignature::done(fs, false);
- fs
- }
- };
- (new fn($func:expr), $($tt:tt,)*) => {
- {
- let fs = FunctionSignature::new($func);
- let fs = make_signature!(@param; fs, $($tt),*);
- fs
- }
+ (new $($tt:tt)*) => {
+ ($crate::custom_signature::SignatureUnit {
+ data: {
+ let mut out = [0u8; $crate::custom_signature::SIGNATURE_SIZE_LIMIT];
+ let mut dst_offset = 0;
+ $crate::make_signature!(@data(out, dst_offset); $($tt)*);
+ out
+ },
+ len: {0 + $crate::make_signature!(@size; $($tt)*)},
+ })
};
- (@param; $func:expr) => {
- FunctionSignature::done($func, true)
+ (@size;) => {
+ 0
};
- (@param; $func:expr, $param:expr) => {
- make_signature!(@param; FunctionSignature::add_param($func, $param))
+ (@size; fixed($expr:expr) $($tt:tt)*) => {
+ $expr.len() + $crate::make_signature!(@size; $($tt)*)
};
- (@param; $func:expr, $param:expr, $($tt:tt),*) => {
- make_signature!(@param; FunctionSignature::add_param($func, $param), $($tt),*)
+ (@size; nameof($expr:ty) $($tt:tt)*) => {
+ <$expr>::SIGNATURE.len + $crate::make_signature!(@size; $($tt)*)
};
-
- (new $($tt:tt)*) => {
- const SIGNATURE: SignatureUnit = SignatureUnit {
- data: {
- let mut out = [0u8; SIGNATURE_SIZE_LIMIT];
- let mut dst_offset = 0;
- make_signature!(@data(out, dst_offset); $($tt)*);
- out
- },
- len: {0 + make_signature!(@size; $($tt)*)},
- };
- };
-
- (@size;) => {
- 0
- };
- (@size; fixed($expr:expr) $($tt:tt)*) => {
- $expr.len() + make_signature!(@size; $($tt)*)
- };
- (@size; nameof($expr:ty) $($tt:tt)*) => {
- <$expr>::SIGNATURE.len + make_signature!(@size; $($tt)*)
- };
(@size; shift_left($expr:expr) $($tt:tt)*) => {
- make_signature!(@size; $($tt)*) - $expr
+ $crate::make_signature!(@size; $($tt)*) - $expr
};
- (@data($dst:ident, $dst_offset:ident);) => {};
- (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
- {
- let data = $expr.as_bytes();
+ (@data($dst:ident, $dst_offset:ident);) => {};
+ (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
+ {
+ let data = $expr.as_bytes();
let data_len = data.len();
- make_signature!(@copy(data, $dst, data_len, $dst_offset));
- }
- make_signature!(@data($dst, $dst_offset); $($tt)*)
- };
- (@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {
- {
- make_signature!(@copy(&<$expr>::SIGNATURE.data, $dst, <$expr>::SIGNATURE.len, $dst_offset));
- }
- make_signature!(@data($dst, $dst_offset); $($tt)*)
- };
+ $crate::make_signature!(@copy(data, $dst, data_len, $dst_offset));
+ }
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+ (@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {
+ {
+ $crate::make_signature!(@copy(&<$expr>::SIGNATURE.data, $dst, <$expr>::SIGNATURE.len, $dst_offset));
+ }
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
(@data($dst:ident, $dst_offset:ident); shift_left($expr:expr) $($tt:tt)*) => {
- $dst_offset -= $expr;
- make_signature!(@data($dst, $dst_offset); $($tt)*)
- };
+ $dst_offset -= $expr;
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
(@copy($src:expr, $dst:expr, $src_len:expr, $dst_offset:ident)) => {
{
@@ -328,7 +178,7 @@
mod test {
use core::str::from_utf8;
- use super::{SIGNATURE_SIZE_LIMIT, SignatureUnit, FunctionSignature, SignaturePreferences};
+ use super::{SIGNATURE_SIZE_LIMIT, SignatureUnit};
trait Name {
const SIGNATURE: SignatureUnit;
@@ -339,19 +189,21 @@
}
impl Name for u8 {
- make_signature!(new fixed("uint8"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint8"));
}
impl Name for u32 {
- make_signature!(new fixed("uint32"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint32"));
}
impl<T: Name> Name for Vec<T> {
- make_signature!(new nameof(T) fixed("[]"));
+ const SIGNATURE: SignatureUnit = make_signature!(new nameof(T) fixed("[]"));
}
impl<A: Name, B: Name> Name for (A, B) {
- make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
+ const SIGNATURE: SignatureUnit =
+ make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
}
impl<A: Name> Name for (A,) {
- make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));
+ const SIGNATURE: SignatureUnit =
+ make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));
}
struct MaxSize();
@@ -361,14 +213,6 @@
len: SIGNATURE_SIZE_LIMIT,
};
}
-
- 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,
- };
#[test]
fn simple() {
@@ -421,68 +265,6 @@
#[test]
fn max_size() {
assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));
- }
-
- #[test]
- 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()");
- }
-
- #[test]
- fn make_func_with_1_args() {
- const SIG: FunctionSignature = make_signature!(
- new fn(SIGNATURE_PREFERENCES),
- (<u8>::SIGNATURE),
- );
- let name = SIG.as_str();
- similar_asserts::assert_eq!(name, "some_funk(uint8)");
- }
-
- #[test]
- fn make_func_with_2_args() {
- const SIG: FunctionSignature = make_signature!(
- new fn(SIGNATURE_PREFERENCES),
- (u8::SIGNATURE),
- (<Vec<u32>>::SIGNATURE),
- );
- let name = SIG.as_str();
- similar_asserts::assert_eq!(name, "some_funk(uint8,uint32[])");
- }
-
- #[test]
- fn make_func_with_3_args() {
- const SIG: FunctionSignature = make_signature!(
- new fn(SIGNATURE_PREFERENCES),
- (<u8>::SIGNATURE),
- (<u32>::SIGNATURE),
- (<Vec<u32>>::SIGNATURE),
- );
- let name = SIG.as_str();
- similar_asserts::assert_eq!(name, "some_funk(uint8,uint32,uint32[])");
- }
-
- #[test]
- fn make_slice_from_signature() {
- const SIG: FunctionSignature = make_signature!(
- new fn(SIGNATURE_PREFERENCES),
- (<u8>::SIGNATURE),
- (<u32>::SIGNATURE),
- (<Vec<u32>>::SIGNATURE),
- );
- const NAME: [u8; SIG.unit.len] = {
- let mut name: [u8; SIG.unit.len] = [0; SIG.unit.len];
- let mut i = 0;
- while i < SIG.unit.len {
- name[i] = SIG.unit.data[i];
- i += 1;
- }
- name
- };
- similar_asserts::assert_eq!(&NAME, b"some_funk(uint8,uint32,uint32[])");
}
#[test]
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -122,7 +122,7 @@
use primitive_types::{U256, H160, H256};
use core::str::from_utf8;
- use crate::custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT};
+ use crate::custom_signature::SignatureUnit;
pub trait Signature {
const SIGNATURE: SignatureUnit;
@@ -133,14 +133,14 @@
}
impl Signature for bool {
- make_signature!(new fixed("bool"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bool"));
}
macro_rules! define_simple_type {
(type $ident:ident = $ty:ty) => {
pub type $ident = $ty;
impl Signature for $ty {
- make_signature!(new fixed(stringify!($ident)));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ident)));
}
};
}
@@ -165,7 +165,7 @@
#[derive(Default, Debug)]
pub struct bytes(pub Vec<u8>);
impl Signature for bytes {
- make_signature!(new fixed("bytes"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));
}
/// Solidity doesn't have `void` type, however we have special implementation
@@ -259,7 +259,7 @@
}
impl Signature for EthCrossAccount {
- make_signature!(new fixed("(address,uint256)"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("(address,uint256)"));
}
/// Convert `CrossAccountId` to `uint256`.
crates/evm-coder/src/solidity.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//! 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::*, custom_signature::FunctionSignature};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_struct::<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: u32,488 pub hide: bool,489 pub custom_signature: FunctionSignature,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.custom_signature.as_str()516 )?;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}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::*, custom_signature::SignatureUnit};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_struct::<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: u32,488 pub hide: bool,489 pub custom_signature: SignatureUnit,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.custom_signature.as_str().expect("bad utf-8")516 )?;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}pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -21,8 +21,6 @@
types::*,
execution::{Result, Error},
weight,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
};
pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};
use pallet_evm_coder_substrate::dispatch_to_evm;
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -19,13 +19,7 @@
extern crate alloc;
use core::marker::PhantomData;
use evm_coder::{
- abi::AbiWriter,
- execution::Result,
- generate_stubgen, solidity_interface,
- types::*,
- ToLog,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
+ abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
};
use pallet_evm::{
ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -19,15 +19,7 @@
extern crate alloc;
use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
use core::convert::TryInto;
-use evm_coder::{
- ToLog,
- execution::*,
- generate_stubgen, solidity_interface,
- types::*,
- weight,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
use up_data_structs::CollectionMode;
use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
use sp_std::vec::Vec;
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -24,15 +24,7 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{
- ToLog,
- execution::*,
- generate_stubgen, solidity, solidity_interface,
- types::*,
- weight,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use frame_support::BoundedVec;
use up_data_structs::{
TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -25,15 +25,7 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{
- ToLog,
- execution::*,
- generate_stubgen, solidity, solidity_interface,
- types::*,
- weight,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use frame_support::{BoundedBTreeMap, BoundedVec};
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions,
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -29,15 +29,7 @@
convert::TryInto,
ops::Deref,
};
-use evm_coder::{
- ToLog,
- execution::*,
- generate_stubgen, solidity_interface,
- types::*,
- weight,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -18,13 +18,7 @@
use core::marker::PhantomData;
use ethereum as _;
-use evm_coder::{
- execution::*,
- generate_stubgen, solidity, solidity_interface,
- types::*,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature, weight,
-};
+use evm_coder::{execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use frame_support::traits::Get;
use crate::Pallet;