git.delta.rocks / unique-network / refs/commits / 5a3fe2c70832

difftreelog

refactor unify function and type signature handling

Yaroslav Bolyukin2022-11-02parent: #4c1a924.patch.diff
in: master

12 files changed

modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
24use quote::{quote, format_ident};24use quote::{quote, format_ident};
25use inflector::cases;25use inflector::cases;
26use syn::{26use syn::{
27 Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,27 Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,
28 MetaNameValue, PatType, PathArguments, ReturnType, Type,28 PatType, ReturnType, Type,
29 spanned::Spanned,29 spanned::Spanned,
30 parse::{Parse, ParseStream},30 parse::{Parse, ParseStream},
31 parenthesized, Token, LitInt, LitStr,31 parenthesized, Token, LitInt, LitStr,
601 let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);601 let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);
602 let custom_signature = self.expand_custom_signature();602 let custom_signature = self.expand_custom_signature();
603 quote! {603 quote! {
604 const #screaming_name_signature: ::evm_coder::custom_signature::FunctionSignature = #custom_signature;604 const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;
605 const #screaming_name: ::evm_coder::types::bytes4 = {605 const #screaming_name: ::evm_coder::types::bytes4 = {
606 let mut sum = ::evm_coder::sha3_const::Keccak256::new();606 let mut sum = ::evm_coder::sha3_const::Keccak256::new();
607 let mut pos = 0;607 let mut pos = 0;
608 while pos < Self::#screaming_name_signature.unit.len {608 while pos < Self::#screaming_name_signature.len {
609 sum = sum.update(&[Self::#screaming_name_signature.unit.data[pos]; 1]);609 sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);
610 pos += 1;610 pos += 1;
611 }611 }
612 let a = sum.finalize();612 let a = sum.finalize();
714 }714 }
715 }715 }
716
717 fn expand_type(ty: &Type, token_stream: &mut proc_macro2::TokenStream, read_signature: bool) {
718 match ty {
719 Type::Path(tp) => {
720 if let Some(qself) = &tp.qself {
721 panic!("no receiver expected {:?}", qself.ty.span());
722 }
723 let path = &tp.path;
724 if path.segments.len() != 1 {
725 panic!("expected path to have only one segment {:?}", path.span());
726 }
727 let last_segment = path.segments.last().unwrap();
728
729 if last_segment.ident == "Vec" {
730 let args = match &last_segment.arguments {
731 PathArguments::AngleBracketed(e) => e,
732 _ => {
733 panic!("missing Vec generic {:?}", last_segment.arguments.span());
734 }
735 };
736 let args = &args.args;
737 if args.len() != 1 {
738 panic!("expected only one generic for vec {:?}", args.span());
739 }
740 let arg = args.first().expect("first arg");
741
742 let ty = match arg {
743 GenericArgument::Type(ty) => ty,
744 _ => {
745 panic!("expected first generic to be type {:?}", arg.span());
746 }
747 };
748
749 let mut vec_token = proc_macro2::TokenStream::new();
750 Self::expand_type(ty, &mut vec_token, false);
751 vec_token = if read_signature {
752 quote! { (<Vec<#vec_token>>::SIGNATURE) }
753 } else {
754 quote! { <Vec<#vec_token>> }
755 };
756 token_stream.extend(vec_token);
757 } else {
758 if !last_segment.arguments.is_empty() {
759 panic!(
760 "unexpected generic arguments for non-vec type {:?}",
761 last_segment.arguments.span()
762 );
763 }
764
765 let ident = &last_segment.ident;
766 let plain_token = if read_signature {
767 quote! {
768 (<#ident>::SIGNATURE)
769 }
770 } else {
771 quote! {
772 #ident
773 }
774 };
775
776 token_stream.extend(plain_token);
777 }
778 }
779
780 Type::Tuple(tt) => {
781 // for ty in tt.elems.iter() {
782 // out.push(AbiType::try_from(ty)?)
783 // }
784
785 let mut tuple_types = proc_macro2::TokenStream::new();
786 let mut is_first = true;
787
788 for ty in tt.elems.iter() {
789 if is_first {
790 is_first = false
791 } else {
792 tuple_types.extend(quote!(,));
793 }
794 Self::expand_type(ty, &mut tuple_types, false);
795 }
796 tuple_types = if read_signature {
797 quote! { (<(#tuple_types)>::SIGNATURE) }
798 } else {
799 quote! { (#tuple_types) }
800 };
801 token_stream.extend(tuple_types);
802 }
803
804 // Type::Array(arr) => {
805 // let wrapped = AbiType::try_from(&arr.elem)?;
806 // match &arr.len {
807 // Expr::Lit(l) => match &l.lit {
808 // Lit::Int(i) => {
809 // let num = i.base10_parse::<usize>()?;
810 // Ok(AbiType::Array(Box::new(wrapped), num as usize))
811 // }
812 // _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),
813 // },
814 // _ => Err(syn::Error::new(arr.len.span(), "should be literal")),
815 // }
816 // }
817 _ => panic!("Unexpected type {ty:?}"),
818 }
819 // match ty {
820 // AbiType::Plain(ref ident) => {
821 // let plain_token = if read_signature {
822 // quote! {
823 // (<#ident>::SIGNATURE)
824 // }
825 // } else {
826 // quote! {
827 // #ident
828 // }
829 // };
830
831 // token_stream.extend(plain_token);
832 // }
833
834 // AbiType::Tuple(ref tuple_type) => {
835 // let mut tuple_types = proc_macro2::TokenStream::new();
836 // let mut is_first = true;
837
838 // for ty in tuple_type {
839 // if is_first {
840 // is_first = false
841 // } else {
842 // tuple_types.extend(quote!(,));
843 // }
844 // Self::expand_type(ty, &mut tuple_types, false);
845 // }
846 // tuple_types = if read_signature {
847 // quote! { (<(#tuple_types)>::SIGNATURE) }
848 // } else {
849 // quote! { (#tuple_types) }
850 // };
851 // token_stream.extend(tuple_types);
852 // }
853
854 // AbiType::Vec(ref vec_type) => {
855 // let mut vec_token = proc_macro2::TokenStream::new();
856 // Self::expand_type(vec_type.as_ref(), &mut vec_token, false);
857 // vec_token = if read_signature {
858 // quote! { (<Vec<#vec_token>>::SIGNATURE) }
859 // } else {
860 // quote! { <Vec<#vec_token>> }
861 // };
862 // token_stream.extend(vec_token);
863 // }
864
865 // AbiType::Array(_, _) => todo!("Array eth signature"),
866 // };
867 }
868716
869 fn expand_custom_signature(&self) -> proc_macro2::TokenStream {717 fn expand_custom_signature(&self) -> proc_macro2::TokenStream {
870 let mut token_stream = TokenStream::new();718 let mut args = TokenStream::new();
871719
872 let mut is_first = true;720 let mut is_first = true;
873 for arg in &self.args {721 for arg in self.args.iter().filter(|a| !a.is_special()) {
874 if arg.is_special() {
875 continue;
876 }
877
878 if is_first {
879 is_first = false;722 is_first = false;
880 } else {723 let ty = &arg.ty;
881 token_stream.extend(quote!(,));724 args.extend(quote! {nameof(#ty)});
882 }
883 Self::expand_type(&arg.ty, &mut token_stream, true);725 args.extend(quote! {fixed(",")})
884 }726 }
885727
728 // Remove trailing comma
886 if !is_first {729 if !is_first {
887 token_stream.extend(quote!(,));730 args.extend(quote! {shift_left(1)})
888 }731 }
889732
890 let func_name = self.camel_name.clone();733 let func_name = self.camel_name.clone();
891 let func_name = quote!(SignaturePreferences {
892 open_name: Some(SignatureUnit::new(#func_name)),
893 open_delimiter: Some(SignatureUnit::new("(")),
894 param_delimiter: Some(SignatureUnit::new(",")),
895 close_delimiter: Some(SignatureUnit::new(")")),
896 close_name: None,
897 });
898 quote!({ ::evm_coder::make_signature!(new fn(#func_name), #token_stream) })734 quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }
899 }735 }
900736
901 fn expand_solidity_function(&self) -> proc_macro2::TokenStream {737 fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
916 let screaming_name = &self.screaming_name;752 let screaming_name = &self.screaming_name;
917 let hide = self.hide;753 let hide = self.hide;
918 let custom_signature = self.expand_custom_signature();754 let custom_signature = self.expand_custom_signature();
919 let custom_signature = quote!(
920 {
921 const cs: FunctionSignature = #custom_signature;
922 cs
923 }
924 );
925 let is_payable = self.has_value_args;755 let is_payable = self.has_value_args;
926756
927 quote! {757 quote! {
modifiedcrates/evm-coder/src/abi.rsdiffbeforeafterboth
27 execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},27 execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},
28 types::*,28 types::*,
29 make_signature,29 make_signature,
30 custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT},30 custom_signature::{SignatureUnit},
31};31};
32use crate::execution::Result;32use crate::execution::Result;
3333
428}428}
429429
430impl<R: Signature> Signature for Vec<R> {430impl<R: Signature> Signature for Vec<R> {
431 make_signature!(new nameof(R) fixed("[]"));431 const SIGNATURE: SignatureUnit = make_signature!(new nameof(R) fixed("[]"));
432}432}
433433
434impl sealed::CanBePlacedInVec for EthCrossAccount {}434impl sealed::CanBePlacedInVec for EthCrossAccount {}
522 where522 where
523 $($ident: Signature,)+523 $($ident: Signature,)+
524 {524 {
525 make_signature!(525 const SIGNATURE: SignatureUnit = make_signature!(
526 new fixed("(")526 new fixed("(")
527 $(nameof($ident) fixed(","))+527 $(nameof($ident) fixed(","))+
528 shift_left(1)528 shift_left(1)
754 ),754 ),
755 ],755 ],
756 &hex!(756 &hex!(
757 "757 "
758 1ACF2D55758 1ACF2D55
759 0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]759 0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
760 0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]760 0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
761 761
762 0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address762 0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
763 000000000000000000000000000000000000000000000000000000000000000A // uint256763 000000000000000000000000000000000000000000000000000000000000000A // uint256
764 764
765 000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address765 000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
766 0000000000000000000000000000000000000000000000000000000000000014 // uint256766 0000000000000000000000000000000000000000000000000000000000000014 // uint256
767 767
768 0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address768 0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
769 000000000000000000000000000000000000000000000000000000000000001E // uint256769 000000000000000000000000000000000000000000000000000000000000001E // uint256
770 "770 "
771 )771 )
772 );772 );
773773
modifiedcrates/evm-coder/src/custom_signature.rsdiffbeforeafterboth
73//! }73//! }
74//! impl<T: SoliditySignature> SoliditySignature for Vec<T> {74//! impl<T: SoliditySignature> SoliditySignature for Vec<T> {
75//! make_signature!(new nameof(T) fixed("[]"));75//! make_signature!(new nameof(T) fixed("[]"));
76//! }
77//!
78//! // Function signature settings
79//! const SIGNATURE_PREFERENCES: SignaturePreferences = SignaturePreferences {
80//! open_name: Some(SignatureUnit::new("some_funk")),
81//! open_delimiter: Some(SignatureUnit::new("(")),
82//! param_delimiter: Some(SignatureUnit::new(",")),
83//! close_delimiter: Some(SignatureUnit::new(")")),
84//! close_name: None,
85//! };
86//!
87//! // Create functions signatures
88//! fn make_func_without_args() {
89//! const SIG: FunctionSignature = make_signature!(
90//! new fn(SIGNATURE_PREFERENCES),
91//! );
92//! let name = SIG.as_str();
93//! similar_asserts::assert_eq!(name, "some_funk()");
94//! }
95//!
96//! fn make_func_with_3_args() {
97//! const SIG: FunctionSignature = make_signature!(
98//! new fn(SIGNATURE_PREFERENCES),
99//! (<u8>::SIGNATURE),
100//! (<u8>::SIGNATURE),
101//! (<Vec<u8>>::SIGNATURE),
102//! );
103//! let name = SIG.as_str();
104//! similar_asserts::assert_eq!(name, "some_funk(uint8,uint8,uint8[])");
105//! }76//! }
106//! ```77//! ```
107use core::str::from_utf8;
10878
109/// The maximum length of the signature.79/// The maximum length of the signature.
110pub const SIGNATURE_SIZE_LIMIT: usize = 256;80pub const SIGNATURE_SIZE_LIMIT: usize = 256;
111
112/// Function signature formatting preferences.
113#[derive(Debug)]
114pub struct SignaturePreferences {
115 /// The name of the function before the list of parameters: `*some*(param1,param2)func`
116 pub open_name: Option<SignatureUnit>,
117 /// Opening separator: `some*(*param1,param2)func`
118 pub open_delimiter: Option<SignatureUnit>,
119 /// Parameters separator: `some(param1*,*param2)func`
120 pub param_delimiter: Option<SignatureUnit>,
121 /// Closinging separator: `some(param1,param2*)*func`
122 pub close_delimiter: Option<SignatureUnit>,
123 /// The name of the function after the list of parameters: `some(param1,param2)*func*`
124 pub close_name: Option<SignatureUnit>,
125}
126
127/// Constructs and stores the signature of the function.
128#[derive(Debug)]
129pub struct FunctionSignature {
130 /// Storage for function signature.
131 pub unit: SignatureUnit,
132 preferences: SignaturePreferences,
133}
134
135impl FunctionSignature {
136 /// Start constructing the signature. It is written to the storage
137 /// [`SignaturePreferences::open_name`] and [`SignaturePreferences::open_delimiter`].
138 pub const fn new(preferences: SignaturePreferences) -> FunctionSignature {
139 let mut dst = [0_u8; SIGNATURE_SIZE_LIMIT];
140 let mut dst_offset = 0;
141 if let Some(ref name) = preferences.open_name {
142 crate::make_signature!(@copy(name.data, dst, name.len, dst_offset));
143 }
144 if let Some(ref delimiter) = preferences.open_delimiter {
145 crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
146 }
147 FunctionSignature {
148 unit: SignatureUnit {
149 data: dst,
150 len: dst_offset,
151 },
152 preferences,
153 }
154 }
155
156 /// Add a function parameter to the signature. It is written to the storage
157 /// `param` [`SignatureUnit`] and [`SignaturePreferences::param_delimiter`].
158 pub const fn add_param(
159 signature: FunctionSignature,
160 param: SignatureUnit,
161 ) -> FunctionSignature {
162 let mut dst = signature.unit.data;
163 let mut dst_offset = signature.unit.len;
164 crate::make_signature!(@copy(param.data, dst, param.len, dst_offset));
165 if let Some(ref delimiter) = signature.preferences.param_delimiter {
166 crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
167 }
168 FunctionSignature {
169 unit: SignatureUnit {
170 data: dst,
171 len: dst_offset,
172 },
173 ..signature
174 }
175 }
176
177 /// Complete signature construction. It is written to the storage
178 /// [`SignaturePreferences::close_delimiter`] and [`SignaturePreferences::close_name`].
179 pub const fn done(signature: FunctionSignature, owerride: bool) -> FunctionSignature {
180 let mut dst = signature.unit.data;
181 let mut dst_offset = signature.unit.len - if owerride { 1 } else { 0 };
182 if let Some(ref delimiter) = signature.preferences.close_delimiter {
183 crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
184 }
185 if let Some(ref name) = signature.preferences.close_name {
186 crate::make_signature!(@copy(name.data, dst, name.len, dst_offset));
187 }
188 FunctionSignature {
189 unit: SignatureUnit {
190 data: dst,
191 len: dst_offset,
192 },
193 ..signature
194 }
195 }
196
197 /// Represent the signature as `&str'.
198 pub fn as_str(&self) -> &str {
199 from_utf8(&self.unit.data[..self.unit.len]).expect("bad utf-8")
200 }
201}
20281
203/// Storage for the signature or its elements.82/// Storage for the signature or its elements.
204#[derive(Debug)]83#[derive(Debug)]
222 len: name_len,101 len: name_len,
223 }102 }
224 }103 }
104 /// String conversion
105 pub fn as_str(&self) -> Option<&str> {
106 core::str::from_utf8(&self.data[0..self.len]).ok()
107 }
225}108}
226109
227/// ### Macro to create signatures of types and functions.110/// ### Macro to create signatures of types and functions.
230/// ```ignore113/// ```ignore
231/// make_signature!(new fixed("uint8")); // Simple type114/// make_signature!(new fixed("uint8")); // Simple type
232/// make_signature!(new fixed("(") nameof(u8) fixed(",") nameof(u8) fixed(")")); // Composite type115/// make_signature!(new fixed("(") nameof(u8) fixed(",") nameof(u8) fixed(")")); // Composite type
233/// ```
234/// Format for creating a function of the function:
235/// ```ignore
236/// const SIG: FunctionSignature = make_signature!(
237/// new fn(SIGNATURE_PREFERENCES),
238/// (u8::SIGNATURE),
239/// (<(u8,u8)>::SIGNATURE),
240/// );
241/// ```116/// ```
242#[macro_export]117#[macro_export]
243macro_rules! make_signature {118macro_rules! make_signature {
244 (new fn($func:expr)$(,)*) => {
245 {
246 let fs = FunctionSignature::new($func);
247 let fs = FunctionSignature::done(fs, false);
248 fs
249 }
250 };
251 (new fn($func:expr), $($tt:tt,)*) => {
252 {
253 let fs = FunctionSignature::new($func);
254 let fs = make_signature!(@param; fs, $($tt),*);
255 fs
256 }
257 };
258
259 (@param; $func:expr) => {
260 FunctionSignature::done($func, true)
261 };
262 (@param; $func:expr, $param:expr) => {
263 make_signature!(@param; FunctionSignature::add_param($func, $param))
264 };
265 (@param; $func:expr, $param:expr, $($tt:tt),*) => {
266 make_signature!(@param; FunctionSignature::add_param($func, $param), $($tt),*)
267 };
268
269 (new $($tt:tt)*) => {119 (new $($tt:tt)*) => {
270 const SIGNATURE: SignatureUnit = SignatureUnit {120 ($crate::custom_signature::SignatureUnit {
271 data: {121 data: {
272 let mut out = [0u8; SIGNATURE_SIZE_LIMIT];122 let mut out = [0u8; $crate::custom_signature::SIGNATURE_SIZE_LIMIT];
273 let mut dst_offset = 0;123 let mut dst_offset = 0;
274 make_signature!(@data(out, dst_offset); $($tt)*);124 $crate::make_signature!(@data(out, dst_offset); $($tt)*);
275 out125 out
276 },126 },
277 len: {0 + make_signature!(@size; $($tt)*)},127 len: {0 + $crate::make_signature!(@size; $($tt)*)},
278 };128 })
279 };129 };
280130
281 (@size;) => {131 (@size;) => {
282 0132 0
283 };133 };
284 (@size; fixed($expr:expr) $($tt:tt)*) => {134 (@size; fixed($expr:expr) $($tt:tt)*) => {
285 $expr.len() + make_signature!(@size; $($tt)*)135 $expr.len() + $crate::make_signature!(@size; $($tt)*)
286 };136 };
287 (@size; nameof($expr:ty) $($tt:tt)*) => {137 (@size; nameof($expr:ty) $($tt:tt)*) => {
288 <$expr>::SIGNATURE.len + make_signature!(@size; $($tt)*)138 <$expr>::SIGNATURE.len + $crate::make_signature!(@size; $($tt)*)
289 };139 };
290 (@size; shift_left($expr:expr) $($tt:tt)*) => {140 (@size; shift_left($expr:expr) $($tt:tt)*) => {
291 make_signature!(@size; $($tt)*) - $expr141 $crate::make_signature!(@size; $($tt)*) - $expr
292 };142 };
293143
294 (@data($dst:ident, $dst_offset:ident);) => {};144 (@data($dst:ident, $dst_offset:ident);) => {};
295 (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {145 (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
296 {146 {
297 let data = $expr.as_bytes();147 let data = $expr.as_bytes();
298 let data_len = data.len();148 let data_len = data.len();
299 make_signature!(@copy(data, $dst, data_len, $dst_offset));149 $crate::make_signature!(@copy(data, $dst, data_len, $dst_offset));
300 }150 }
301 make_signature!(@data($dst, $dst_offset); $($tt)*)151 $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
302 };152 };
303 (@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {153 (@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {
304 {154 {
305 make_signature!(@copy(&<$expr>::SIGNATURE.data, $dst, <$expr>::SIGNATURE.len, $dst_offset));155 $crate::make_signature!(@copy(&<$expr>::SIGNATURE.data, $dst, <$expr>::SIGNATURE.len, $dst_offset));
306 }156 }
307 make_signature!(@data($dst, $dst_offset); $($tt)*)157 $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
308 };158 };
309 (@data($dst:ident, $dst_offset:ident); shift_left($expr:expr) $($tt:tt)*) => {159 (@data($dst:ident, $dst_offset:ident); shift_left($expr:expr) $($tt:tt)*) => {
310 $dst_offset -= $expr;160 $dst_offset -= $expr;
311 make_signature!(@data($dst, $dst_offset); $($tt)*)161 $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
312 };162 };
313163
314 (@copy($src:expr, $dst:expr, $src_len:expr, $dst_offset:ident)) => {164 (@copy($src:expr, $dst:expr, $src_len:expr, $dst_offset:ident)) => {
328mod test {178mod test {
329 use core::str::from_utf8;179 use core::str::from_utf8;
330180
331 use super::{SIGNATURE_SIZE_LIMIT, SignatureUnit, FunctionSignature, SignaturePreferences};181 use super::{SIGNATURE_SIZE_LIMIT, SignatureUnit};
332182
333 trait Name {183 trait Name {
334 const SIGNATURE: SignatureUnit;184 const SIGNATURE: SignatureUnit;
339 }189 }
340190
341 impl Name for u8 {191 impl Name for u8 {
342 make_signature!(new fixed("uint8"));192 const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint8"));
343 }193 }
344 impl Name for u32 {194 impl Name for u32 {
345 make_signature!(new fixed("uint32"));195 const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint32"));
346 }196 }
347 impl<T: Name> Name for Vec<T> {197 impl<T: Name> Name for Vec<T> {
348 make_signature!(new nameof(T) fixed("[]"));198 const SIGNATURE: SignatureUnit = make_signature!(new nameof(T) fixed("[]"));
349 }199 }
350 impl<A: Name, B: Name> Name for (A, B) {200 impl<A: Name, B: Name> Name for (A, B) {
201 const SIGNATURE: SignatureUnit =
351 make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));202 make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
352 }203 }
353 impl<A: Name> Name for (A,) {204 impl<A: Name> Name for (A,) {
205 const SIGNATURE: SignatureUnit =
354 make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));206 make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));
355 }207 }
356208
362 };214 };
363 }215 }
364
365 const SIGNATURE_PREFERENCES: SignaturePreferences = SignaturePreferences {
366 open_name: Some(SignatureUnit::new("some_funk")),
367 open_delimiter: Some(SignatureUnit::new("(")),
368 param_delimiter: Some(SignatureUnit::new(",")),
369 close_delimiter: Some(SignatureUnit::new(")")),
370 close_name: None,
371 };
372216
373 #[test]217 #[test]
374 fn simple() {218 fn simple() {
423 assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));267 assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));
424 }268 }
425
426 #[test]
427 fn make_func_without_args() {
428 const SIG: FunctionSignature = make_signature!(
429 new fn(SIGNATURE_PREFERENCES)
430 );
431 let name = SIG.as_str();
432 similar_asserts::assert_eq!(name, "some_funk()");
433 }
434
435 #[test]
436 fn make_func_with_1_args() {
437 const SIG: FunctionSignature = make_signature!(
438 new fn(SIGNATURE_PREFERENCES),
439 (<u8>::SIGNATURE),
440 );
441 let name = SIG.as_str();
442 similar_asserts::assert_eq!(name, "some_funk(uint8)");
443 }
444
445 #[test]
446 fn make_func_with_2_args() {
447 const SIG: FunctionSignature = make_signature!(
448 new fn(SIGNATURE_PREFERENCES),
449 (u8::SIGNATURE),
450 (<Vec<u32>>::SIGNATURE),
451 );
452 let name = SIG.as_str();
453 similar_asserts::assert_eq!(name, "some_funk(uint8,uint32[])");
454 }
455
456 #[test]
457 fn make_func_with_3_args() {
458 const SIG: FunctionSignature = make_signature!(
459 new fn(SIGNATURE_PREFERENCES),
460 (<u8>::SIGNATURE),
461 (<u32>::SIGNATURE),
462 (<Vec<u32>>::SIGNATURE),
463 );
464 let name = SIG.as_str();
465 similar_asserts::assert_eq!(name, "some_funk(uint8,uint32,uint32[])");
466 }
467
468 #[test]
469 fn make_slice_from_signature() {
470 const SIG: FunctionSignature = make_signature!(
471 new fn(SIGNATURE_PREFERENCES),
472 (<u8>::SIGNATURE),
473 (<u32>::SIGNATURE),
474 (<Vec<u32>>::SIGNATURE),
475 );
476 const NAME: [u8; SIG.unit.len] = {
477 let mut name: [u8; SIG.unit.len] = [0; SIG.unit.len];
478 let mut i = 0;
479 while i < SIG.unit.len {
480 name[i] = SIG.unit.data[i];
481 i += 1;
482 }
483 name
484 };
485 similar_asserts::assert_eq!(&NAME, b"some_funk(uint8,uint32,uint32[])");
486 }
487269
488 #[test]270 #[test]
489 fn shift() {271 fn shift() {
modifiedcrates/evm-coder/src/lib.rsdiffbeforeafterboth
122 use primitive_types::{U256, H160, H256};122 use primitive_types::{U256, H160, H256};
123 use core::str::from_utf8;123 use core::str::from_utf8;
124124
125 use crate::custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT};125 use crate::custom_signature::SignatureUnit;
126126
127 pub trait Signature {127 pub trait Signature {
128 const SIGNATURE: SignatureUnit;128 const SIGNATURE: SignatureUnit;
133 }133 }
134134
135 impl Signature for bool {135 impl Signature for bool {
136 make_signature!(new fixed("bool"));136 const SIGNATURE: SignatureUnit = make_signature!(new fixed("bool"));
137 }137 }
138138
139 macro_rules! define_simple_type {139 macro_rules! define_simple_type {
140 (type $ident:ident = $ty:ty) => {140 (type $ident:ident = $ty:ty) => {
141 pub type $ident = $ty;141 pub type $ident = $ty;
142 impl Signature for $ty {142 impl Signature for $ty {
143 make_signature!(new fixed(stringify!($ident)));143 const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ident)));
144 }144 }
145 };145 };
146 }146 }
165 #[derive(Default, Debug)]165 #[derive(Default, Debug)]
166 pub struct bytes(pub Vec<u8>);166 pub struct bytes(pub Vec<u8>);
167 impl Signature for bytes {167 impl Signature for bytes {
168 make_signature!(new fixed("bytes"));168 const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));
169 }169 }
170170
171 /// Solidity doesn't have `void` type, however we have special implementation171 /// Solidity doesn't have `void` type, however we have special implementation
259 }259 }
260260
261 impl Signature for EthCrossAccount {261 impl Signature for EthCrossAccount {
262 make_signature!(new fixed("(address,uint256)"));262 const SIGNATURE: SignatureUnit = make_signature!(new fixed("(address,uint256)"));
263 }263 }
264264
265 /// Convert `CrossAccountId` to `uint256`.265 /// Convert `CrossAccountId` to `uint256`.
modifiedcrates/evm-coder/src/solidity.rsdiffbeforeafterboth
32 cmp::Reverse,32 cmp::Reverse,
33};33};
34use impl_trait_for_tuples::impl_for_tuples;34use impl_trait_for_tuples::impl_for_tuples;
35use crate::{types::*, custom_signature::FunctionSignature};35use crate::{types::*, custom_signature::SignatureUnit};
3636
37#[derive(Default)]37#[derive(Default)]
38pub struct TypeCollector {38pub struct TypeCollector {
486 pub docs: &'static [&'static str],486 pub docs: &'static [&'static str],
487 pub selector: u32,487 pub selector: u32,
488 pub hide: bool,488 pub hide: bool,
489 pub custom_signature: FunctionSignature,489 pub custom_signature: SignatureUnit,
490 pub name: &'static str,490 pub name: &'static str,
491 pub args: A,491 pub args: A,
492 pub result: R,492 pub result: R,
512 writeln!(512 writeln!(
513 writer,513 writer,
514 "\t{hide_comment}/// or in textual repr: {}",514 "\t{hide_comment}/// or in textual repr: {}",
515 self.custom_signature.as_str()515 self.custom_signature.as_str().expect("bad utf-8")
516 )?;516 )?;
517 write!(writer, "\t{hide_comment}function {}(", self.name)?;517 write!(writer, "\t{hide_comment}function {}(", self.name)?;
518 self.args.solidity_name(writer, tc)?;518 self.args.solidity_name(writer, tc)?;
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
21 types::*,21 types::*,
22 execution::{Result, Error},22 execution::{Result, Error},
23 weight,23 weight,
24 custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
25 make_signature,
26};24};
27pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};25pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};
28use pallet_evm_coder_substrate::dispatch_to_evm;26use pallet_evm_coder_substrate::dispatch_to_evm;
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
24 generate_stubgen, solidity_interface,
25 types::*,
26 ToLog,
27 custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
28 make_signature,
29};23};
30use pallet_evm::{24use pallet_evm::{
31 ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,25 ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
24 execution::*,
25 generate_stubgen, solidity_interface,
26 types::*,
27 weight,
28 custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
29 make_signature,
30};
31use up_data_structs::CollectionMode;23use up_data_structs::CollectionMode;
32use pallet_common::erc::{CommonEvmHandler, PrecompileResult};24use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
29 execution::*,
30 generate_stubgen, solidity, solidity_interface,
31 types::*,
32 weight,
33 custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
34 make_signature,
35};
36use frame_support::BoundedVec;28use frame_support::BoundedVec;
37use up_data_structs::{29use up_data_structs::{
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
30 execution::*,
31 generate_stubgen, solidity, solidity_interface,
32 types::*,
33 weight,
34 custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
35 make_signature,
36};
37use frame_support::{BoundedBTreeMap, BoundedVec};29use frame_support::{BoundedBTreeMap, BoundedVec};
38use pallet_common::{30use pallet_common::{
modifiedpallets/refungible/src/erc_token.rsdiffbeforeafterboth
34 execution::*,
35 generate_stubgen, solidity_interface,
36 types::*,
37 weight,
38 custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
39 make_signature,
40};
41use pallet_common::{33use pallet_common::{
42 CommonWeightInfo,34 CommonWeightInfo,
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
22 execution::*,
23 generate_stubgen, solidity, solidity_interface,
24 types::*,
25 custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
26 make_signature, weight,
27};
28use frame_support::traits::Get;22use frame_support::traits::Get;
29use crate::Pallet;23use crate::Pallet;