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.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -32,7 +32,7 @@
cmp::Reverse,
};
use impl_trait_for_tuples::impl_for_tuples;
-use crate::{types::*, custom_signature::FunctionSignature};
+use crate::{types::*, custom_signature::SignatureUnit};
#[derive(Default)]
pub struct TypeCollector {
@@ -486,7 +486,7 @@
pub docs: &'static [&'static str],
pub selector: u32,
pub hide: bool,
- pub custom_signature: FunctionSignature,
+ pub custom_signature: SignatureUnit,
pub name: &'static str,
pub args: A,
pub result: R,
@@ -512,7 +512,7 @@
writeln!(
writer,
"\t{hide_comment}/// or in textual repr: {}",
- self.custom_signature.as_str()
+ self.custom_signature.as_str().expect("bad utf-8")
)?;
write!(writer, "\t{hide_comment}function {}(", self.name)?;
self.args.solidity_name(writer, tc)?;
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.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 of magic contract1819extern crate alloc;20use core::marker::PhantomData;21use evm_coder::{22 abi::AbiWriter,23 execution::Result,24 generate_stubgen, solidity_interface,25 types::*,26 ToLog,27 custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},28 make_signature,29};30use pallet_evm::{31 ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,32 account::CrossAccountId,33};34use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};35use pallet_evm_transaction_payment::CallContext;36use sp_core::{H160, U256};37use up_data_structs::SponsorshipState;38use crate::{39 AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,40 SponsoringRateLimit, SponsoringModeT, Sponsoring,41};42use frame_support::traits::Get;43use up_sponsorship::SponsorshipHandler;44use sp_std::vec::Vec;4546/// Pallet events.47#[derive(ToLog)]48pub enum ContractHelpersEvents {49 /// Contract sponsor was set.50 ContractSponsorSet {51 /// Contract address of the affected collection.52 #[indexed]53 contract_address: address,54 /// New sponsor address.55 sponsor: address,56 },5758 /// New sponsor was confirm.59 ContractSponsorshipConfirmed {60 /// Contract address of the affected collection.61 #[indexed]62 contract_address: address,63 /// New sponsor address.64 sponsor: address,65 },6667 /// Collection sponsor was removed.68 ContractSponsorRemoved {69 /// Contract address of the affected collection.70 #[indexed]71 contract_address: address,72 },73}7475/// See [`ContractHelpersCall`]76pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);77impl<T: Config> WithRecorder<T> for ContractHelpers<T> {78 fn recorder(&self) -> &SubstrateRecorder<T> {79 &self.080 }8182 fn into_recorder(self) -> SubstrateRecorder<T> {83 self.084 }85}8687/// @title Magic contract, which allows users to reconfigure other contracts88#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]89impl<T: Config> ContractHelpers<T>90where91 T::AccountId: AsRef<[u8; 32]>,92{93 /// Get user, which deployed specified contract94 /// @dev May return zero address in case if contract is deployed95 /// using uniquenetwork evm-migration pallet, or using other terms not96 /// intended by pallet-evm97 /// @dev Returns zero address if contract does not exists98 /// @param contractAddress Contract to get owner of99 /// @return address Owner of contract100 fn contract_owner(&self, contract_address: address) -> Result<address> {101 Ok(<Owner<T>>::get(contract_address))102 }103104 /// Set sponsor.105 /// @param contractAddress Contract for which a sponsor is being established.106 /// @param sponsor User address who set as pending sponsor.107 fn set_sponsor(108 &mut self,109 caller: caller,110 contract_address: address,111 sponsor: address,112 ) -> Result<void> {113 self.recorder().consume_sload()?;114 self.recorder().consume_sstore()?;115116 Pallet::<T>::set_sponsor(117 &T::CrossAccountId::from_eth(caller),118 contract_address,119 &T::CrossAccountId::from_eth(sponsor),120 )121 .map_err(dispatch_to_evm::<T>)?;122123 Ok(())124 }125126 /// Set contract as self sponsored.127 ///128 /// @param contractAddress Contract for which a self sponsoring is being enabled.129 fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {130 self.recorder().consume_sload()?;131 self.recorder().consume_sstore()?;132133 let caller = T::CrossAccountId::from_eth(caller);134135 Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())136 .map_err(dispatch_to_evm::<T>)?;137138 Pallet::<T>::force_set_sponsor(139 contract_address,140 &T::CrossAccountId::from_eth(contract_address),141 )142 .map_err(dispatch_to_evm::<T>)?;143144 Ok(())145 }146147 /// Remove sponsor.148 ///149 /// @param contractAddress Contract for which a sponsorship is being removed.150 fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {151 self.recorder().consume_sload()?;152 self.recorder().consume_sstore()?;153154 Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)155 .map_err(dispatch_to_evm::<T>)?;156157 Ok(())158 }159160 /// Confirm sponsorship.161 ///162 /// @dev Caller must be same that set via [`setSponsor`].163 ///164 /// @param contractAddress Сontract for which need to confirm sponsorship.165 fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {166 self.recorder().consume_sload()?;167 self.recorder().consume_sstore()?;168169 Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)170 .map_err(dispatch_to_evm::<T>)?;171172 Ok(())173 }174175 /// Get current sponsor.176 ///177 /// @param contractAddress The contract for which a sponsor is requested.178 /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.179 fn sponsor(&self, contract_address: address) -> Result<(address, uint256)> {180 let sponsor =181 Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;182 Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(183 &sponsor,184 ))185 }186187 /// Check tat contract has confirmed sponsor.188 ///189 /// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.190 /// @return **true** if contract has confirmed sponsor.191 fn has_sponsor(&self, contract_address: address) -> Result<bool> {192 Ok(Pallet::<T>::get_sponsor(contract_address).is_some())193 }194195 /// Check tat contract has pending sponsor.196 ///197 /// @param contractAddress The contract for which the presence of a pending sponsor is checked.198 /// @return **true** if contract has pending sponsor.199 fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {200 Ok(match Sponsoring::<T>::get(contract_address) {201 SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,202 SponsorshipState::Unconfirmed(_) => true,203 })204 }205206 fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {207 Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)208 }209210 fn set_sponsoring_mode(211 &mut self,212 caller: caller,213 contract_address: address,214 // TODO: implement support for enums in evm-coder215 mode: uint8,216 ) -> Result<void> {217 self.recorder().consume_sload()?;218 self.recorder().consume_sstore()?;219220 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;221 let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;222 <Pallet<T>>::set_sponsoring_mode(contract_address, mode);223224 Ok(())225 }226227 /// Get current contract sponsoring rate limit228 /// @param contractAddress Contract to get sponsoring rate limit of229 /// @return uint32 Amount of blocks between two sponsored transactions230 fn sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {231 self.recorder().consume_sload()?;232233 Ok(<SponsoringRateLimit<T>>::get(contract_address)234 .try_into()235 .map_err(|_| "rate limit > u32::MAX")?)236 }237238 /// Set contract sponsoring rate limit239 /// @dev Sponsoring rate limit - is a minimum amount of blocks that should240 /// pass between two sponsored transactions241 /// @param contractAddress Contract to change sponsoring rate limit of242 /// @param rateLimit Target rate limit243 /// @dev Only contract owner can change this setting244 fn set_sponsoring_rate_limit(245 &mut self,246 caller: caller,247 contract_address: address,248 rate_limit: uint32,249 ) -> Result<void> {250 self.recorder().consume_sload()?;251 self.recorder().consume_sstore()?;252253 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;254 <Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());255 Ok(())256 }257258 /// Set contract sponsoring fee limit259 /// @dev Sponsoring fee limit - is maximum fee that could be spent by260 /// single transaction261 /// @param contractAddress Contract to change sponsoring fee limit of262 /// @param feeLimit Fee limit263 /// @dev Only contract owner can change this setting264 fn set_sponsoring_fee_limit(265 &mut self,266 caller: caller,267 contract_address: address,268 fee_limit: uint256,269 ) -> Result<void> {270 self.recorder().consume_sload()?;271 self.recorder().consume_sstore()?;272273 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;274 <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())275 .map_err(dispatch_to_evm::<T>)?;276 Ok(())277 }278279 /// Get current contract sponsoring fee limit280 /// @param contractAddress Contract to get sponsoring fee limit of281 /// @return uint256 Maximum amount of fee that could be spent by single282 /// transaction283 fn sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {284 self.recorder().consume_sload()?;285286 Ok(get_sponsoring_fee_limit::<T>(contract_address))287 }288289 /// Is specified user present in contract allow list290 /// @dev Contract owner always implicitly included291 /// @param contractAddress Contract to check allowlist of292 /// @param user User to check293 /// @return bool Is specified users exists in contract allowlist294 fn allowed(&self, contract_address: address, user: address) -> Result<bool> {295 self.0.consume_sload()?;296 Ok(<Pallet<T>>::allowed(contract_address, user))297 }298299 /// Toggle user presence in contract allowlist300 /// @param contractAddress Contract to change allowlist of301 /// @param user Which user presence should be toggled302 /// @param isAllowed `true` if user should be allowed to be sponsored303 /// or call this contract, `false` otherwise304 /// @dev Only contract owner can change this setting305 fn toggle_allowed(306 &mut self,307 caller: caller,308 contract_address: address,309 user: address,310 is_allowed: bool,311 ) -> Result<void> {312 self.recorder().consume_sload()?;313 self.recorder().consume_sstore()?;314315 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;316 <Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);317318 Ok(())319 }320321 /// Is this contract has allowlist access enabled322 /// @dev Allowlist always can have users, and it is used for two purposes:323 /// in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist324 /// in case of allowlist access enabled, only users from allowlist may call this contract325 /// @param contractAddress Contract to get allowlist access of326 /// @return bool Is specified contract has allowlist access enabled327 fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {328 Ok(<AllowlistEnabled<T>>::get(contract_address))329 }330331 /// Toggle contract allowlist access332 /// @param contractAddress Contract to change allowlist access of333 /// @param enabled Should allowlist access to be enabled?334 fn toggle_allowlist(335 &mut self,336 caller: caller,337 contract_address: address,338 enabled: bool,339 ) -> Result<void> {340 self.recorder().consume_sload()?;341 self.recorder().consume_sstore()?;342343 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;344 <Pallet<T>>::toggle_allowlist(contract_address, enabled);345 Ok(())346 }347}348349/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]350pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);351impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>352where353 T::AccountId: AsRef<[u8; 32]>,354{355 fn is_reserved(contract: &sp_core::H160) -> bool {356 contract == &T::ContractAddress::get()357 }358359 fn is_used(contract: &sp_core::H160) -> bool {360 contract == &T::ContractAddress::get()361 }362363 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {364 // TODO: Extract to another OnMethodCall handler365 if <AllowlistEnabled<T>>::get(handle.code_address())366 && !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)367 {368 return Some(Err(PrecompileFailure::Revert {369 exit_status: ExitRevert::Reverted,370 output: {371 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));372 writer.string("Target contract is allowlisted");373 writer.finish()374 },375 }));376 }377378 if handle.code_address() != T::ContractAddress::get() {379 return None;380 }381382 let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));383 pallet_evm_coder_substrate::call(handle, helpers)384 }385386 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {387 (contract == &T::ContractAddress::get())388 .then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())389 }390}391392/// Hooks into contract creation, storing owner of newly deployed contract393pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);394impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {395 fn on_create(owner: H160, contract: H160) {396 <Owner<T>>::insert(contract, owner);397 }398}399400/// Bridge to pallet-sponsoring401pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);402impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>403 for HelpersContractSponsoring<T>404{405 fn get_sponsor(406 who: &T::CrossAccountId,407 call_context: &CallContext,408 ) -> Option<T::CrossAccountId> {409 let contract_address = call_context.contract_address;410 let mode = <Pallet<T>>::sponsoring_mode(contract_address);411 if mode == SponsoringModeT::Disabled {412 return None;413 }414415 let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {416 Some(sponsor) => sponsor,417 None => return None,418 };419420 if mode == SponsoringModeT::Allowlisted421 && !<Pallet<T>>::allowed(contract_address, *who.as_eth())422 {423 return None;424 }425 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;426427 if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {428 let limit = <SponsoringRateLimit<T>>::get(contract_address);429430 let timeout = last_tx_block + limit;431 if block_number < timeout {432 return None;433 }434 }435436 let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);437438 if call_context.max_fee > sponsored_fee_limit {439 return None;440 }441442 <SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);443444 Some(sponsor)445 }446}447448fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {449 <SponsoringFeeLimit<T>>::get(contract_address)450 .get(&0xffffffff)451 .cloned()452 .unwrap_or(U256::MAX)453}454455generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);456generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);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 of magic contract1819extern crate alloc;20use core::marker::PhantomData;21use evm_coder::{22 abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,23};24use pallet_evm::{25 ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,26 account::CrossAccountId,27};28use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder, dispatch_to_evm};29use pallet_evm_transaction_payment::CallContext;30use sp_core::{H160, U256};31use up_data_structs::SponsorshipState;32use crate::{33 AllowlistEnabled, Config, Owner, Pallet, SponsorBasket, SponsoringFeeLimit,34 SponsoringRateLimit, SponsoringModeT, Sponsoring,35};36use frame_support::traits::Get;37use up_sponsorship::SponsorshipHandler;38use sp_std::vec::Vec;3940/// Pallet events.41#[derive(ToLog)]42pub enum ContractHelpersEvents {43 /// Contract sponsor was set.44 ContractSponsorSet {45 /// Contract address of the affected collection.46 #[indexed]47 contract_address: address,48 /// New sponsor address.49 sponsor: address,50 },5152 /// New sponsor was confirm.53 ContractSponsorshipConfirmed {54 /// Contract address of the affected collection.55 #[indexed]56 contract_address: address,57 /// New sponsor address.58 sponsor: address,59 },6061 /// Collection sponsor was removed.62 ContractSponsorRemoved {63 /// Contract address of the affected collection.64 #[indexed]65 contract_address: address,66 },67}6869/// See [`ContractHelpersCall`]70pub struct ContractHelpers<T: Config>(SubstrateRecorder<T>);71impl<T: Config> WithRecorder<T> for ContractHelpers<T> {72 fn recorder(&self) -> &SubstrateRecorder<T> {73 &self.074 }7576 fn into_recorder(self) -> SubstrateRecorder<T> {77 self.078 }79}8081/// @title Magic contract, which allows users to reconfigure other contracts82#[solidity_interface(name = ContractHelpers, events(ContractHelpersEvents))]83impl<T: Config> ContractHelpers<T>84where85 T::AccountId: AsRef<[u8; 32]>,86{87 /// Get user, which deployed specified contract88 /// @dev May return zero address in case if contract is deployed89 /// using uniquenetwork evm-migration pallet, or using other terms not90 /// intended by pallet-evm91 /// @dev Returns zero address if contract does not exists92 /// @param contractAddress Contract to get owner of93 /// @return address Owner of contract94 fn contract_owner(&self, contract_address: address) -> Result<address> {95 Ok(<Owner<T>>::get(contract_address))96 }9798 /// Set sponsor.99 /// @param contractAddress Contract for which a sponsor is being established.100 /// @param sponsor User address who set as pending sponsor.101 fn set_sponsor(102 &mut self,103 caller: caller,104 contract_address: address,105 sponsor: address,106 ) -> Result<void> {107 self.recorder().consume_sload()?;108 self.recorder().consume_sstore()?;109110 Pallet::<T>::set_sponsor(111 &T::CrossAccountId::from_eth(caller),112 contract_address,113 &T::CrossAccountId::from_eth(sponsor),114 )115 .map_err(dispatch_to_evm::<T>)?;116117 Ok(())118 }119120 /// Set contract as self sponsored.121 ///122 /// @param contractAddress Contract for which a self sponsoring is being enabled.123 fn self_sponsored_enable(&mut self, caller: caller, contract_address: address) -> Result<void> {124 self.recorder().consume_sload()?;125 self.recorder().consume_sstore()?;126127 let caller = T::CrossAccountId::from_eth(caller);128129 Pallet::<T>::ensure_owner(contract_address, *caller.as_eth())130 .map_err(dispatch_to_evm::<T>)?;131132 Pallet::<T>::force_set_sponsor(133 contract_address,134 &T::CrossAccountId::from_eth(contract_address),135 )136 .map_err(dispatch_to_evm::<T>)?;137138 Ok(())139 }140141 /// Remove sponsor.142 ///143 /// @param contractAddress Contract for which a sponsorship is being removed.144 fn remove_sponsor(&mut self, caller: caller, contract_address: address) -> Result<void> {145 self.recorder().consume_sload()?;146 self.recorder().consume_sstore()?;147148 Pallet::<T>::remove_sponsor(&T::CrossAccountId::from_eth(caller), contract_address)149 .map_err(dispatch_to_evm::<T>)?;150151 Ok(())152 }153154 /// Confirm sponsorship.155 ///156 /// @dev Caller must be same that set via [`setSponsor`].157 ///158 /// @param contractAddress Сontract for which need to confirm sponsorship.159 fn confirm_sponsorship(&mut self, caller: caller, contract_address: address) -> Result<void> {160 self.recorder().consume_sload()?;161 self.recorder().consume_sstore()?;162163 Pallet::<T>::confirm_sponsorship(&T::CrossAccountId::from_eth(caller), contract_address)164 .map_err(dispatch_to_evm::<T>)?;165166 Ok(())167 }168169 /// Get current sponsor.170 ///171 /// @param contractAddress The contract for which a sponsor is requested.172 /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.173 fn sponsor(&self, contract_address: address) -> Result<(address, uint256)> {174 let sponsor =175 Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;176 Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(177 &sponsor,178 ))179 }180181 /// Check tat contract has confirmed sponsor.182 ///183 /// @param contractAddress The contract for which the presence of a confirmed sponsor is checked.184 /// @return **true** if contract has confirmed sponsor.185 fn has_sponsor(&self, contract_address: address) -> Result<bool> {186 Ok(Pallet::<T>::get_sponsor(contract_address).is_some())187 }188189 /// Check tat contract has pending sponsor.190 ///191 /// @param contractAddress The contract for which the presence of a pending sponsor is checked.192 /// @return **true** if contract has pending sponsor.193 fn has_pending_sponsor(&self, contract_address: address) -> Result<bool> {194 Ok(match Sponsoring::<T>::get(contract_address) {195 SponsorshipState::Disabled | SponsorshipState::Confirmed(_) => false,196 SponsorshipState::Unconfirmed(_) => true,197 })198 }199200 fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {201 Ok(<Pallet<T>>::sponsoring_mode(contract_address) != SponsoringModeT::Disabled)202 }203204 fn set_sponsoring_mode(205 &mut self,206 caller: caller,207 contract_address: address,208 // TODO: implement support for enums in evm-coder209 mode: uint8,210 ) -> Result<void> {211 self.recorder().consume_sload()?;212 self.recorder().consume_sstore()?;213214 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;215 let mode = SponsoringModeT::from_eth(mode).ok_or("unknown mode")?;216 <Pallet<T>>::set_sponsoring_mode(contract_address, mode);217218 Ok(())219 }220221 /// Get current contract sponsoring rate limit222 /// @param contractAddress Contract to get sponsoring rate limit of223 /// @return uint32 Amount of blocks between two sponsored transactions224 fn sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {225 self.recorder().consume_sload()?;226227 Ok(<SponsoringRateLimit<T>>::get(contract_address)228 .try_into()229 .map_err(|_| "rate limit > u32::MAX")?)230 }231232 /// Set contract sponsoring rate limit233 /// @dev Sponsoring rate limit - is a minimum amount of blocks that should234 /// pass between two sponsored transactions235 /// @param contractAddress Contract to change sponsoring rate limit of236 /// @param rateLimit Target rate limit237 /// @dev Only contract owner can change this setting238 fn set_sponsoring_rate_limit(239 &mut self,240 caller: caller,241 contract_address: address,242 rate_limit: uint32,243 ) -> Result<void> {244 self.recorder().consume_sload()?;245 self.recorder().consume_sstore()?;246247 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;248 <Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());249 Ok(())250 }251252 /// Set contract sponsoring fee limit253 /// @dev Sponsoring fee limit - is maximum fee that could be spent by254 /// single transaction255 /// @param contractAddress Contract to change sponsoring fee limit of256 /// @param feeLimit Fee limit257 /// @dev Only contract owner can change this setting258 fn set_sponsoring_fee_limit(259 &mut self,260 caller: caller,261 contract_address: address,262 fee_limit: uint256,263 ) -> Result<void> {264 self.recorder().consume_sload()?;265 self.recorder().consume_sstore()?;266267 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;268 <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())269 .map_err(dispatch_to_evm::<T>)?;270 Ok(())271 }272273 /// Get current contract sponsoring fee limit274 /// @param contractAddress Contract to get sponsoring fee limit of275 /// @return uint256 Maximum amount of fee that could be spent by single276 /// transaction277 fn sponsoring_fee_limit(&self, contract_address: address) -> Result<uint256> {278 self.recorder().consume_sload()?;279280 Ok(get_sponsoring_fee_limit::<T>(contract_address))281 }282283 /// Is specified user present in contract allow list284 /// @dev Contract owner always implicitly included285 /// @param contractAddress Contract to check allowlist of286 /// @param user User to check287 /// @return bool Is specified users exists in contract allowlist288 fn allowed(&self, contract_address: address, user: address) -> Result<bool> {289 self.0.consume_sload()?;290 Ok(<Pallet<T>>::allowed(contract_address, user))291 }292293 /// Toggle user presence in contract allowlist294 /// @param contractAddress Contract to change allowlist of295 /// @param user Which user presence should be toggled296 /// @param isAllowed `true` if user should be allowed to be sponsored297 /// or call this contract, `false` otherwise298 /// @dev Only contract owner can change this setting299 fn toggle_allowed(300 &mut self,301 caller: caller,302 contract_address: address,303 user: address,304 is_allowed: bool,305 ) -> Result<void> {306 self.recorder().consume_sload()?;307 self.recorder().consume_sstore()?;308309 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;310 <Pallet<T>>::toggle_allowed(contract_address, user, is_allowed);311312 Ok(())313 }314315 /// Is this contract has allowlist access enabled316 /// @dev Allowlist always can have users, and it is used for two purposes:317 /// in case of allowlist sponsoring mode, users will be sponsored if they exist in allowlist318 /// in case of allowlist access enabled, only users from allowlist may call this contract319 /// @param contractAddress Contract to get allowlist access of320 /// @return bool Is specified contract has allowlist access enabled321 fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {322 Ok(<AllowlistEnabled<T>>::get(contract_address))323 }324325 /// Toggle contract allowlist access326 /// @param contractAddress Contract to change allowlist access of327 /// @param enabled Should allowlist access to be enabled?328 fn toggle_allowlist(329 &mut self,330 caller: caller,331 contract_address: address,332 enabled: bool,333 ) -> Result<void> {334 self.recorder().consume_sload()?;335 self.recorder().consume_sstore()?;336337 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;338 <Pallet<T>>::toggle_allowlist(contract_address, enabled);339 Ok(())340 }341}342343/// Implements [`OnMethodCall`], which delegates call to [`ContractHelpers`]344pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);345impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T>346where347 T::AccountId: AsRef<[u8; 32]>,348{349 fn is_reserved(contract: &sp_core::H160) -> bool {350 contract == &T::ContractAddress::get()351 }352353 fn is_used(contract: &sp_core::H160) -> bool {354 contract == &T::ContractAddress::get()355 }356357 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {358 // TODO: Extract to another OnMethodCall handler359 if <AllowlistEnabled<T>>::get(handle.code_address())360 && !<Pallet<T>>::allowed(handle.code_address(), handle.context().caller)361 {362 return Some(Err(PrecompileFailure::Revert {363 exit_status: ExitRevert::Reverted,364 output: {365 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));366 writer.string("Target contract is allowlisted");367 writer.finish()368 },369 }));370 }371372 if handle.code_address() != T::ContractAddress::get() {373 return None;374 }375376 let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));377 pallet_evm_coder_substrate::call(handle, helpers)378 }379380 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {381 (contract == &T::ContractAddress::get())382 .then(|| include_bytes!("./stubs/ContractHelpers.raw").to_vec())383 }384}385386/// Hooks into contract creation, storing owner of newly deployed contract387pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);388impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {389 fn on_create(owner: H160, contract: H160) {390 <Owner<T>>::insert(contract, owner);391 }392}393394/// Bridge to pallet-sponsoring395pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);396impl<T: Config> SponsorshipHandler<T::CrossAccountId, CallContext>397 for HelpersContractSponsoring<T>398{399 fn get_sponsor(400 who: &T::CrossAccountId,401 call_context: &CallContext,402 ) -> Option<T::CrossAccountId> {403 let contract_address = call_context.contract_address;404 let mode = <Pallet<T>>::sponsoring_mode(contract_address);405 if mode == SponsoringModeT::Disabled {406 return None;407 }408409 let sponsor = match <Pallet<T>>::get_sponsor(contract_address) {410 Some(sponsor) => sponsor,411 None => return None,412 };413414 if mode == SponsoringModeT::Allowlisted415 && !<Pallet<T>>::allowed(contract_address, *who.as_eth())416 {417 return None;418 }419 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;420421 if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {422 let limit = <SponsoringRateLimit<T>>::get(contract_address);423424 let timeout = last_tx_block + limit;425 if block_number < timeout {426 return None;427 }428 }429430 let sponsored_fee_limit = get_sponsoring_fee_limit::<T>(contract_address);431432 if call_context.max_fee > sponsored_fee_limit {433 return None;434 }435436 <SponsorBasket<T>>::insert(contract_address, who.as_eth(), block_number);437438 Some(sponsor)439 }440}441442fn get_sponsoring_fee_limit<T: Config>(contract_address: address) -> uint256 {443 <SponsoringFeeLimit<T>>::get(contract_address)444 .get(&0xffffffff)445 .cloned()446 .unwrap_or(U256::MAX)447}448449generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);450generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);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;