difftreelog
refactor abi module
in: master
17 files changed
crates/evm-coder/procedural/src/solidity_interface.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#![allow(dead_code)]1819// NOTE: In order to understand this Rust macro better, first read this chapter20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html2223use proc_macro2::TokenStream;24use quote::{quote, format_ident};25use inflector::cases;26use syn::{27 Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,28 PatType, ReturnType, Type,29 spanned::Spanned,30 parse::{Parse, ParseStream},31 parenthesized, Token, LitInt, LitStr,32};3334use crate::{35 parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment, parse_result_ok,36 pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,37 snake_ident_to_screaming,38};3940struct Is {41 name: Ident,42 pascal_call_name: Ident,43 snake_call_name: Ident,44 via: Option<(Type, Ident)>,45 condition: Option<Expr>,46}47impl Is {48 fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {49 let name = &self.name;50 let pascal_call_name = &self.pascal_call_name;51 quote! {52 #name(#pascal_call_name #gen_ref)53 }54 }5556 fn expand_interface_id(&self) -> proc_macro2::TokenStream {57 let pascal_call_name = &self.pascal_call_name;58 quote! {59 interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());60 }61 }6263 fn expand_supports_interface(64 &self,65 generics: &proc_macro2::TokenStream,66 ) -> proc_macro2::TokenStream {67 let pascal_call_name = &self.pascal_call_name;68 let condition = self.condition.as_ref().map(|condition| {69 quote! {70 (#condition) &&71 }72 });73 quote! {74 #condition <#pascal_call_name #generics>::supports_interface(this, interface_id)75 }76 }7778 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {79 let name = &self.name;80 quote! {81 Self::#name(call) => call.weight()82 }83 }8485 fn expand_variant_call(86 &self,87 call_name: &proc_macro2::Ident,88 generics: &proc_macro2::TokenStream,89 ) -> proc_macro2::TokenStream {90 let name = &self.name;91 let pascal_call_name = &self.pascal_call_name;92 let via_typ = self93 .via94 .as_ref()95 .map(|(t, _)| quote! {#t})96 .unwrap_or_else(|| quote! {Self});97 let via_map = self98 .via99 .as_ref()100 .map(|(_, i)| quote! {.#i()})101 .unwrap_or_default();102 let condition = self.condition.as_ref().map(|condition| {103 quote! {104 if ({let this = &self; (#condition)})105 }106 });107 quote! {108 #call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {109 call,110 caller: c.caller,111 value: c.value,112 })113 }114 }115116 fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {117 let name = &self.name;118 let pascal_call_name = &self.pascal_call_name;119 quote! {120 if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {121 return Ok(Some(Self::#name(parsed_call)))122 }123 }124 }125126 fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {127 let pascal_call_name = &self.pascal_call_name;128 quote! {129 <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);130 }131 }132133 fn expand_event_generator(&self) -> proc_macro2::TokenStream {134 let name = &self.name;135 quote! {136 #name::generate_solidity_interface(tc, is_impl);137 }138 }139}140141#[derive(Default)]142struct IsList(Vec<Is>);143impl Parse for IsList {144 fn parse(input: ParseStream) -> syn::Result<Self> {145 let mut out = vec![];146 loop {147 if input.is_empty() {148 break;149 }150 let name = input.parse::<Ident>()?;151 let lookahead = input.lookahead1();152153 let mut condition: Option<Expr> = None;154 let mut via: Option<(Type, Ident)> = None;155156 if lookahead.peek(syn::token::Paren) {157 let contents;158 parenthesized!(contents in input);159 let input = contents;160161 while !input.is_empty() {162 let lookahead = input.lookahead1();163 if lookahead.peek(Token![if]) {164 input.parse::<Token![if]>()?;165 let contents;166 parenthesized!(contents in input);167 let contents = contents.parse::<Expr>()?;168169 if condition.replace(contents).is_some() {170 return Err(syn::Error::new(input.span(), "condition is already set"));171 }172 } else if lookahead.peek(kw::via) {173 input.parse::<kw::via>()?;174 let contents;175 parenthesized!(contents in input);176177 let method = contents.parse::<Ident>()?;178 contents.parse::<kw::returns>()?;179 let ty = contents.parse::<Type>()?;180181 if via.replace((ty, method)).is_some() {182 return Err(syn::Error::new(input.span(), "via is already set"));183 }184 } else {185 return Err(lookahead.error());186 }187188 if input.peek(Token![,]) {189 input.parse::<Token![,]>()?;190 } else if !input.is_empty() {191 return Err(syn::Error::new(input.span(), "expected end"));192 }193 }194 } else if lookahead.peek(Token![,]) || input.is_empty() {195 // Pass196 } else {197 return Err(lookahead.error());198 };199 out.push(Is {200 pascal_call_name: pascal_ident_to_call(&name),201 snake_call_name: pascal_ident_to_snake_call(&name),202 name,203 via,204 condition,205 });206 if input.peek(Token![,]) {207 input.parse::<Token![,]>()?;208 continue;209 } else {210 break;211 }212 }213 Ok(Self(out))214 }215}216217pub struct InterfaceInfo {218 name: Ident,219 is: IsList,220 inline_is: IsList,221 events: IsList,222 expect_selector: Option<u32>,223}224impl Parse for InterfaceInfo {225 fn parse(input: ParseStream) -> syn::Result<Self> {226 let mut name = None;227 let mut is = None;228 let mut inline_is = None;229 let mut events = None;230 let mut expect_selector = None;231 // TODO: create proc-macro to optimize proc-macro boilerplate? :D232 loop {233 let lookahead = input.lookahead1();234 if lookahead.peek(kw::name) {235 let k = input.parse::<kw::name>()?;236 input.parse::<Token![=]>()?;237 if name.replace(input.parse::<Ident>()?).is_some() {238 return Err(syn::Error::new(k.span(), "name is already set"));239 }240 } else if lookahead.peek(kw::is) {241 let k = input.parse::<kw::is>()?;242 let contents;243 parenthesized!(contents in input);244 if is.replace(contents.parse::<IsList>()?).is_some() {245 return Err(syn::Error::new(k.span(), "is is already set"));246 }247 } else if lookahead.peek(kw::inline_is) {248 let k = input.parse::<kw::inline_is>()?;249 let contents;250 parenthesized!(contents in input);251 if inline_is.replace(contents.parse::<IsList>()?).is_some() {252 return Err(syn::Error::new(k.span(), "inline_is is already set"));253 }254 } else if lookahead.peek(kw::events) {255 let k = input.parse::<kw::events>()?;256 let contents;257 parenthesized!(contents in input);258 if events.replace(contents.parse::<IsList>()?).is_some() {259 return Err(syn::Error::new(k.span(), "events is already set"));260 }261 } else if lookahead.peek(kw::expect_selector) {262 let k = input.parse::<kw::expect_selector>()?;263 input.parse::<Token![=]>()?;264 let value = input.parse::<LitInt>()?;265 if expect_selector266 .replace(value.base10_parse::<u32>()?)267 .is_some()268 {269 return Err(syn::Error::new(k.span(), "expect_selector is already set"));270 }271 } else if input.is_empty() {272 break;273 } else {274 return Err(lookahead.error());275 }276 if input.peek(Token![,]) {277 input.parse::<Token![,]>()?;278 } else {279 break;280 }281 }282 Ok(Self {283 name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,284 is: is.unwrap_or_default(),285 inline_is: inline_is.unwrap_or_default(),286 events: events.unwrap_or_default(),287 expect_selector,288 })289 }290}291292struct MethodInfo {293 rename_selector: Option<String>,294 hide: bool,295}296impl Parse for MethodInfo {297 fn parse(input: ParseStream) -> syn::Result<Self> {298 let mut rename_selector = None;299 let mut hide = false;300 while !input.is_empty() {301 let lookahead = input.lookahead1();302 if lookahead.peek(kw::rename_selector) {303 let k = input.parse::<kw::rename_selector>()?;304 input.parse::<Token![=]>()?;305 if rename_selector306 .replace(input.parse::<LitStr>()?.value())307 .is_some()308 {309 return Err(syn::Error::new(k.span(), "rename_selector is already set"));310 }311 } else if lookahead.peek(kw::hide) {312 input.parse::<kw::hide>()?;313 hide = true;314 } else {315 return Err(lookahead.error());316 }317318 if input.peek(Token![,]) {319 input.parse::<Token![,]>()?;320 } else if !input.is_empty() {321 return Err(syn::Error::new(input.span(), "expected end"));322 }323 }324 Ok(Self {325 rename_selector,326 hide,327 })328 }329}330331trait AbiType {332 fn plain(&self) -> syn::Result<&Ident>;333 fn is_value(&self) -> bool;334 fn is_caller(&self) -> bool;335 fn is_special(&self) -> bool;336}337338impl AbiType for Type {339 fn plain(&self) -> syn::Result<&Ident> {340 let path = parse_path(self)?;341 let segment = parse_path_segment(path)?;342 if !segment.arguments.is_empty() {343 return Err(syn::Error::new(self.span(), "Not plain type"));344 }345 Ok(&segment.ident)346 }347348 fn is_value(&self) -> bool {349 if let Ok(ident) = self.plain() {350 return ident == "value";351 }352 false353 }354355 fn is_caller(&self) -> bool {356 if let Ok(ident) = self.plain() {357 return ident == "caller";358 }359 false360 }361362 fn is_special(&self) -> bool {363 self.is_caller() || self.is_value()364 }365}366367#[derive(Debug)]368struct MethodArg {369 name: Ident,370 camel_name: String,371 ty: Type,372}373impl MethodArg {374 fn try_from(value: &PatType) -> syn::Result<Self> {375 let name = parse_ident_from_pat(&value.pat)?.clone();376 Ok(Self {377 camel_name: cases::camelcase::to_camel_case(&name.to_string()),378 name,379 ty: value.ty.as_ref().clone(),380 })381 }382 fn is_value(&self) -> bool {383 self.ty.is_value()384 }385 fn is_caller(&self) -> bool {386 self.ty.is_caller()387 }388 fn is_special(&self) -> bool {389 self.ty.is_special()390 }391392 fn expand_call_def(&self) -> proc_macro2::TokenStream {393 assert!(!self.is_special());394 let name = &self.name;395 let ty = &self.ty;396397 quote! {398 #name: #ty399 }400 }401402 fn expand_parse(&self) -> proc_macro2::TokenStream {403 assert!(!self.is_special());404 let name = &self.name;405 let ty = &self.ty;406 quote! {407 #name: <#ty>::abi_read(reader)?408 }409 }410411 fn expand_call_arg(&self) -> proc_macro2::TokenStream {412 if self.is_value() {413 quote! {414 c.value.clone()415 }416 } else if self.is_caller() {417 quote! {418 c.caller.clone()419 }420 } else {421 let name = &self.name;422 quote! {423 #name424 }425 }426 }427428 fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {429 let camel_name = &self.camel_name.to_string();430 let ty = &self.ty;431 quote! {432 <NamedArgument<#ty>>::new(#camel_name)433 }434 }435}436437#[derive(PartialEq)]438enum Mutability {439 Mutable,440 View,441 Pure,442}443444/// Group all keywords for this macro. Usage example:445/// #[solidity_interface(name = "B", inline_is(A))]446mod kw {447 syn::custom_keyword!(weight);448449 syn::custom_keyword!(via);450 syn::custom_keyword!(returns);451 syn::custom_keyword!(name);452 syn::custom_keyword!(is);453 syn::custom_keyword!(inline_is);454 syn::custom_keyword!(events);455 syn::custom_keyword!(expect_selector);456457 syn::custom_keyword!(rename_selector);458 syn::custom_keyword!(hide);459}460461/// Rust methods are parsed into this structure when Solidity code is generated462struct Method {463 name: Ident,464 camel_name: String,465 pascal_name: Ident,466 screaming_name: Ident,467 hide: bool,468 args: Vec<MethodArg>,469 has_normal_args: bool,470 has_value_args: bool,471 mutability: Mutability,472 result: Type,473 weight: Option<Expr>,474 docs: Vec<String>,475}476impl Method {477 fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {478 let mut info = MethodInfo {479 rename_selector: None,480 hide: false,481 };482 let mut docs = Vec::new();483 let mut weight = None;484 for attr in &value.attrs {485 let ident = parse_ident_from_path(&attr.path, false)?;486 if ident == "solidity" {487 info = attr.parse_args::<MethodInfo>()?;488 } else if ident == "doc" {489 let args = attr.parse_meta().unwrap();490 let value = match args {491 Meta::NameValue(MetaNameValue {492 lit: Lit::Str(str), ..493 }) => str.value(),494 _ => unreachable!(),495 };496 docs.push(value);497 } else if ident == "weight" {498 weight = Some(attr.parse_args::<Expr>()?);499 }500 }501 let ident = &value.sig.ident;502 let ident_str = ident.to_string();503 if !cases::snakecase::is_snake_case(&ident_str) {504 return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));505 }506507 let mut mutability = Mutability::Pure;508509 if let Some(FnArg::Receiver(receiver)) = value510 .sig511 .inputs512 .iter()513 .find(|arg| matches!(arg, FnArg::Receiver(_)))514 {515 if receiver.reference.is_none() {516 return Err(syn::Error::new(517 receiver.span(),518 "receiver should be by ref",519 ));520 }521 if receiver.mutability.is_some() {522 mutability = Mutability::Mutable;523 } else {524 mutability = Mutability::View;525 }526 }527 let mut args = Vec::new();528 for typ in value529 .sig530 .inputs531 .iter()532 .filter(|arg| matches!(arg, FnArg::Typed(_)))533 {534 let typ = match typ {535 FnArg::Typed(typ) => typ,536 _ => unreachable!(),537 };538 args.push(MethodArg::try_from(typ)?);539 }540541 if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {542 return Err(syn::Error::new(543 args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),544 "payable function should be mutable",545 ));546 }547548 let result = match &value.sig.output {549 ReturnType::Type(_, ty) => ty,550 _ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),551 };552 let result = parse_result_ok(result)?;553554 let camel_name = info555 .rename_selector556 .unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));557 let has_normal_args = args.iter().filter(|arg| !arg.is_special()).count() != 0;558 let has_value_args = args.iter().any(|a| a.is_value());559560 Ok(Self {561 name: ident.clone(),562 camel_name,563 pascal_name: snake_ident_to_pascal(ident),564 screaming_name: snake_ident_to_screaming(ident),565 hide: info.hide,566 args,567 has_normal_args,568 has_value_args,569 mutability,570 result: result.clone(),571 weight,572 docs,573 })574 }575 fn expand_call_def(&self) -> proc_macro2::TokenStream {576 let defs = self577 .args578 .iter()579 .filter(|a| !a.is_special())580 .map(|a| a.expand_call_def());581 let pascal_name = &self.pascal_name;582 let docs = &self.docs;583584 if self.has_normal_args {585 quote! {586 #(#[doc = #docs])*587 #[allow(missing_docs)]588 #pascal_name {589 #(590 #defs,591 )*592 }593 }594 } else {595 quote! {596 #(#[doc = #docs])*597 #[allow(missing_docs)]598 #pascal_name599 }600 }601 }602603 fn expand_const(&self) -> proc_macro2::TokenStream {604 let screaming_name = &self.screaming_name;605 let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);606 let custom_signature = self.expand_custom_signature();607 quote! {608 const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;609 const #screaming_name: ::evm_coder::types::bytes4 = {610 let mut sum = ::evm_coder::sha3_const::Keccak256::new();611 let mut pos = 0;612 while pos < Self::#screaming_name_signature.len {613 sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);614 pos += 1;615 }616 let a = sum.finalize();617 [a[0], a[1], a[2], a[3]]618 };619 }620 }621622 fn expand_interface_id(&self) -> proc_macro2::TokenStream {623 let screaming_name = &self.screaming_name;624 quote! {625 interface_id ^= u32::from_be_bytes(Self::#screaming_name);626 }627 }628629 fn expand_parse(&self) -> proc_macro2::TokenStream {630 let pascal_name = &self.pascal_name;631 let screaming_name = &self.screaming_name;632 if self.has_normal_args {633 let parsers = self634 .args635 .iter()636 .filter(|a| !a.is_special())637 .map(|a| a.expand_parse());638 quote! {639 Self::#screaming_name => return Ok(Some(Self::#pascal_name {640 #(641 #parsers,642 )*643 }))644 }645 } else {646 quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }647 }648 }649650 fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {651 let pascal_name = &self.pascal_name;652 let name = &self.name;653654 let matcher = if self.has_normal_args {655 let names = self656 .args657 .iter()658 .filter(|a| !a.is_special())659 .map(|a| &a.name);660661 quote! {{662 #(663 #names,664 )*665 }}666 } else {667 quote! {}668 };669670 let receiver = match self.mutability {671 Mutability::Mutable | Mutability::View => quote! {self.},672 Mutability::Pure => quote! {Self::},673 };674 let args = self.args.iter().map(|a| a.expand_call_arg());675676 quote! {677 #call_name::#pascal_name #matcher => {678 #[allow(deprecated)]679 let result = #receiver #name(680 #(681 #args,682 )*683 )?;684 (&result).to_result()685 }686 }687 }688689 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {690 let pascal_name = &self.pascal_name;691 if let Some(weight) = &self.weight {692 let matcher = if self.has_normal_args {693 let names = self694 .args695 .iter()696 .filter(|a| !a.is_special())697 .map(|a| &a.name);698699 quote! {{700 #(701 #names,702 )*703 }}704 } else {705 quote! {}706 };707 quote! {708 Self::#pascal_name #matcher => (#weight).into()709 }710 } else {711 let matcher = if self.has_normal_args {712 quote! {{..}}713 } else {714 quote! {}715 };716 quote! {717 Self::#pascal_name #matcher => ().into()718 }719 }720 }721722 fn expand_custom_signature(&self) -> proc_macro2::TokenStream {723 let mut args = TokenStream::new();724725 let mut has_params = false;726 for arg in self.args.iter().filter(|a| !a.is_special()) {727 has_params = true;728 let ty = &arg.ty;729 args.extend(quote! {nameof(<#ty>::SIGNATURE)});730 args.extend(quote! {fixed(",")})731 }732733 // Remove trailing comma734 if has_params {735 args.extend(quote! {shift_left(1)})736 }737738 let func_name = self.camel_name.clone();739 quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }740 }741742 fn expand_solidity_function(&self) -> proc_macro2::TokenStream {743 let camel_name = &self.camel_name;744 let mutability = match self.mutability {745 Mutability::Mutable => quote! {SolidityMutability::Mutable},746 Mutability::View => quote! { SolidityMutability::View },747 Mutability::Pure => quote! {SolidityMutability::Pure},748 };749 let result = &self.result;750751 let args = self752 .args753 .iter()754 .filter(|a| !a.is_special())755 .map(MethodArg::expand_solidity_argument);756 let docs = &self.docs;757 let screaming_name = &self.screaming_name;758 let hide = self.hide;759 let custom_signature = self.expand_custom_signature();760 let is_payable = self.has_value_args;761762 quote! {763 SolidityFunction {764 docs: &[#(#docs),*],765 hide: #hide,766 selector: u32::from_be_bytes(Self::#screaming_name),767 custom_signature: #custom_signature,768 name: #camel_name,769 mutability: #mutability,770 is_payable: #is_payable,771 args: (772 #(773 #args,774 )*775 ),776 result: <UnnamedArgument<#result>>::default(),777 }778 }779 }780}781782fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {783 if gen.params.is_empty() {784 return quote! {};785 }786 let params = gen.params.iter().map(|p| match p {787 syn::GenericParam::Type(id) => {788 let v = &id.ident;789 quote! {#v}790 }791 syn::GenericParam::Lifetime(lt) => {792 let v = <.lifetime;793 quote! {#v}794 }795 syn::GenericParam::Const(c) => {796 let i = &c.ident;797 quote! {#i}798 }799 });800 quote! { #(#params),* }801}802fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {803 if gen.params.is_empty() {804 return quote! {};805 }806 let list = generics_list(gen);807 quote! { <#list> }808}809fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {810 let list = generics_list(gen);811 if gen.params.len() == 1 {812 quote! {#list}813 } else {814 quote! { (#list) }815 }816}817818pub struct SolidityInterface {819 generics: Generics,820 name: Box<syn::Type>,821 info: InterfaceInfo,822 methods: Vec<Method>,823 docs: Vec<String>,824}825impl SolidityInterface {826 pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {827 let mut methods = Vec::new();828829 for item in &value.items {830 if let ImplItem::Method(method) = item {831 methods.push(Method::try_from(method)?)832 }833 }834 let mut docs = vec![];835 for attr in &value.attrs {836 let ident = parse_ident_from_path(&attr.path, false)?;837 if ident == "doc" {838 let args = attr.parse_meta().unwrap();839 let value = match args {840 Meta::NameValue(MetaNameValue {841 lit: Lit::Str(str), ..842 }) => str.value(),843 _ => unreachable!(),844 };845 docs.push(value);846 }847 }848 Ok(Self {849 generics: value.generics.clone(),850 name: value.self_ty.clone(),851 info,852 methods,853 docs,854 })855 }856 pub fn expand(self) -> proc_macro2::TokenStream {857 let name = self.name;858859 let solidity_name = self.info.name.to_string();860 let call_name = pascal_ident_to_call(&self.info.name);861 let generics = self.generics;862 let gen_ref = generics_reference(&generics);863 let gen_data = generics_data(&generics);864 let gen_where = &generics.where_clause;865866 let call_sub = self867 .info868 .inline_is869 .0870 .iter()871 .chain(self.info.is.0.iter())872 .map(|c| Is::expand_call_def(c, &gen_ref));873 let call_parse = self874 .info875 .inline_is876 .0877 .iter()878 .chain(self.info.is.0.iter())879 .map(|is| Is::expand_parse(is, &gen_ref));880 let call_variants = self881 .info882 .inline_is883 .0884 .iter()885 .chain(self.info.is.0.iter())886 .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));887 let weight_variants = self888 .info889 .inline_is890 .0891 .iter()892 .chain(self.info.is.0.iter())893 .map(Is::expand_variant_weight);894895 let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);896 let supports_interface = self897 .info898 .is899 .0900 .iter()901 .map(|is| Is::expand_supports_interface(is, &gen_ref));902903 let calls = self.methods.iter().map(Method::expand_call_def);904 let consts = self.methods.iter().map(Method::expand_const);905 let interface_id = self.methods.iter().map(Method::expand_interface_id);906 let parsers = self.methods.iter().map(Method::expand_parse);907 let call_variants_this = self908 .methods909 .iter()910 .map(|m| Method::expand_variant_call(m, &call_name));911 let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);912 let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);913914 // TODO: Inline inline_is915 let solidity_is = self916 .info917 .is918 .0919 .iter()920 .chain(self.info.inline_is.0.iter())921 .map(|is| is.name.to_string());922 let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());923 let solidity_generators = self924 .info925 .is926 .0927 .iter()928 .chain(self.info.inline_is.0.iter())929 .map(|is| Is::expand_generator(is, &gen_ref));930 let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);931 let solidity_events_idents = self.info.events.0.iter().map(|is| is.name.clone());932 let docs = &self.docs;933934 quote! {935 #(936 const _: ::core::marker::PhantomData<#solidity_events_idents> = ::core::marker::PhantomData;937 )*938 #[derive(Debug)]939 #(#[doc = #docs])*940 pub enum #call_name #gen_ref {941 /// Inherited method942 ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),943 #(944 #calls,945 )*946 #(947 #call_sub,948 )*949 }950 impl #gen_ref #call_name #gen_ref {951 #(952 #consts953 )*954 /// Return this call ERC165 selector955 pub fn interface_id() -> ::evm_coder::types::bytes4 {956 let mut interface_id = 0;957 #(#interface_id)*958 #(#inline_interface_id)*959 u32::to_be_bytes(interface_id)960 }961 /// Generate solidity definitions for methods described in this interface962 #[cfg(feature = "stubgen")]963 pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {964 use evm_coder::solidity::*;965 use core::fmt::Write;966 let interface = SolidityInterface {967 docs: &[#(#docs),*],968 name: #solidity_name,969 selector: Self::interface_id(),970 is: &["Dummy", "ERC165", #(971 #solidity_is,972 )* #(973 #solidity_events_is,974 )* ],975 functions: (#(976 #solidity_functions,977 )*),978 };979980 let mut out = ::evm_coder::types::string::new();981 if #solidity_name.starts_with("Inline") {982 out.push_str("/// @dev inlined interface\n");983 }984 let _ = interface.format(is_impl, &mut out, tc);985 tc.collect(out);986 #(987 #solidity_event_generators988 )*989 #(990 #solidity_generators991 )*992 if is_impl {993 tc.collect("/// @dev common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());994 } else {995 tc.collect("/// @dev common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());996 }997 }998 }999 impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1000 fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1001 use ::evm_coder::abi::AbiRead;1002 match method_id {1003 ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1004 ::evm_coder::ERC165Call::parse(method_id, reader)?1005 .map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1006 ),1007 #(1008 #parsers,1009 )*1010 _ => {},1011 }1012 #(1013 #call_parse1014 )else*1015 return Ok(None);1016 }1017 }1018 impl #generics #call_name #gen_ref1019 #gen_where1020 {1021 /// Is this contract implements specified ERC165 selector1022 pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1023 interface_id != u32::to_be_bytes(0xffffff) && (1024 interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1025 interface_id == Self::interface_id()1026 #(1027 || #supports_interface1028 )*1029 )1030 }1031 }1032 impl #generics ::evm_coder::Weighted for #call_name #gen_ref1033 #gen_where1034 {1035 #[allow(unused_variables)]1036 fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1037 match self {1038 #(1039 #weight_variants,1040 )*1041 // TODO: It should be very cheap, but not free1042 Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1043 #(1044 #weight_variants_this,1045 )*1046 }1047 }1048 }1049 impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1050 #gen_where1051 {1052 #[allow(unreachable_code)] // In case of no inner calls1053 fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1054 use ::evm_coder::abi::AbiWrite;1055 match c.call {1056 #(1057 #call_variants,1058 )*1059 #call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1060 let mut writer = ::evm_coder::abi::AbiWriter::default();1061 writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1062 return Ok(writer.into());1063 }1064 _ => {},1065 }1066 let mut writer = ::evm_coder::abi::AbiWriter::default();1067 match c.call {1068 #(1069 #call_variants_this,1070 )*1071 _ => Err(::evm_coder::execution::Error::from("method is not available").into()),1072 }1073 }1074 }1075 }1076 }1077}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#![allow(dead_code)]1819// NOTE: In order to understand this Rust macro better, first read this chapter20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html2223use proc_macro2::TokenStream;24use quote::{quote, format_ident};25use inflector::cases;26use syn::{27 Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,28 PatType, ReturnType, Type,29 spanned::Spanned,30 parse::{Parse, ParseStream},31 parenthesized, Token, LitInt, LitStr,32};3334use crate::{35 parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment, parse_result_ok,36 pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,37 snake_ident_to_screaming,38};3940struct Is {41 name: Ident,42 pascal_call_name: Ident,43 snake_call_name: Ident,44 via: Option<(Type, Ident)>,45 condition: Option<Expr>,46}47impl Is {48 fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {49 let name = &self.name;50 let pascal_call_name = &self.pascal_call_name;51 quote! {52 #name(#pascal_call_name #gen_ref)53 }54 }5556 fn expand_interface_id(&self) -> proc_macro2::TokenStream {57 let pascal_call_name = &self.pascal_call_name;58 quote! {59 interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());60 }61 }6263 fn expand_supports_interface(64 &self,65 generics: &proc_macro2::TokenStream,66 ) -> proc_macro2::TokenStream {67 let pascal_call_name = &self.pascal_call_name;68 let condition = self.condition.as_ref().map(|condition| {69 quote! {70 (#condition) &&71 }72 });73 quote! {74 #condition <#pascal_call_name #generics>::supports_interface(this, interface_id)75 }76 }7778 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {79 let name = &self.name;80 quote! {81 Self::#name(call) => call.weight()82 }83 }8485 fn expand_variant_call(86 &self,87 call_name: &proc_macro2::Ident,88 generics: &proc_macro2::TokenStream,89 ) -> proc_macro2::TokenStream {90 let name = &self.name;91 let pascal_call_name = &self.pascal_call_name;92 let via_typ = self93 .via94 .as_ref()95 .map(|(t, _)| quote! {#t})96 .unwrap_or_else(|| quote! {Self});97 let via_map = self98 .via99 .as_ref()100 .map(|(_, i)| quote! {.#i()})101 .unwrap_or_default();102 let condition = self.condition.as_ref().map(|condition| {103 quote! {104 if ({let this = &self; (#condition)})105 }106 });107 quote! {108 #call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {109 call,110 caller: c.caller,111 value: c.value,112 })113 }114 }115116 fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {117 let name = &self.name;118 let pascal_call_name = &self.pascal_call_name;119 quote! {120 if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {121 return Ok(Some(Self::#name(parsed_call)))122 }123 }124 }125126 fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {127 let pascal_call_name = &self.pascal_call_name;128 quote! {129 <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);130 }131 }132133 fn expand_event_generator(&self) -> proc_macro2::TokenStream {134 let name = &self.name;135 quote! {136 #name::generate_solidity_interface(tc, is_impl);137 }138 }139}140141#[derive(Default)]142struct IsList(Vec<Is>);143impl Parse for IsList {144 fn parse(input: ParseStream) -> syn::Result<Self> {145 let mut out = vec![];146 loop {147 if input.is_empty() {148 break;149 }150 let name = input.parse::<Ident>()?;151 let lookahead = input.lookahead1();152153 let mut condition: Option<Expr> = None;154 let mut via: Option<(Type, Ident)> = None;155156 if lookahead.peek(syn::token::Paren) {157 let contents;158 parenthesized!(contents in input);159 let input = contents;160161 while !input.is_empty() {162 let lookahead = input.lookahead1();163 if lookahead.peek(Token![if]) {164 input.parse::<Token![if]>()?;165 let contents;166 parenthesized!(contents in input);167 let contents = contents.parse::<Expr>()?;168169 if condition.replace(contents).is_some() {170 return Err(syn::Error::new(input.span(), "condition is already set"));171 }172 } else if lookahead.peek(kw::via) {173 input.parse::<kw::via>()?;174 let contents;175 parenthesized!(contents in input);176177 let method = contents.parse::<Ident>()?;178 contents.parse::<kw::returns>()?;179 let ty = contents.parse::<Type>()?;180181 if via.replace((ty, method)).is_some() {182 return Err(syn::Error::new(input.span(), "via is already set"));183 }184 } else {185 return Err(lookahead.error());186 }187188 if input.peek(Token![,]) {189 input.parse::<Token![,]>()?;190 } else if !input.is_empty() {191 return Err(syn::Error::new(input.span(), "expected end"));192 }193 }194 } else if lookahead.peek(Token![,]) || input.is_empty() {195 // Pass196 } else {197 return Err(lookahead.error());198 };199 out.push(Is {200 pascal_call_name: pascal_ident_to_call(&name),201 snake_call_name: pascal_ident_to_snake_call(&name),202 name,203 via,204 condition,205 });206 if input.peek(Token![,]) {207 input.parse::<Token![,]>()?;208 continue;209 } else {210 break;211 }212 }213 Ok(Self(out))214 }215}216217pub struct InterfaceInfo {218 name: Ident,219 is: IsList,220 inline_is: IsList,221 events: IsList,222 expect_selector: Option<u32>,223}224impl Parse for InterfaceInfo {225 fn parse(input: ParseStream) -> syn::Result<Self> {226 let mut name = None;227 let mut is = None;228 let mut inline_is = None;229 let mut events = None;230 let mut expect_selector = None;231 // TODO: create proc-macro to optimize proc-macro boilerplate? :D232 loop {233 let lookahead = input.lookahead1();234 if lookahead.peek(kw::name) {235 let k = input.parse::<kw::name>()?;236 input.parse::<Token![=]>()?;237 if name.replace(input.parse::<Ident>()?).is_some() {238 return Err(syn::Error::new(k.span(), "name is already set"));239 }240 } else if lookahead.peek(kw::is) {241 let k = input.parse::<kw::is>()?;242 let contents;243 parenthesized!(contents in input);244 if is.replace(contents.parse::<IsList>()?).is_some() {245 return Err(syn::Error::new(k.span(), "is is already set"));246 }247 } else if lookahead.peek(kw::inline_is) {248 let k = input.parse::<kw::inline_is>()?;249 let contents;250 parenthesized!(contents in input);251 if inline_is.replace(contents.parse::<IsList>()?).is_some() {252 return Err(syn::Error::new(k.span(), "inline_is is already set"));253 }254 } else if lookahead.peek(kw::events) {255 let k = input.parse::<kw::events>()?;256 let contents;257 parenthesized!(contents in input);258 if events.replace(contents.parse::<IsList>()?).is_some() {259 return Err(syn::Error::new(k.span(), "events is already set"));260 }261 } else if lookahead.peek(kw::expect_selector) {262 let k = input.parse::<kw::expect_selector>()?;263 input.parse::<Token![=]>()?;264 let value = input.parse::<LitInt>()?;265 if expect_selector266 .replace(value.base10_parse::<u32>()?)267 .is_some()268 {269 return Err(syn::Error::new(k.span(), "expect_selector is already set"));270 }271 } else if input.is_empty() {272 break;273 } else {274 return Err(lookahead.error());275 }276 if input.peek(Token![,]) {277 input.parse::<Token![,]>()?;278 } else {279 break;280 }281 }282 Ok(Self {283 name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,284 is: is.unwrap_or_default(),285 inline_is: inline_is.unwrap_or_default(),286 events: events.unwrap_or_default(),287 expect_selector,288 })289 }290}291292struct MethodInfo {293 rename_selector: Option<String>,294 hide: bool,295}296impl Parse for MethodInfo {297 fn parse(input: ParseStream) -> syn::Result<Self> {298 let mut rename_selector = None;299 let mut hide = false;300 while !input.is_empty() {301 let lookahead = input.lookahead1();302 if lookahead.peek(kw::rename_selector) {303 let k = input.parse::<kw::rename_selector>()?;304 input.parse::<Token![=]>()?;305 if rename_selector306 .replace(input.parse::<LitStr>()?.value())307 .is_some()308 {309 return Err(syn::Error::new(k.span(), "rename_selector is already set"));310 }311 } else if lookahead.peek(kw::hide) {312 input.parse::<kw::hide>()?;313 hide = true;314 } else {315 return Err(lookahead.error());316 }317318 if input.peek(Token![,]) {319 input.parse::<Token![,]>()?;320 } else if !input.is_empty() {321 return Err(syn::Error::new(input.span(), "expected end"));322 }323 }324 Ok(Self {325 rename_selector,326 hide,327 })328 }329}330331trait AbiTypeHelper {332 fn plain(&self) -> syn::Result<&Ident>;333 fn is_value(&self) -> bool;334 fn is_caller(&self) -> bool;335 fn is_special(&self) -> bool;336}337338impl AbiTypeHelper for Type {339 fn plain(&self) -> syn::Result<&Ident> {340 let path = parse_path(self)?;341 let segment = parse_path_segment(path)?;342 if !segment.arguments.is_empty() {343 return Err(syn::Error::new(self.span(), "Not plain type"));344 }345 Ok(&segment.ident)346 }347348 fn is_value(&self) -> bool {349 if let Ok(ident) = self.plain() {350 return ident == "value";351 }352 false353 }354355 fn is_caller(&self) -> bool {356 if let Ok(ident) = self.plain() {357 return ident == "caller";358 }359 false360 }361362 fn is_special(&self) -> bool {363 self.is_caller() || self.is_value()364 }365}366367#[derive(Debug)]368struct MethodArg {369 name: Ident,370 camel_name: String,371 ty: Type,372}373impl MethodArg {374 fn try_from(value: &PatType) -> syn::Result<Self> {375 let name = parse_ident_from_pat(&value.pat)?.clone();376 Ok(Self {377 camel_name: cases::camelcase::to_camel_case(&name.to_string()),378 name,379 ty: value.ty.as_ref().clone(),380 })381 }382 fn is_value(&self) -> bool {383 self.ty.is_value()384 }385 fn is_caller(&self) -> bool {386 self.ty.is_caller()387 }388 fn is_special(&self) -> bool {389 self.ty.is_special()390 }391392 fn expand_call_def(&self) -> proc_macro2::TokenStream {393 assert!(!self.is_special());394 let name = &self.name;395 let ty = &self.ty;396397 quote! {398 #name: #ty399 }400 }401402 fn expand_parse(&self) -> proc_macro2::TokenStream {403 assert!(!self.is_special());404 let name = &self.name;405 let ty = &self.ty;406 quote! {407 #name: <#ty>::abi_read(reader)?408 }409 }410411 fn expand_call_arg(&self) -> proc_macro2::TokenStream {412 if self.is_value() {413 quote! {414 c.value.clone()415 }416 } else if self.is_caller() {417 quote! {418 c.caller.clone()419 }420 } else {421 let name = &self.name;422 quote! {423 #name424 }425 }426 }427428 fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {429 let camel_name = &self.camel_name.to_string();430 let ty = &self.ty;431 quote! {432 <NamedArgument<#ty>>::new(#camel_name)433 }434 }435}436437#[derive(PartialEq)]438enum Mutability {439 Mutable,440 View,441 Pure,442}443444/// Group all keywords for this macro. Usage example:445/// #[solidity_interface(name = "B", inline_is(A))]446mod kw {447 syn::custom_keyword!(weight);448449 syn::custom_keyword!(via);450 syn::custom_keyword!(returns);451 syn::custom_keyword!(name);452 syn::custom_keyword!(is);453 syn::custom_keyword!(inline_is);454 syn::custom_keyword!(events);455 syn::custom_keyword!(expect_selector);456457 syn::custom_keyword!(rename_selector);458 syn::custom_keyword!(hide);459}460461/// Rust methods are parsed into this structure when Solidity code is generated462struct Method {463 name: Ident,464 camel_name: String,465 pascal_name: Ident,466 screaming_name: Ident,467 hide: bool,468 args: Vec<MethodArg>,469 has_normal_args: bool,470 has_value_args: bool,471 mutability: Mutability,472 result: Type,473 weight: Option<Expr>,474 docs: Vec<String>,475}476impl Method {477 fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {478 let mut info = MethodInfo {479 rename_selector: None,480 hide: false,481 };482 let mut docs = Vec::new();483 let mut weight = None;484 for attr in &value.attrs {485 let ident = parse_ident_from_path(&attr.path, false)?;486 if ident == "solidity" {487 info = attr.parse_args::<MethodInfo>()?;488 } else if ident == "doc" {489 let args = attr.parse_meta().unwrap();490 let value = match args {491 Meta::NameValue(MetaNameValue {492 lit: Lit::Str(str), ..493 }) => str.value(),494 _ => unreachable!(),495 };496 docs.push(value);497 } else if ident == "weight" {498 weight = Some(attr.parse_args::<Expr>()?);499 }500 }501 let ident = &value.sig.ident;502 let ident_str = ident.to_string();503 if !cases::snakecase::is_snake_case(&ident_str) {504 return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));505 }506507 let mut mutability = Mutability::Pure;508509 if let Some(FnArg::Receiver(receiver)) = value510 .sig511 .inputs512 .iter()513 .find(|arg| matches!(arg, FnArg::Receiver(_)))514 {515 if receiver.reference.is_none() {516 return Err(syn::Error::new(517 receiver.span(),518 "receiver should be by ref",519 ));520 }521 if receiver.mutability.is_some() {522 mutability = Mutability::Mutable;523 } else {524 mutability = Mutability::View;525 }526 }527 let mut args = Vec::new();528 for typ in value529 .sig530 .inputs531 .iter()532 .filter(|arg| matches!(arg, FnArg::Typed(_)))533 {534 let typ = match typ {535 FnArg::Typed(typ) => typ,536 _ => unreachable!(),537 };538 args.push(MethodArg::try_from(typ)?);539 }540541 if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {542 return Err(syn::Error::new(543 args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),544 "payable function should be mutable",545 ));546 }547548 let result = match &value.sig.output {549 ReturnType::Type(_, ty) => ty,550 _ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),551 };552 let result = parse_result_ok(result)?;553554 let camel_name = info555 .rename_selector556 .unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));557 let has_normal_args = args.iter().filter(|arg| !arg.is_special()).count() != 0;558 let has_value_args = args.iter().any(|a| a.is_value());559560 Ok(Self {561 name: ident.clone(),562 camel_name,563 pascal_name: snake_ident_to_pascal(ident),564 screaming_name: snake_ident_to_screaming(ident),565 hide: info.hide,566 args,567 has_normal_args,568 has_value_args,569 mutability,570 result: result.clone(),571 weight,572 docs,573 })574 }575 fn expand_call_def(&self) -> proc_macro2::TokenStream {576 let defs = self577 .args578 .iter()579 .filter(|a| !a.is_special())580 .map(|a| a.expand_call_def());581 let pascal_name = &self.pascal_name;582 let docs = &self.docs;583584 if self.has_normal_args {585 quote! {586 #(#[doc = #docs])*587 #[allow(missing_docs)]588 #pascal_name {589 #(590 #defs,591 )*592 }593 }594 } else {595 quote! {596 #(#[doc = #docs])*597 #[allow(missing_docs)]598 #pascal_name599 }600 }601 }602603 fn expand_const(&self) -> proc_macro2::TokenStream {604 let screaming_name = &self.screaming_name;605 let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);606 let custom_signature = self.expand_custom_signature();607 quote! {608 const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;609 const #screaming_name: ::evm_coder::types::bytes4 = {610 let mut sum = ::evm_coder::sha3_const::Keccak256::new();611 let mut pos = 0;612 while pos < Self::#screaming_name_signature.len {613 sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);614 pos += 1;615 }616 let a = sum.finalize();617 [a[0], a[1], a[2], a[3]]618 };619 }620 }621622 fn expand_interface_id(&self) -> proc_macro2::TokenStream {623 let screaming_name = &self.screaming_name;624 quote! {625 interface_id ^= u32::from_be_bytes(Self::#screaming_name);626 }627 }628629 fn expand_parse(&self) -> proc_macro2::TokenStream {630 let pascal_name = &self.pascal_name;631 let screaming_name = &self.screaming_name;632 if self.has_normal_args {633 let parsers = self634 .args635 .iter()636 .filter(|a| !a.is_special())637 .map(|a| a.expand_parse());638 quote! {639 Self::#screaming_name => return Ok(Some(Self::#pascal_name {640 #(641 #parsers,642 )*643 }))644 }645 } else {646 quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }647 }648 }649650 fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {651 let pascal_name = &self.pascal_name;652 let name = &self.name;653654 let matcher = if self.has_normal_args {655 let names = self656 .args657 .iter()658 .filter(|a| !a.is_special())659 .map(|a| &a.name);660661 quote! {{662 #(663 #names,664 )*665 }}666 } else {667 quote! {}668 };669670 let receiver = match self.mutability {671 Mutability::Mutable | Mutability::View => quote! {self.},672 Mutability::Pure => quote! {Self::},673 };674 let args = self.args.iter().map(|a| a.expand_call_arg());675676 quote! {677 #call_name::#pascal_name #matcher => {678 #[allow(deprecated)]679 let result = #receiver #name(680 #(681 #args,682 )*683 )?;684 (&result).to_result()685 }686 }687 }688689 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {690 let pascal_name = &self.pascal_name;691 if let Some(weight) = &self.weight {692 let matcher = if self.has_normal_args {693 let names = self694 .args695 .iter()696 .filter(|a| !a.is_special())697 .map(|a| &a.name);698699 quote! {{700 #(701 #names,702 )*703 }}704 } else {705 quote! {}706 };707 quote! {708 Self::#pascal_name #matcher => (#weight).into()709 }710 } else {711 let matcher = if self.has_normal_args {712 quote! {{..}}713 } else {714 quote! {}715 };716 quote! {717 Self::#pascal_name #matcher => ().into()718 }719 }720 }721722 fn expand_custom_signature(&self) -> proc_macro2::TokenStream {723 let mut args = TokenStream::new();724725 let mut has_params = false;726 for arg in self.args.iter().filter(|a| !a.is_special()) {727 has_params = true;728 let ty = &arg.ty;729 args.extend(quote! {nameof(<#ty>::SIGNATURE)});730 args.extend(quote! {fixed(",")})731 }732733 // Remove trailing comma734 if has_params {735 args.extend(quote! {shift_left(1)})736 }737738 let func_name = self.camel_name.clone();739 quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }740 }741742 fn expand_solidity_function(&self) -> proc_macro2::TokenStream {743 let camel_name = &self.camel_name;744 let mutability = match self.mutability {745 Mutability::Mutable => quote! {SolidityMutability::Mutable},746 Mutability::View => quote! { SolidityMutability::View },747 Mutability::Pure => quote! {SolidityMutability::Pure},748 };749 let result = &self.result;750751 let args = self752 .args753 .iter()754 .filter(|a| !a.is_special())755 .map(MethodArg::expand_solidity_argument);756 let docs = &self.docs;757 let screaming_name = &self.screaming_name;758 let hide = self.hide;759 let custom_signature = self.expand_custom_signature();760 let is_payable = self.has_value_args;761762 quote! {763 SolidityFunction {764 docs: &[#(#docs),*],765 hide: #hide,766 selector: u32::from_be_bytes(Self::#screaming_name),767 custom_signature: #custom_signature,768 name: #camel_name,769 mutability: #mutability,770 is_payable: #is_payable,771 args: (772 #(773 #args,774 )*775 ),776 result: <UnnamedArgument<#result>>::default(),777 }778 }779 }780}781782fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {783 if gen.params.is_empty() {784 return quote! {};785 }786 let params = gen.params.iter().map(|p| match p {787 syn::GenericParam::Type(id) => {788 let v = &id.ident;789 quote! {#v}790 }791 syn::GenericParam::Lifetime(lt) => {792 let v = <.lifetime;793 quote! {#v}794 }795 syn::GenericParam::Const(c) => {796 let i = &c.ident;797 quote! {#i}798 }799 });800 quote! { #(#params),* }801}802fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {803 if gen.params.is_empty() {804 return quote! {};805 }806 let list = generics_list(gen);807 quote! { <#list> }808}809fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {810 let list = generics_list(gen);811 if gen.params.len() == 1 {812 quote! {#list}813 } else {814 quote! { (#list) }815 }816}817818pub struct SolidityInterface {819 generics: Generics,820 name: Box<syn::Type>,821 info: InterfaceInfo,822 methods: Vec<Method>,823 docs: Vec<String>,824}825impl SolidityInterface {826 pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {827 let mut methods = Vec::new();828829 for item in &value.items {830 if let ImplItem::Method(method) = item {831 methods.push(Method::try_from(method)?)832 }833 }834 let mut docs = vec![];835 for attr in &value.attrs {836 let ident = parse_ident_from_path(&attr.path, false)?;837 if ident == "doc" {838 let args = attr.parse_meta().unwrap();839 let value = match args {840 Meta::NameValue(MetaNameValue {841 lit: Lit::Str(str), ..842 }) => str.value(),843 _ => unreachable!(),844 };845 docs.push(value);846 }847 }848 Ok(Self {849 generics: value.generics.clone(),850 name: value.self_ty.clone(),851 info,852 methods,853 docs,854 })855 }856 pub fn expand(self) -> proc_macro2::TokenStream {857 let name = self.name;858859 let solidity_name = self.info.name.to_string();860 let call_name = pascal_ident_to_call(&self.info.name);861 let generics = self.generics;862 let gen_ref = generics_reference(&generics);863 let gen_data = generics_data(&generics);864 let gen_where = &generics.where_clause;865866 let call_sub = self867 .info868 .inline_is869 .0870 .iter()871 .chain(self.info.is.0.iter())872 .map(|c| Is::expand_call_def(c, &gen_ref));873 let call_parse = self874 .info875 .inline_is876 .0877 .iter()878 .chain(self.info.is.0.iter())879 .map(|is| Is::expand_parse(is, &gen_ref));880 let call_variants = self881 .info882 .inline_is883 .0884 .iter()885 .chain(self.info.is.0.iter())886 .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));887 let weight_variants = self888 .info889 .inline_is890 .0891 .iter()892 .chain(self.info.is.0.iter())893 .map(Is::expand_variant_weight);894895 let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);896 let supports_interface = self897 .info898 .is899 .0900 .iter()901 .map(|is| Is::expand_supports_interface(is, &gen_ref));902903 let calls = self.methods.iter().map(Method::expand_call_def);904 let consts = self.methods.iter().map(Method::expand_const);905 let interface_id = self.methods.iter().map(Method::expand_interface_id);906 let parsers = self.methods.iter().map(Method::expand_parse);907 let call_variants_this = self908 .methods909 .iter()910 .map(|m| Method::expand_variant_call(m, &call_name));911 let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);912 let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);913914 // TODO: Inline inline_is915 let solidity_is = self916 .info917 .is918 .0919 .iter()920 .chain(self.info.inline_is.0.iter())921 .map(|is| is.name.to_string());922 let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());923 let solidity_generators = self924 .info925 .is926 .0927 .iter()928 .chain(self.info.inline_is.0.iter())929 .map(|is| Is::expand_generator(is, &gen_ref));930 let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);931 let solidity_events_idents = self.info.events.0.iter().map(|is| is.name.clone());932 let docs = &self.docs;933934 quote! {935 #(936 const _: ::core::marker::PhantomData<#solidity_events_idents> = ::core::marker::PhantomData;937 )*938 #[derive(Debug)]939 #(#[doc = #docs])*940 pub enum #call_name #gen_ref {941 /// Inherited method942 ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),943 #(944 #calls,945 )*946 #(947 #call_sub,948 )*949 }950 impl #gen_ref #call_name #gen_ref {951 #(952 #consts953 )*954 /// Return this call ERC165 selector955 pub fn interface_id() -> ::evm_coder::types::bytes4 {956 let mut interface_id = 0;957 #(#interface_id)*958 #(#inline_interface_id)*959 u32::to_be_bytes(interface_id)960 }961 /// Generate solidity definitions for methods described in this interface962 #[cfg(feature = "stubgen")]963 pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {964 use evm_coder::solidity::*;965 use core::fmt::Write;966 let interface = SolidityInterface {967 docs: &[#(#docs),*],968 name: #solidity_name,969 selector: Self::interface_id(),970 is: &["Dummy", "ERC165", #(971 #solidity_is,972 )* #(973 #solidity_events_is,974 )* ],975 functions: (#(976 #solidity_functions,977 )*),978 };979980 let mut out = ::evm_coder::types::string::new();981 if #solidity_name.starts_with("Inline") {982 out.push_str("/// @dev inlined interface\n");983 }984 let _ = interface.format(is_impl, &mut out, tc);985 tc.collect(out);986 #(987 #solidity_event_generators988 )*989 #(990 #solidity_generators991 )*992 if is_impl {993 tc.collect("/// @dev common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());994 } else {995 tc.collect("/// @dev common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());996 }997 }998 }999 impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1000 fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1001 use ::evm_coder::abi::AbiRead;1002 match method_id {1003 ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1004 ::evm_coder::ERC165Call::parse(method_id, reader)?1005 .map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1006 ),1007 #(1008 #parsers,1009 )*1010 _ => {},1011 }1012 #(1013 #call_parse1014 )else*1015 return Ok(None);1016 }1017 }1018 impl #generics #call_name #gen_ref1019 #gen_where1020 {1021 /// Is this contract implements specified ERC165 selector1022 pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1023 interface_id != u32::to_be_bytes(0xffffff) && (1024 interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1025 interface_id == Self::interface_id()1026 #(1027 || #supports_interface1028 )*1029 )1030 }1031 }1032 impl #generics ::evm_coder::Weighted for #call_name #gen_ref1033 #gen_where1034 {1035 #[allow(unused_variables)]1036 fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1037 match self {1038 #(1039 #weight_variants,1040 )*1041 // TODO: It should be very cheap, but not free1042 Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1043 #(1044 #weight_variants_this,1045 )*1046 }1047 }1048 }1049 impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1050 #gen_where1051 {1052 #[allow(unreachable_code)] // In case of no inner calls1053 fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1054 use ::evm_coder::abi::AbiWrite;1055 match c.call {1056 #(1057 #call_variants,1058 )*1059 #call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1060 let mut writer = ::evm_coder::abi::AbiWriter::default();1061 writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1062 return Ok(writer.into());1063 }1064 _ => {},1065 }1066 let mut writer = ::evm_coder::abi::AbiWriter::default();1067 match c.call {1068 #(1069 #call_variants_this,1070 )*1071 _ => Err(::evm_coder::execution::Error::from("method is not available").into()),1072 }1073 }1074 }1075 }1076 }1077}crates/evm-coder/src/abi.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi.rs
+++ /dev/null
@@ -1,968 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-//! Implementation of EVM RLP reader/writer
-
-#![allow(dead_code)]
-
-#[cfg(not(feature = "std"))]
-use alloc::vec::Vec;
-use evm_core::ExitError;
-use primitive_types::{H160, U256};
-
-use crate::{
- execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},
- types::*,
- make_signature,
- custom_signature::{SignatureUnit},
-};
-use crate::execution::Result;
-
-const ABI_ALIGNMENT: usize = 32;
-
-trait TypeHelper {
- /// Is type dynamic sized.
- fn is_dynamic() -> bool;
-
- /// Size for type aligned to [`ABI_ALIGNMENT`].
- fn size() -> usize;
-}
-
-/// View into RLP data, which provides method to read typed items from it
-#[derive(Clone)]
-pub struct AbiReader<'i> {
- buf: &'i [u8],
- subresult_offset: usize,
- offset: usize,
-}
-impl<'i> AbiReader<'i> {
- /// Start reading RLP buffer, assuming there is no padding bytes
- pub fn new(buf: &'i [u8]) -> Self {
- Self {
- buf,
- subresult_offset: 0,
- offset: 0,
- }
- }
- /// Start reading RLP buffer, parsing first 4 bytes as selector
- pub fn new_call(buf: &'i [u8]) -> Result<(bytes4, Self)> {
- if buf.len() < 4 {
- return Err(Error::Error(ExitError::OutOfOffset));
- }
- let mut method_id = [0; 4];
- method_id.copy_from_slice(&buf[0..4]);
-
- Ok((
- method_id,
- Self {
- buf,
- subresult_offset: 4,
- offset: 4,
- },
- ))
- }
-
- fn read_pad<const S: usize>(
- buf: &[u8],
- offset: usize,
- pad_start: usize,
- pad_size: usize,
- block_start: usize,
- block_size: usize,
- ) -> Result<[u8; S]> {
- if buf.len() - offset < ABI_ALIGNMENT {
- return Err(Error::Error(ExitError::OutOfOffset));
- }
- let mut block = [0; S];
- let is_pad_zeroed = buf[pad_start..pad_size].iter().all(|&v| v == 0);
- if !is_pad_zeroed {
- return Err(Error::Error(ExitError::InvalidRange));
- }
- block.copy_from_slice(&buf[block_start..block_size]);
- Ok(block)
- }
-
- fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {
- let offset = self.offset;
- self.offset += ABI_ALIGNMENT;
- Self::read_pad(
- self.buf,
- offset,
- offset,
- offset + ABI_ALIGNMENT - S,
- offset + ABI_ALIGNMENT - S,
- offset + ABI_ALIGNMENT,
- )
- }
-
- fn read_padright<const S: usize>(&mut self) -> Result<[u8; S]> {
- let offset = self.offset;
- self.offset += ABI_ALIGNMENT;
- Self::read_pad(
- self.buf,
- offset,
- offset + S,
- offset + ABI_ALIGNMENT,
- offset,
- offset + S,
- )
- }
-
- /// Read [`H160`] at current position, then advance
- pub fn address(&mut self) -> Result<H160> {
- Ok(H160(self.read_padleft()?))
- }
-
- /// Read [`bool`] at current position, then advance
- pub fn bool(&mut self) -> Result<bool> {
- let data: [u8; 1] = self.read_padleft()?;
- match data[0] {
- 0 => Ok(false),
- 1 => Ok(true),
- _ => Err(Error::Error(ExitError::InvalidRange)),
- }
- }
-
- /// Read [`[u8; 4]`] at current position, then advance
- pub fn bytes4(&mut self) -> Result<[u8; 4]> {
- self.read_padright()
- }
-
- /// Read [`Vec<u8>`] at current position, then advance
- pub fn bytes(&mut self) -> Result<Vec<u8>> {
- let mut subresult = self.subresult(None)?;
- let length = subresult.uint32()? as usize;
- if subresult.buf.len() < subresult.offset + length {
- return Err(Error::Error(ExitError::OutOfOffset));
- }
- Ok(subresult.buf[subresult.offset..subresult.offset + length].into())
- }
-
- /// Read [`string`] at current position, then advance
- pub fn string(&mut self) -> Result<string> {
- string::from_utf8(self.bytes()?).map_err(|_| Error::Error(ExitError::InvalidRange))
- }
-
- /// Read [`u8`] at current position, then advance
- pub fn uint8(&mut self) -> Result<u8> {
- Ok(self.read_padleft::<1>()?[0])
- }
-
- /// Read [`u32`] at current position, then advance
- pub fn uint32(&mut self) -> Result<u32> {
- Ok(u32::from_be_bytes(self.read_padleft()?))
- }
-
- /// Read [`u128`] at current position, then advance
- pub fn uint128(&mut self) -> Result<u128> {
- Ok(u128::from_be_bytes(self.read_padleft()?))
- }
-
- /// Read [`U256`] at current position, then advance
- pub fn uint256(&mut self) -> Result<U256> {
- let buf: [u8; 32] = self.read_padleft()?;
- Ok(U256::from_big_endian(&buf))
- }
-
- /// Read [`u64`] at current position, then advance
- pub fn uint64(&mut self) -> Result<u64> {
- Ok(u64::from_be_bytes(self.read_padleft()?))
- }
-
- /// Read [`usize`] at current position, then advance
- #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]
- pub fn read_usize(&mut self) -> Result<usize> {
- Ok(usize::from_be_bytes(self.read_padleft()?))
- }
-
- /// Slice recursive buffer, advance one word for buffer offset
- /// If `size` is [`None`] then [`Self::offset`] and [`Self::subresult_offset`] evals from [`Self::buf`].
- fn subresult(&mut self, size: Option<usize>) -> Result<AbiReader<'i>> {
- let subresult_offset = self.subresult_offset;
- let offset = if let Some(size) = size {
- self.offset += size;
- self.subresult_offset += size;
- 0
- } else {
- self.uint32()? as usize
- };
-
- if offset + self.subresult_offset > self.buf.len() {
- return Err(Error::Error(ExitError::InvalidRange));
- }
-
- let new_offset = offset + subresult_offset;
- Ok(AbiReader {
- buf: self.buf,
- subresult_offset: new_offset,
- offset: new_offset,
- })
- }
-
- /// Is this parser reached end of buffer?
- pub fn is_finished(&self) -> bool {
- self.buf.len() == self.offset
- }
-}
-
-/// Writer for RLP encoded data
-#[derive(Default)]
-pub struct AbiWriter {
- static_part: Vec<u8>,
- dynamic_part: Vec<(usize, AbiWriter)>,
- had_call: bool,
- is_dynamic: bool,
-}
-impl AbiWriter {
- /// Initialize internal buffers for output data, assuming no padding required
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Initialize internal buffers with data size
- pub fn new_dynamic(is_dynamic: bool) -> Self {
- Self {
- is_dynamic,
- ..Default::default()
- }
- }
- /// Initialize internal buffers, inserting method selector at beginning
- pub fn new_call(method_id: u32) -> Self {
- let mut val = Self::new();
- val.static_part.extend(&method_id.to_be_bytes());
- val.had_call = true;
- val
- }
-
- fn write_padleft(&mut self, block: &[u8]) {
- assert!(block.len() <= ABI_ALIGNMENT);
- self.static_part
- .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);
- self.static_part.extend(block);
- }
-
- fn write_padright(&mut self, block: &[u8]) {
- assert!(block.len() <= ABI_ALIGNMENT);
- self.static_part.extend(block);
- self.static_part
- .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);
- }
-
- /// Write [`H160`] to end of buffer
- pub fn address(&mut self, address: &H160) {
- self.write_padleft(&address.0)
- }
-
- /// Write [`bool`] to end of buffer
- pub fn bool(&mut self, value: &bool) {
- self.write_padleft(&[if *value { 1 } else { 0 }])
- }
-
- /// Write [`u8`] to end of buffer
- pub fn uint8(&mut self, value: &u8) {
- self.write_padleft(&[*value])
- }
-
- /// Write [`u32`] to end of buffer
- pub fn uint32(&mut self, value: &u32) {
- self.write_padleft(&u32::to_be_bytes(*value))
- }
-
- /// Write [`u128`] to end of buffer
- pub fn uint128(&mut self, value: &u128) {
- self.write_padleft(&u128::to_be_bytes(*value))
- }
-
- /// Write [`U256`] to end of buffer
- pub fn uint256(&mut self, value: &U256) {
- let mut out = [0; 32];
- value.to_big_endian(&mut out);
- self.write_padleft(&out)
- }
-
- /// Write [`usize`] to end of buffer
- #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]
- pub fn write_usize(&mut self, value: &usize) {
- self.write_padleft(&usize::to_be_bytes(*value))
- }
-
- /// Append recursive data, writing pending offset at end of buffer
- pub fn write_subresult(&mut self, result: Self) {
- self.dynamic_part.push((self.static_part.len(), result));
- // Empty block, to be filled later
- self.write_padleft(&[]);
- }
-
- fn memory(&mut self, value: &[u8]) {
- let mut sub = Self::new();
- sub.uint32(&(value.len() as u32));
- for chunk in value.chunks(ABI_ALIGNMENT) {
- sub.write_padright(chunk);
- }
- self.write_subresult(sub);
- }
-
- /// Append recursive [`str`] at end of buffer
- pub fn string(&mut self, value: &str) {
- self.memory(value.as_bytes())
- }
-
- /// Append recursive [`[u8]`] at end of buffer
- pub fn bytes(&mut self, value: &[u8]) {
- self.memory(value)
- }
-
- /// Finish writer, concatenating all internal buffers
- pub fn finish(mut self) -> Vec<u8> {
- for (static_offset, part) in self.dynamic_part {
- let part_offset = self.static_part.len()
- - if self.had_call { 4 } else { 0 }
- - if self.is_dynamic { ABI_ALIGNMENT } else { 0 };
-
- let encoded_dynamic_offset = usize::to_be_bytes(part_offset);
- let start = static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len();
- let stop = static_offset + ABI_ALIGNMENT;
- self.static_part[start..stop].copy_from_slice(&encoded_dynamic_offset);
- self.static_part.extend(part.finish())
- }
- self.static_part
- }
-}
-
-/// [`AbiReader`] implements reading of many types.
-pub trait AbiRead {
- /// Read item from current position, advanding decoder
- fn abi_read(reader: &mut AbiReader) -> Result<Self>
- where
- Self: Sized;
-}
-
-macro_rules! impl_abi_readable {
- ($ty:ty, $method:ident, $dynamic:literal) => {
- impl sealed::CanBePlacedInVec for $ty {}
-
- impl TypeHelper for $ty {
- fn is_dynamic() -> bool {
- $dynamic
- }
-
- fn size() -> usize {
- ABI_ALIGNMENT
- }
- }
-
- impl AbiRead for $ty {
- fn abi_read(reader: &mut AbiReader) -> Result<$ty> {
- reader.$method()
- }
- }
- };
-}
-
-impl_abi_readable!(bool, bool, false);
-impl_abi_readable!(uint32, uint32, false);
-impl_abi_readable!(uint64, uint64, false);
-impl_abi_readable!(uint128, uint128, false);
-impl_abi_readable!(uint256, uint256, false);
-impl_abi_readable!(bytes4, bytes4, false);
-impl_abi_readable!(address, address, false);
-impl_abi_readable!(string, string, true);
-
-impl TypeHelper for uint8 {
- fn is_dynamic() -> bool {
- false
- }
- fn size() -> usize {
- ABI_ALIGNMENT
- }
-}
-impl AbiRead for uint8 {
- fn abi_read(reader: &mut AbiReader) -> Result<uint8> {
- reader.uint8()
- }
-}
-
-impl TypeHelper for bytes {
- fn is_dynamic() -> bool {
- true
- }
- fn size() -> usize {
- ABI_ALIGNMENT
- }
-}
-impl AbiRead for bytes {
- fn abi_read(reader: &mut AbiReader) -> Result<bytes> {
- Ok(bytes(reader.bytes()?))
- }
-}
-
-mod sealed {
- /// Not all types can be placed in vec, i.e `Vec<u8>` is restricted, `bytes` should be used instead
- pub trait CanBePlacedInVec {}
-}
-
-impl<R: AbiRead + sealed::CanBePlacedInVec> AbiRead for Vec<R> {
- fn abi_read(reader: &mut AbiReader) -> Result<Vec<R>> {
- let mut sub = reader.subresult(None)?;
- let size = sub.uint32()? as usize;
- sub.subresult_offset = sub.offset;
- let mut out = Vec::with_capacity(size);
- for _ in 0..size {
- out.push(<R>::abi_read(&mut sub)?);
- }
- Ok(out)
- }
-}
-
-impl<R: Signature> Signature for Vec<R> {
- const SIGNATURE: SignatureUnit = make_signature!(new nameof(R::SIGNATURE) fixed("[]"));
-}
-
-impl sealed::CanBePlacedInVec for EthCrossAccount {}
-
-impl TypeHelper for EthCrossAccount {
- fn is_dynamic() -> bool {
- address::is_dynamic() || uint256::is_dynamic()
- }
-
- fn size() -> usize {
- <address as TypeHelper>::size() + <uint256 as TypeHelper>::size()
- }
-}
-
-impl AbiRead for EthCrossAccount {
- fn abi_read(reader: &mut AbiReader) -> Result<EthCrossAccount> {
- let size = if !EthCrossAccount::is_dynamic() {
- Some(<EthCrossAccount as TypeHelper>::size())
- } else {
- None
- };
- let mut subresult = reader.subresult(size)?;
- let eth = <address>::abi_read(&mut subresult)?;
- let sub = <uint256>::abi_read(&mut subresult)?;
-
- Ok(EthCrossAccount { eth, sub })
- }
-}
-
-impl AbiWrite for EthCrossAccount {
- fn abi_write(&self, writer: &mut AbiWriter) {
- self.eth.abi_write(writer);
- self.sub.abi_write(writer);
- }
-}
-
-macro_rules! impl_tuples {
- ($($ident:ident)+) => {
- impl<$($ident: TypeHelper,)+> TypeHelper for ($($ident,)+)
- where
- $(
- $ident: TypeHelper,
- )+
- {
- fn is_dynamic() -> bool {
- false
- $(
- || <$ident>::is_dynamic()
- )*
- }
-
- fn size() -> usize {
- 0 $(+ <$ident>::size())+
- }
- }
-
- impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}
-
- impl<$($ident),+> AbiRead for ($($ident,)+)
- where
- $($ident: AbiRead,)+
- ($($ident,)+): TypeHelper,
- {
- fn abi_read(reader: &mut AbiReader) -> Result<($($ident,)+)> {
- let size = if !<($($ident,)+)>::is_dynamic() { Some(<($($ident,)+)>::size()) } else { None };
- let mut subresult = reader.subresult(size)?;
- Ok((
- $(<$ident>::abi_read(&mut subresult)?,)+
- ))
- }
- }
-
- #[allow(non_snake_case)]
- impl<$($ident),+> AbiWrite for ($($ident,)+)
- where
- $($ident: AbiWrite,)+
- {
- fn abi_write(&self, writer: &mut AbiWriter) {
- let ($($ident,)+) = self;
- if writer.is_dynamic {
- let mut sub = AbiWriter::new();
- $($ident.abi_write(&mut sub);)+
- writer.write_subresult(sub);
- } else {
- $($ident.abi_write(writer);)+
- }
- }
- }
-
- impl<$($ident),+> Signature for ($($ident,)+)
- where
- $($ident: Signature,)+
- {
- const SIGNATURE: SignatureUnit = make_signature!(
- new fixed("(")
- $(nameof(<$ident>::SIGNATURE) fixed(","))+
- shift_left(1)
- fixed(")")
- );
- }
- };
-}
-
-impl_tuples! {A}
-impl_tuples! {A B}
-impl_tuples! {A B C}
-impl_tuples! {A B C D}
-impl_tuples! {A B C D E}
-impl_tuples! {A B C D E F}
-impl_tuples! {A B C D E F G}
-impl_tuples! {A B C D E F G H}
-impl_tuples! {A B C D E F G H I}
-impl_tuples! {A B C D E F G H I J}
-
-/// For questions about inability to provide custom implementations,
-/// see [`AbiRead`]
-pub trait AbiWrite {
- /// Write value to end of specified encoder
- fn abi_write(&self, writer: &mut AbiWriter);
- /// Specialization for [`crate::solidity_interface`] implementation,
- /// see comment in `impl AbiWrite for ResultWithPostInfo`
- fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
- let mut writer = AbiWriter::new();
- self.abi_write(&mut writer);
- Ok(writer.into())
- }
-}
-
-/// This particular AbiWrite implementation should be split to another trait,
-/// which only implements `to_result`, but due to lack of specialization feature
-/// in stable Rust, we can't have blanket impl of this trait `for T where T: AbiWrite`,
-/// so here we abusing default trait methods for it
-impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {
- fn abi_write(&self, _writer: &mut AbiWriter) {
- debug_assert!(false, "shouldn't be called, see comment")
- }
- fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
- match self {
- Ok(v) => Ok(WithPostDispatchInfo {
- post_info: v.post_info.clone(),
- data: {
- let mut out = AbiWriter::new();
- v.data.abi_write(&mut out);
- out
- },
- }),
- Err(e) => Err(e.clone()),
- }
- }
-}
-
-macro_rules! impl_abi_writeable {
- ($ty:ty, $method:ident) => {
- impl AbiWrite for $ty {
- fn abi_write(&self, writer: &mut AbiWriter) {
- writer.$method(&self)
- }
- }
- };
-}
-
-impl_abi_writeable!(u8, uint8);
-impl_abi_writeable!(u32, uint32);
-impl_abi_writeable!(u128, uint128);
-impl_abi_writeable!(U256, uint256);
-impl_abi_writeable!(H160, address);
-impl_abi_writeable!(bool, bool);
-impl_abi_writeable!(&str, string);
-
-impl AbiWrite for string {
- fn abi_write(&self, writer: &mut AbiWriter) {
- writer.string(self)
- }
-}
-
-impl AbiWrite for bytes {
- fn abi_write(&self, writer: &mut AbiWriter) {
- writer.bytes(self.0.as_slice())
- }
-}
-
-impl<T: AbiWrite + TypeHelper> AbiWrite for Vec<T> {
- fn abi_write(&self, writer: &mut AbiWriter) {
- let is_dynamic = T::is_dynamic();
- let mut sub = if is_dynamic {
- AbiWriter::new_dynamic(is_dynamic)
- } else {
- AbiWriter::new()
- };
-
- // Write items count
- (self.len() as u32).abi_write(&mut sub);
-
- for item in self {
- item.abi_write(&mut sub);
- }
- writer.write_subresult(sub);
- }
-}
-
-impl AbiWrite for () {
- fn abi_write(&self, _writer: &mut AbiWriter) {}
-}
-
-/// Helper macros to parse reader into variables
-#[deprecated]
-#[macro_export]
-macro_rules! abi_decode {
- ($reader:expr, $($name:ident: $typ:ident),+ $(,)?) => {
- $(
- let $name = $reader.$typ()?;
- )+
- }
-}
-
-/// Helper macros to construct RLP-encoded buffer
-#[deprecated]
-#[macro_export]
-macro_rules! abi_encode {
- ($($typ:ident($value:expr)),* $(,)?) => {{
- #[allow(unused_mut)]
- let mut writer = ::evm_coder::abi::AbiWriter::new();
- $(
- writer.$typ($value);
- )*
- writer
- }};
- (call $val:expr; $($typ:ident($value:expr)),* $(,)?) => {{
- #[allow(unused_mut)]
- let mut writer = ::evm_coder::abi::AbiWriter::new_call($val);
- $(
- writer.$typ($value);
- )*
- writer
- }}
-}
-
-#[cfg(test)]
-pub mod test {
- use crate::{
- abi::{AbiRead, AbiWrite},
- types::*,
- };
-
- use super::{AbiReader, AbiWriter};
- use hex_literal::hex;
- use primitive_types::{H160, U256};
- use concat_idents::concat_idents;
-
- macro_rules! test_impl {
- ($name:ident, $type:ty, $function_identifier:expr, $decoded_data:expr, $encoded_data:expr) => {
- concat_idents!(test_name = encode_decode_, $name {
- #[test]
- fn test_name() {
- let function_identifier: u32 = $function_identifier;
- let decoded_data = $decoded_data;
- let encoded_data = $encoded_data;
-
- let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
- assert_eq!(call, u32::to_be_bytes(function_identifier));
- let data = <$type>::abi_read(&mut decoder).unwrap();
- assert_eq!(data, decoded_data);
-
- let mut writer = AbiWriter::new_call(function_identifier);
- decoded_data.abi_write(&mut writer);
- let ed = writer.finish();
- similar_asserts::assert_eq!(encoded_data, ed.as_slice());
- }
- });
- };
- }
-
- macro_rules! test_impl_uint {
- ($type:ident) => {
- test_impl!(
- $type,
- $type,
- 0xdeadbeef,
- 255 as $type,
- &hex!(
- "
- deadbeef
- 00000000000000000000000000000000000000000000000000000000000000ff
- "
- )
- );
- };
- }
-
- test_impl_uint!(uint8);
- test_impl_uint!(uint32);
- test_impl_uint!(uint128);
-
- test_impl!(
- uint256,
- uint256,
- 0xdeadbeef,
- U256([255, 0, 0, 0]),
- &hex!(
- "
- deadbeef
- 00000000000000000000000000000000000000000000000000000000000000ff
- "
- )
- );
-
- test_impl!(
- vec_tuple_address_uint256,
- Vec<(address, uint256)>,
- 0x1ACF2D55,
- vec![
- (
- H160(hex!("2D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC")),
- U256([10, 0, 0, 0]),
- ),
- (
- H160(hex!("AB8E3D9134955566483B11E6825C9223B6737B10")),
- U256([20, 0, 0, 0]),
- ),
- (
- H160(hex!("8C582BDF2953046705FC56F189385255EFC1BE18")),
- U256([30, 0, 0, 0]),
- ),
- ],
- &hex!(
- "
- 1ACF2D55
- 0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
- 0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
-
- 0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
- 000000000000000000000000000000000000000000000000000000000000000A // uint256
-
- 000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
- 0000000000000000000000000000000000000000000000000000000000000014 // uint256
-
- 0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
- 000000000000000000000000000000000000000000000000000000000000001E // uint256
- "
- )
- );
-
- test_impl!(
- vec_tuple_uint256_string,
- Vec<(uint256, string)>,
- 0xdeadbeef,
- vec![
- (1.into(), "Test URI 0".to_string()),
- (11.into(), "Test URI 1".to_string()),
- (12.into(), "Test URI 2".to_string()),
- ],
- &hex!(
- "
- deadbeef
- 0000000000000000000000000000000000000000000000000000000000000020 // offset of (uint256, string)[]
- 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]
-
- 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem
- 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem
- 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem
-
- 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203000000000000000000000000000000000000000000000 // string
-
- 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203100000000000000000000000000000000000000000000 // string
-
- 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203200000000000000000000000000000000000000000000 // string
- "
- )
- );
-
- test_impl!(
- vec_tuple_string_bytes,
- Vec<(string, bytes)>,
- 0xdeadbeef,
- vec![
- (
- "Test URI 0".to_string(),
- bytes(vec![
- 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
- 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
- 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
- 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
- ])
- ),
- (
- "Test URI 1".to_string(),
- bytes(vec![
- 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
- 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
- 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
- 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22
- ])
- ),
- ("Test URI 2".to_string(), bytes(vec![0x33, 0x33])),
- ],
- &hex!(
- "
- deadbeef
- 0000000000000000000000000000000000000000000000000000000000000020
- 0000000000000000000000000000000000000000000000000000000000000003
-
- 0000000000000000000000000000000000000000000000000000000000000060
- 0000000000000000000000000000000000000000000000000000000000000140
- 0000000000000000000000000000000000000000000000000000000000000220
-
- 0000000000000000000000000000000000000000000000000000000000000040
- 0000000000000000000000000000000000000000000000000000000000000080
- 000000000000000000000000000000000000000000000000000000000000000a
- 5465737420555249203000000000000000000000000000000000000000000000
- 0000000000000000000000000000000000000000000000000000000000000030
- 1111111111111111111111111111111111111111111111111111111111111111
- 1111111111111111111111111111111100000000000000000000000000000000
-
- 0000000000000000000000000000000000000000000000000000000000000040
- 0000000000000000000000000000000000000000000000000000000000000080
- 000000000000000000000000000000000000000000000000000000000000000a
- 5465737420555249203100000000000000000000000000000000000000000000
- 000000000000000000000000000000000000000000000000000000000000002f
- 2222222222222222222222222222222222222222222222222222222222222222
- 2222222222222222222222222222220000000000000000000000000000000000
-
- 0000000000000000000000000000000000000000000000000000000000000040
- 0000000000000000000000000000000000000000000000000000000000000080
- 000000000000000000000000000000000000000000000000000000000000000a
- 5465737420555249203200000000000000000000000000000000000000000000
- 0000000000000000000000000000000000000000000000000000000000000002
- 3333000000000000000000000000000000000000000000000000000000000000
- "
- )
- );
-
- #[test]
- fn dynamic_after_static() {
- let mut encoder = AbiWriter::new();
- encoder.bool(&true);
- encoder.string("test");
- let encoded = encoder.finish();
-
- let mut encoder = AbiWriter::new();
- encoder.bool(&true);
- // Offset to subresult
- encoder.uint32(&(32 * 2));
- // Len of "test"
- encoder.uint32(&4);
- encoder.write_padright(&[b't', b'e', b's', b't']);
- let alternative_encoded = encoder.finish();
-
- assert_eq!(encoded, alternative_encoded);
-
- let mut decoder = AbiReader::new(&encoded);
- assert!(decoder.bool().unwrap());
- assert_eq!(decoder.string().unwrap(), "test");
- }
-
- #[test]
- fn mint_sample() {
- let (call, mut decoder) = AbiReader::new_call(&hex!(
- "
- 50bb4e7f
- 000000000000000000000000ad2c0954693c2b5404b7e50967d3481bea432374
- 0000000000000000000000000000000000000000000000000000000000000001
- 0000000000000000000000000000000000000000000000000000000000000060
- 0000000000000000000000000000000000000000000000000000000000000008
- 5465737420555249000000000000000000000000000000000000000000000000
- "
- ))
- .unwrap();
- assert_eq!(call, u32::to_be_bytes(0x50bb4e7f));
- assert_eq!(
- format!("{:?}", decoder.address().unwrap()),
- "0xad2c0954693c2b5404b7e50967d3481bea432374"
- );
- assert_eq!(decoder.uint32().unwrap(), 1);
- assert_eq!(decoder.string().unwrap(), "Test URI");
- }
-
- #[test]
- fn parse_vec_with_dynamic_type() {
- let decoded_data = (
- 0x36543006,
- vec![
- (1.into(), "Test URI 0".to_string()),
- (11.into(), "Test URI 1".to_string()),
- (12.into(), "Test URI 2".to_string()),
- ],
- );
-
- let encoded_data = &hex!(
- "
- 36543006
- 00000000000000000000000053744e6da587ba10b32a2554d2efdcd985bc27a3 // address
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of (uint256, string)[]
- 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]
-
- 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem
- 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem
- 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem
-
- 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203000000000000000000000000000000000000000000000 // string
-
- 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203100000000000000000000000000000000000000000000 // string
-
- 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160
- 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
- 000000000000000000000000000000000000000000000000000000000000000a // size of string
- 5465737420555249203200000000000000000000000000000000000000000000 // string
- "
- );
-
- let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
- assert_eq!(call, u32::to_be_bytes(decoded_data.0));
- let address = decoder.address().unwrap();
- let data = <Vec<(uint256, string)>>::abi_read(&mut decoder).unwrap();
- assert_eq!(data, decoded_data.1);
-
- let mut writer = AbiWriter::new_call(decoded_data.0);
- address.abi_write(&mut writer);
- decoded_data.1.abi_write(&mut writer);
- let ed = writer.finish();
- similar_asserts::assert_eq!(encoded_data, ed.as_slice());
- }
-}
crates/evm-coder/src/abi/impls.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/abi/impls.rs
@@ -0,0 +1,303 @@
+use crate::{
+ execution::{Result, ResultWithPostInfo, WithPostDispatchInfo},
+ types::*,
+ make_signature,
+ custom_signature::SignatureUnit,
+};
+use super::{traits::*, ABI_ALIGNMENT, AbiReader, AbiWriter};
+use primitive_types::{U256, H160};
+
+#[cfg(not(feature = "std"))]
+use alloc::vec::Vec;
+
+macro_rules! impl_abi_readable {
+ ($ty:ty, $method:ident, $dynamic:literal) => {
+ impl sealed::CanBePlacedInVec for $ty {}
+
+ impl AbiType for $ty {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ty)));
+
+ fn is_dynamic() -> bool {
+ $dynamic
+ }
+
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+ }
+
+ impl AbiRead for $ty {
+ fn abi_read(reader: &mut AbiReader) -> Result<$ty> {
+ reader.$method()
+ }
+ }
+ };
+}
+
+impl_abi_readable!(uint32, uint32, false);
+impl_abi_readable!(uint64, uint64, false);
+impl_abi_readable!(uint128, uint128, false);
+impl_abi_readable!(uint256, uint256, false);
+impl_abi_readable!(bytes4, bytes4, false);
+impl_abi_readable!(address, address, false);
+impl_abi_readable!(string, string, true);
+
+impl sealed::CanBePlacedInVec for bool {}
+
+impl AbiType for bool {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bool"));
+
+ fn is_dynamic() -> bool {
+ false
+ }
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+impl AbiRead for bool {
+ fn abi_read(reader: &mut AbiReader) -> Result<bool> {
+ reader.bool()
+ }
+}
+
+impl AbiType for uint8 {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint8"));
+
+ fn is_dynamic() -> bool {
+ false
+ }
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+impl AbiRead for uint8 {
+ fn abi_read(reader: &mut AbiReader) -> Result<uint8> {
+ reader.uint8()
+ }
+}
+
+impl AbiType for bytes {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));
+
+ fn is_dynamic() -> bool {
+ true
+ }
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+impl AbiRead for bytes {
+ fn abi_read(reader: &mut AbiReader) -> Result<bytes> {
+ Ok(bytes(reader.bytes()?))
+ }
+}
+
+impl<R: AbiRead + sealed::CanBePlacedInVec> AbiRead for Vec<R> {
+ fn abi_read(reader: &mut AbiReader) -> Result<Vec<R>> {
+ let mut sub = reader.subresult(None)?;
+ let size = sub.uint32()? as usize;
+ sub.subresult_offset = sub.offset;
+ let mut out = Vec::with_capacity(size);
+ for _ in 0..size {
+ out.push(<R>::abi_read(&mut sub)?);
+ }
+ Ok(out)
+ }
+}
+
+impl<R: AbiType> AbiType for Vec<R> {
+ const SIGNATURE: SignatureUnit = make_signature!(new nameof(R::SIGNATURE) fixed("[]"));
+
+ fn is_dynamic() -> bool {
+ true
+ }
+
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+
+impl sealed::CanBePlacedInVec for EthCrossAccount {}
+
+impl AbiType for EthCrossAccount {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("(address,uint256)"));
+
+ fn is_dynamic() -> bool {
+ address::is_dynamic() || uint256::is_dynamic()
+ }
+
+ fn size() -> usize {
+ <address as AbiType>::size() + <uint256 as AbiType>::size()
+ }
+}
+
+impl AbiRead for EthCrossAccount {
+ fn abi_read(reader: &mut AbiReader) -> Result<EthCrossAccount> {
+ let size = if !EthCrossAccount::is_dynamic() {
+ Some(<EthCrossAccount as AbiType>::size())
+ } else {
+ None
+ };
+ let mut subresult = reader.subresult(size)?;
+ let eth = <address>::abi_read(&mut subresult)?;
+ let sub = <uint256>::abi_read(&mut subresult)?;
+
+ Ok(EthCrossAccount { eth, sub })
+ }
+}
+
+impl AbiWrite for EthCrossAccount {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ self.eth.abi_write(writer);
+ self.sub.abi_write(writer);
+ }
+}
+
+macro_rules! impl_abi_writeable {
+ ($ty:ty, $method:ident) => {
+ impl AbiWrite for $ty {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ writer.$method(&self)
+ }
+ }
+ };
+}
+
+impl_abi_writeable!(u8, uint8);
+impl_abi_writeable!(u32, uint32);
+impl_abi_writeable!(u128, uint128);
+impl_abi_writeable!(U256, uint256);
+impl_abi_writeable!(H160, address);
+impl_abi_writeable!(bool, bool);
+impl_abi_writeable!(&str, string);
+
+impl AbiWrite for string {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ writer.string(self)
+ }
+}
+
+impl AbiWrite for bytes {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ writer.bytes(self.0.as_slice())
+ }
+}
+
+impl<T: AbiWrite + AbiType> AbiWrite for Vec<T> {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ let is_dynamic = T::is_dynamic();
+ let mut sub = if is_dynamic {
+ AbiWriter::new_dynamic(is_dynamic)
+ } else {
+ AbiWriter::new()
+ };
+
+ // Write items count
+ (self.len() as u32).abi_write(&mut sub);
+
+ for item in self {
+ item.abi_write(&mut sub);
+ }
+ writer.write_subresult(sub);
+ }
+}
+
+impl AbiWrite for () {
+ fn abi_write(&self, _writer: &mut AbiWriter) {}
+}
+
+/// This particular AbiWrite implementation should be split to another trait,
+/// which only implements `to_result`, but due to lack of specialization feature
+/// in stable Rust, we can't have blanket impl of this trait `for T where T: AbiWrite`,
+/// so here we abusing default trait methods for it
+impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {
+ fn abi_write(&self, _writer: &mut AbiWriter) {
+ debug_assert!(false, "shouldn't be called, see comment")
+ }
+ fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
+ match self {
+ Ok(v) => Ok(WithPostDispatchInfo {
+ post_info: v.post_info.clone(),
+ data: {
+ let mut out = AbiWriter::new();
+ v.data.abi_write(&mut out);
+ out
+ },
+ }),
+ Err(e) => Err(e.clone()),
+ }
+ }
+}
+
+macro_rules! impl_tuples {
+ ($($ident:ident)+) => {
+ impl<$($ident: AbiType,)+> AbiType for ($($ident,)+)
+ where
+ $(
+ $ident: AbiType,
+ )+
+ {
+ const SIGNATURE: SignatureUnit = make_signature!(
+ new fixed("(")
+ $(nameof(<$ident>::SIGNATURE) fixed(","))+
+ shift_left(1)
+ fixed(")")
+ );
+
+ fn is_dynamic() -> bool {
+ false
+ $(
+ || <$ident>::is_dynamic()
+ )*
+ }
+
+ fn size() -> usize {
+ 0 $(+ <$ident>::size())+
+ }
+ }
+
+ impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}
+
+ impl<$($ident),+> AbiRead for ($($ident,)+)
+ where
+ $($ident: AbiRead,)+
+ ($($ident,)+): AbiType,
+ {
+ fn abi_read(reader: &mut AbiReader) -> Result<($($ident,)+)> {
+ let size = if !<($($ident,)+)>::is_dynamic() { Some(<($($ident,)+)>::size()) } else { None };
+ let mut subresult = reader.subresult(size)?;
+ Ok((
+ $(<$ident>::abi_read(&mut subresult)?,)+
+ ))
+ }
+ }
+
+ #[allow(non_snake_case)]
+ impl<$($ident),+> AbiWrite for ($($ident,)+)
+ where
+ $($ident: AbiWrite,)+
+ {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ let ($($ident,)+) = self;
+ if writer.is_dynamic {
+ let mut sub = AbiWriter::new();
+ $($ident.abi_write(&mut sub);)+
+ writer.write_subresult(sub);
+ } else {
+ $($ident.abi_write(writer);)+
+ }
+ }
+ }
+ };
+}
+
+impl_tuples! {A}
+impl_tuples! {A B}
+impl_tuples! {A B C}
+impl_tuples! {A B C D}
+impl_tuples! {A B C D E}
+impl_tuples! {A B C D E F}
+impl_tuples! {A B C D E F G}
+impl_tuples! {A B C D E F G H}
+impl_tuples! {A B C D E F G H I}
+impl_tuples! {A B C D E F G H I J}
crates/evm-coder/src/abi/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/abi/mod.rs
@@ -0,0 +1,339 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+//! Implementation of EVM RLP reader/writer
+
+#![allow(dead_code)]
+
+mod traits;
+pub use traits::*;
+mod impls;
+
+#[cfg(test)]
+mod test;
+
+#[cfg(not(feature = "std"))]
+use alloc::vec::Vec;
+use evm_core::ExitError;
+use primitive_types::{H160, U256};
+
+use crate::{
+ execution::{Result, Error},
+ types::*,
+};
+
+const ABI_ALIGNMENT: usize = 32;
+
+/// View into RLP data, which provides method to read typed items from it
+#[derive(Clone)]
+pub struct AbiReader<'i> {
+ buf: &'i [u8],
+ subresult_offset: usize,
+ offset: usize,
+}
+impl<'i> AbiReader<'i> {
+ /// Start reading RLP buffer, assuming there is no padding bytes
+ pub fn new(buf: &'i [u8]) -> Self {
+ Self {
+ buf,
+ subresult_offset: 0,
+ offset: 0,
+ }
+ }
+ /// Start reading RLP buffer, parsing first 4 bytes as selector
+ pub fn new_call(buf: &'i [u8]) -> Result<(bytes4, Self)> {
+ if buf.len() < 4 {
+ return Err(Error::Error(ExitError::OutOfOffset));
+ }
+ let mut method_id = [0; 4];
+ method_id.copy_from_slice(&buf[0..4]);
+
+ Ok((
+ method_id,
+ Self {
+ buf,
+ subresult_offset: 4,
+ offset: 4,
+ },
+ ))
+ }
+
+ fn read_pad<const S: usize>(
+ buf: &[u8],
+ offset: usize,
+ pad_start: usize,
+ pad_size: usize,
+ block_start: usize,
+ block_size: usize,
+ ) -> Result<[u8; S]> {
+ if buf.len() - offset < ABI_ALIGNMENT {
+ return Err(Error::Error(ExitError::OutOfOffset));
+ }
+ let mut block = [0; S];
+ let is_pad_zeroed = buf[pad_start..pad_size].iter().all(|&v| v == 0);
+ if !is_pad_zeroed {
+ return Err(Error::Error(ExitError::InvalidRange));
+ }
+ block.copy_from_slice(&buf[block_start..block_size]);
+ Ok(block)
+ }
+
+ fn read_padleft<const S: usize>(&mut self) -> Result<[u8; S]> {
+ let offset = self.offset;
+ self.offset += ABI_ALIGNMENT;
+ Self::read_pad(
+ self.buf,
+ offset,
+ offset,
+ offset + ABI_ALIGNMENT - S,
+ offset + ABI_ALIGNMENT - S,
+ offset + ABI_ALIGNMENT,
+ )
+ }
+
+ fn read_padright<const S: usize>(&mut self) -> Result<[u8; S]> {
+ let offset = self.offset;
+ self.offset += ABI_ALIGNMENT;
+ Self::read_pad(
+ self.buf,
+ offset,
+ offset + S,
+ offset + ABI_ALIGNMENT,
+ offset,
+ offset + S,
+ )
+ }
+
+ /// Read [`H160`] at current position, then advance
+ pub fn address(&mut self) -> Result<H160> {
+ Ok(H160(self.read_padleft()?))
+ }
+
+ /// Read [`bool`] at current position, then advance
+ pub fn bool(&mut self) -> Result<bool> {
+ let data: [u8; 1] = self.read_padleft()?;
+ match data[0] {
+ 0 => Ok(false),
+ 1 => Ok(true),
+ _ => Err(Error::Error(ExitError::InvalidRange)),
+ }
+ }
+
+ /// Read [`[u8; 4]`] at current position, then advance
+ pub fn bytes4(&mut self) -> Result<[u8; 4]> {
+ self.read_padright()
+ }
+
+ /// Read [`Vec<u8>`] at current position, then advance
+ pub fn bytes(&mut self) -> Result<Vec<u8>> {
+ let mut subresult = self.subresult(None)?;
+ let length = subresult.uint32()? as usize;
+ if subresult.buf.len() < subresult.offset + length {
+ return Err(Error::Error(ExitError::OutOfOffset));
+ }
+ Ok(subresult.buf[subresult.offset..subresult.offset + length].into())
+ }
+
+ /// Read [`string`] at current position, then advance
+ pub fn string(&mut self) -> Result<string> {
+ string::from_utf8(self.bytes()?).map_err(|_| Error::Error(ExitError::InvalidRange))
+ }
+
+ /// Read [`u8`] at current position, then advance
+ pub fn uint8(&mut self) -> Result<u8> {
+ Ok(self.read_padleft::<1>()?[0])
+ }
+
+ /// Read [`u32`] at current position, then advance
+ pub fn uint32(&mut self) -> Result<u32> {
+ Ok(u32::from_be_bytes(self.read_padleft()?))
+ }
+
+ /// Read [`u128`] at current position, then advance
+ pub fn uint128(&mut self) -> Result<u128> {
+ Ok(u128::from_be_bytes(self.read_padleft()?))
+ }
+
+ /// Read [`U256`] at current position, then advance
+ pub fn uint256(&mut self) -> Result<U256> {
+ let buf: [u8; 32] = self.read_padleft()?;
+ Ok(U256::from_big_endian(&buf))
+ }
+
+ /// Read [`u64`] at current position, then advance
+ pub fn uint64(&mut self) -> Result<u64> {
+ Ok(u64::from_be_bytes(self.read_padleft()?))
+ }
+
+ /// Read [`usize`] at current position, then advance
+ #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]
+ pub fn read_usize(&mut self) -> Result<usize> {
+ Ok(usize::from_be_bytes(self.read_padleft()?))
+ }
+
+ /// Slice recursive buffer, advance one word for buffer offset
+ /// If `size` is [`None`] then [`Self::offset`] and [`Self::subresult_offset`] evals from [`Self::buf`].
+ fn subresult(&mut self, size: Option<usize>) -> Result<AbiReader<'i>> {
+ let subresult_offset = self.subresult_offset;
+ let offset = if let Some(size) = size {
+ self.offset += size;
+ self.subresult_offset += size;
+ 0
+ } else {
+ self.uint32()? as usize
+ };
+
+ if offset + self.subresult_offset > self.buf.len() {
+ return Err(Error::Error(ExitError::InvalidRange));
+ }
+
+ let new_offset = offset + subresult_offset;
+ Ok(AbiReader {
+ buf: self.buf,
+ subresult_offset: new_offset,
+ offset: new_offset,
+ })
+ }
+
+ /// Is this parser reached end of buffer?
+ pub fn is_finished(&self) -> bool {
+ self.buf.len() == self.offset
+ }
+}
+
+/// Writer for RLP encoded data
+#[derive(Default)]
+pub struct AbiWriter {
+ static_part: Vec<u8>,
+ dynamic_part: Vec<(usize, AbiWriter)>,
+ had_call: bool,
+ is_dynamic: bool,
+}
+impl AbiWriter {
+ /// Initialize internal buffers for output data, assuming no padding required
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Initialize internal buffers with data size
+ pub fn new_dynamic(is_dynamic: bool) -> Self {
+ Self {
+ is_dynamic,
+ ..Default::default()
+ }
+ }
+ /// Initialize internal buffers, inserting method selector at beginning
+ pub fn new_call(method_id: u32) -> Self {
+ let mut val = Self::new();
+ val.static_part.extend(&method_id.to_be_bytes());
+ val.had_call = true;
+ val
+ }
+
+ fn write_padleft(&mut self, block: &[u8]) {
+ assert!(block.len() <= ABI_ALIGNMENT);
+ self.static_part
+ .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);
+ self.static_part.extend(block);
+ }
+
+ fn write_padright(&mut self, block: &[u8]) {
+ assert!(block.len() <= ABI_ALIGNMENT);
+ self.static_part.extend(block);
+ self.static_part
+ .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);
+ }
+
+ /// Write [`H160`] to end of buffer
+ pub fn address(&mut self, address: &H160) {
+ self.write_padleft(&address.0)
+ }
+
+ /// Write [`bool`] to end of buffer
+ pub fn bool(&mut self, value: &bool) {
+ self.write_padleft(&[if *value { 1 } else { 0 }])
+ }
+
+ /// Write [`u8`] to end of buffer
+ pub fn uint8(&mut self, value: &u8) {
+ self.write_padleft(&[*value])
+ }
+
+ /// Write [`u32`] to end of buffer
+ pub fn uint32(&mut self, value: &u32) {
+ self.write_padleft(&u32::to_be_bytes(*value))
+ }
+
+ /// Write [`u128`] to end of buffer
+ pub fn uint128(&mut self, value: &u128) {
+ self.write_padleft(&u128::to_be_bytes(*value))
+ }
+
+ /// Write [`U256`] to end of buffer
+ pub fn uint256(&mut self, value: &U256) {
+ let mut out = [0; 32];
+ value.to_big_endian(&mut out);
+ self.write_padleft(&out)
+ }
+
+ /// Write [`usize`] to end of buffer
+ #[deprecated = "dangerous, as usize may have different width in wasm and native execution"]
+ pub fn write_usize(&mut self, value: &usize) {
+ self.write_padleft(&usize::to_be_bytes(*value))
+ }
+
+ /// Append recursive data, writing pending offset at end of buffer
+ pub fn write_subresult(&mut self, result: Self) {
+ self.dynamic_part.push((self.static_part.len(), result));
+ // Empty block, to be filled later
+ self.write_padleft(&[]);
+ }
+
+ fn memory(&mut self, value: &[u8]) {
+ let mut sub = Self::new();
+ sub.uint32(&(value.len() as u32));
+ for chunk in value.chunks(ABI_ALIGNMENT) {
+ sub.write_padright(chunk);
+ }
+ self.write_subresult(sub);
+ }
+
+ /// Append recursive [`str`] at end of buffer
+ pub fn string(&mut self, value: &str) {
+ self.memory(value.as_bytes())
+ }
+
+ /// Append recursive [`[u8]`] at end of buffer
+ pub fn bytes(&mut self, value: &[u8]) {
+ self.memory(value)
+ }
+
+ /// Finish writer, concatenating all internal buffers
+ pub fn finish(mut self) -> Vec<u8> {
+ for (static_offset, part) in self.dynamic_part {
+ let part_offset = self.static_part.len()
+ - if self.had_call { 4 } else { 0 }
+ - if self.is_dynamic { ABI_ALIGNMENT } else { 0 };
+
+ let encoded_dynamic_offset = usize::to_be_bytes(part_offset);
+ let start = static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len();
+ let stop = static_offset + ABI_ALIGNMENT;
+ self.static_part[start..stop].copy_from_slice(&encoded_dynamic_offset);
+ self.static_part.extend(part.finish())
+ }
+ self.static_part
+ }
+}
crates/evm-coder/src/abi/test.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/abi/test.rs
@@ -0,0 +1,297 @@
+use crate::{
+ abi::{AbiRead, AbiWrite},
+ types::*,
+};
+
+use super::{AbiReader, AbiWriter};
+use hex_literal::hex;
+use primitive_types::{H160, U256};
+use concat_idents::concat_idents;
+
+macro_rules! test_impl {
+ ($name:ident, $type:ty, $function_identifier:expr, $decoded_data:expr, $encoded_data:expr) => {
+ concat_idents!(test_name = encode_decode_, $name {
+ #[test]
+ fn test_name() {
+ let function_identifier: u32 = $function_identifier;
+ let decoded_data = $decoded_data;
+ let encoded_data = $encoded_data;
+
+ let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
+ assert_eq!(call, u32::to_be_bytes(function_identifier));
+ let data = <$type>::abi_read(&mut decoder).unwrap();
+ assert_eq!(data, decoded_data);
+
+ let mut writer = AbiWriter::new_call(function_identifier);
+ decoded_data.abi_write(&mut writer);
+ let ed = writer.finish();
+ similar_asserts::assert_eq!(encoded_data, ed.as_slice());
+ }
+ });
+ };
+}
+
+macro_rules! test_impl_uint {
+ ($type:ident) => {
+ test_impl!(
+ $type,
+ $type,
+ 0xdeadbeef,
+ 255 as $type,
+ &hex!(
+ "
+ deadbeef
+ 00000000000000000000000000000000000000000000000000000000000000ff
+ "
+ )
+ );
+ };
+}
+
+test_impl_uint!(uint8);
+test_impl_uint!(uint32);
+test_impl_uint!(uint128);
+
+test_impl!(
+ uint256,
+ uint256,
+ 0xdeadbeef,
+ U256([255, 0, 0, 0]),
+ &hex!(
+ "
+ deadbeef
+ 00000000000000000000000000000000000000000000000000000000000000ff
+ "
+ )
+);
+
+test_impl!(
+ vec_tuple_address_uint256,
+ Vec<(address, uint256)>,
+ 0x1ACF2D55,
+ vec![
+ (
+ H160(hex!("2D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC")),
+ U256([10, 0, 0, 0]),
+ ),
+ (
+ H160(hex!("AB8E3D9134955566483B11E6825C9223B6737B10")),
+ U256([20, 0, 0, 0]),
+ ),
+ (
+ H160(hex!("8C582BDF2953046705FC56F189385255EFC1BE18")),
+ U256([30, 0, 0, 0]),
+ ),
+ ],
+ &hex!(
+ "
+ 1ACF2D55
+ 0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
+ 0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
+
+ 0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
+ 000000000000000000000000000000000000000000000000000000000000000A // uint256
+
+ 000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
+ 0000000000000000000000000000000000000000000000000000000000000014 // uint256
+
+ 0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
+ 000000000000000000000000000000000000000000000000000000000000001E // uint256
+ "
+ )
+);
+
+test_impl!(
+ vec_tuple_uint256_string,
+ Vec<(uint256, string)>,
+ 0xdeadbeef,
+ vec![
+ (1.into(), "Test URI 0".to_string()),
+ (11.into(), "Test URI 1".to_string()),
+ (12.into(), "Test URI 2".to_string()),
+ ],
+ &hex!(
+ "
+ deadbeef
+ 0000000000000000000000000000000000000000000000000000000000000020 // offset of (uint256, string)[]
+ 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]
+
+ 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem
+ 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem
+ 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem
+
+ 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203000000000000000000000000000000000000000000000 // string
+
+ 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203100000000000000000000000000000000000000000000 // string
+
+ 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203200000000000000000000000000000000000000000000 // string
+ "
+ )
+);
+
+#[test]
+fn dynamic_after_static() {
+ let mut encoder = AbiWriter::new();
+ encoder.bool(&true);
+ encoder.string("test");
+ let encoded = encoder.finish();
+
+ let mut encoder = AbiWriter::new();
+ encoder.bool(&true);
+ // Offset to subresult
+ encoder.uint32(&(32 * 2));
+ // Len of "test"
+ encoder.uint32(&4);
+ encoder.write_padright(&[b't', b'e', b's', b't']);
+ let alternative_encoded = encoder.finish();
+
+ assert_eq!(encoded, alternative_encoded);
+
+ let mut decoder = AbiReader::new(&encoded);
+ assert!(decoder.bool().unwrap());
+ assert_eq!(decoder.string().unwrap(), "test");
+}
+
+#[test]
+fn mint_sample() {
+ let (call, mut decoder) = AbiReader::new_call(&hex!(
+ "
+ 50bb4e7f
+ 000000000000000000000000ad2c0954693c2b5404b7e50967d3481bea432374
+ 0000000000000000000000000000000000000000000000000000000000000001
+ 0000000000000000000000000000000000000000000000000000000000000060
+ 0000000000000000000000000000000000000000000000000000000000000008
+ 5465737420555249000000000000000000000000000000000000000000000000
+ "
+ ))
+ .unwrap();
+ assert_eq!(call, u32::to_be_bytes(0x50bb4e7f));
+ assert_eq!(
+ format!("{:?}", decoder.address().unwrap()),
+ "0xad2c0954693c2b5404b7e50967d3481bea432374"
+ );
+ assert_eq!(decoder.uint32().unwrap(), 1);
+ assert_eq!(decoder.string().unwrap(), "Test URI");
+}
+
+#[test]
+fn parse_vec_with_dynamic_type() {
+ let decoded_data = (
+ 0x36543006,
+ vec![
+ (1.into(), "Test URI 0".to_string()),
+ (11.into(), "Test URI 1".to_string()),
+ (12.into(), "Test URI 2".to_string()),
+ ],
+ );
+
+ let encoded_data = &hex!(
+ "
+ 36543006
+ 00000000000000000000000053744e6da587ba10b32a2554d2efdcd985bc27a3 // address
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of (uint256, string)[]
+ 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]
+
+ 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem
+ 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem
+ 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem
+
+ 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203000000000000000000000000000000000000000000000 // string
+
+ 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203100000000000000000000000000000000000000000000 // string
+
+ 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203200000000000000000000000000000000000000000000 // string
+ "
+ );
+
+ let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
+ assert_eq!(call, u32::to_be_bytes(decoded_data.0));
+ let address = decoder.address().unwrap();
+ let data = <Vec<(uint256, string)>>::abi_read(&mut decoder).unwrap();
+ assert_eq!(data, decoded_data.1);
+
+ let mut writer = AbiWriter::new_call(decoded_data.0);
+ address.abi_write(&mut writer);
+ decoded_data.1.abi_write(&mut writer);
+ let ed = writer.finish();
+ similar_asserts::assert_eq!(encoded_data, ed.as_slice());
+}
+
+test_impl!(
+ vec_tuple_string_bytes,
+ Vec<(string, bytes)>,
+ 0xdeadbeef,
+ vec![
+ (
+ "Test URI 0".to_string(),
+ bytes(vec![
+ 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
+ 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
+ 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
+ 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
+ ])
+ ),
+ (
+ "Test URI 1".to_string(),
+ bytes(vec![
+ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
+ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
+ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
+ 0x22, 0x22, 0x22, 0x22, 0x22
+ ])
+ ),
+ ("Test URI 2".to_string(), bytes(vec![0x33, 0x33])),
+ ],
+ &hex!(
+ "
+ deadbeef
+ 0000000000000000000000000000000000000000000000000000000000000020
+ 0000000000000000000000000000000000000000000000000000000000000003
+
+ 0000000000000000000000000000000000000000000000000000000000000060
+ 0000000000000000000000000000000000000000000000000000000000000140
+ 0000000000000000000000000000000000000000000000000000000000000220
+
+ 0000000000000000000000000000000000000000000000000000000000000040
+ 0000000000000000000000000000000000000000000000000000000000000080
+ 000000000000000000000000000000000000000000000000000000000000000a
+ 5465737420555249203000000000000000000000000000000000000000000000
+ 0000000000000000000000000000000000000000000000000000000000000030
+ 1111111111111111111111111111111111111111111111111111111111111111
+ 1111111111111111111111111111111100000000000000000000000000000000
+
+ 0000000000000000000000000000000000000000000000000000000000000040
+ 0000000000000000000000000000000000000000000000000000000000000080
+ 000000000000000000000000000000000000000000000000000000000000000a
+ 5465737420555249203100000000000000000000000000000000000000000000
+ 000000000000000000000000000000000000000000000000000000000000002f
+ 2222222222222222222222222222222222222222222222222222222222222222
+ 2222222222222222222222222222220000000000000000000000000000000000
+
+ 0000000000000000000000000000000000000000000000000000000000000040
+ 0000000000000000000000000000000000000000000000000000000000000080
+ 000000000000000000000000000000000000000000000000000000000000000a
+ 5465737420555249203200000000000000000000000000000000000000000000
+ 0000000000000000000000000000000000000000000000000000000000000002
+ 3333000000000000000000000000000000000000000000000000000000000000
+ "
+ )
+);
crates/evm-coder/src/abi/traits.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/abi/traits.rs
@@ -0,0 +1,51 @@
+use super::{AbiReader, AbiWriter};
+use crate::{
+ custom_signature::*,
+ execution::{Result, ResultWithPostInfo},
+};
+use core::str::from_utf8;
+
+/// Helper for type.
+pub trait AbiType {
+ /// Signature for Etherium ABI.
+ const SIGNATURE: SignatureUnit;
+
+ /// Signature as str.
+ fn as_str() -> &'static str {
+ from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+ }
+
+ /// Is type dynamic sized.
+ fn is_dynamic() -> bool;
+
+ /// Size for type aligned to [`ABI_ALIGNMENT`].
+ fn size() -> usize;
+}
+
+/// Sealed traits.
+pub mod sealed {
+ /// Not all types can be placed in vec, i.e `Vec<u8>` is restricted, `bytes` should be used instead
+ pub trait CanBePlacedInVec {}
+}
+
+/// [`AbiReader`] implements reading of many types.
+pub trait AbiRead {
+ /// Read item from current position, advanding decoder
+ fn abi_read(reader: &mut AbiReader) -> Result<Self>
+ where
+ Self: Sized;
+}
+
+/// For questions about inability to provide custom implementations,
+/// see [`AbiRead`]
+pub trait AbiWrite {
+ /// Write value to end of specified encoder
+ fn abi_write(&self, writer: &mut AbiWriter);
+ /// Specialization for [`crate::solidity_interface`] implementation,
+ /// see comment in `impl AbiWrite for ResultWithPostInfo`
+ fn to_result(&self) -> ResultWithPostInfo<AbiWriter> {
+ let mut writer = AbiWriter::new();
+ self.abi_write(&mut writer);
+ Ok(writer.into())
+ }
+}
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -121,53 +121,24 @@
use alloc::{vec::Vec};
use pallet_evm::account::CrossAccountId;
use primitive_types::{U256, H160, H256};
- use core::str::from_utf8;
-
- use crate::custom_signature::SignatureUnit;
-
- pub trait Signature {
- const SIGNATURE: SignatureUnit;
-
- fn as_str() -> &'static str {
- from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
- }
- }
-
- impl Signature for 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 {
- const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ident)));
- }
- };
- }
- define_simple_type!(type address = H160);
-
- define_simple_type!(type uint8 = u8);
- define_simple_type!(type uint16 = u16);
- define_simple_type!(type uint32 = u32);
- define_simple_type!(type uint64 = u64);
- define_simple_type!(type uint128 = u128);
- define_simple_type!(type uint256 = U256);
- define_simple_type!(type bytes4 = [u8; 4]);
-
- define_simple_type!(type topic = H256);
+ pub type address = H160;
+ pub type uint8 = u8;
+ pub type uint16 = u16;
+ pub type uint32 = u32;
+ pub type uint64 = u64;
+ pub type uint128 = u128;
+ pub type uint256 = U256;
+ pub type bytes4 = [u8; 4];
+ pub type topic = H256;
#[cfg(not(feature = "std"))]
- define_simple_type!(type string = ::alloc::string::String);
+ pub type string = ::alloc::string::String;
#[cfg(feature = "std")]
- define_simple_type!(type string = ::std::string::String);
+ pub type string = ::std::string::String;
#[derive(Default, Debug, PartialEq)]
pub struct bytes(pub Vec<u8>);
- impl Signature for bytes {
- const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));
- }
/// Solidity doesn't have `void` type, however we have special implementation
/// for empty tuple return type
@@ -257,10 +228,6 @@
Err("All fields of cross account is non zeroed".into())
}
}
- }
-
- impl Signature for EthCrossAccount {
- const SIGNATURE: SignatureUnit = make_signature!(new fixed("(address,uint256)"));
}
/// Convert `CrossAccountId` to `uint256`.
crates/evm-coder/tests/random.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/random.rs
+++ b/crates/evm-coder/tests/random.rs
@@ -16,8 +16,9 @@
#![allow(dead_code)] // This test only checks that macros is not panicking
-use evm_coder::{ToLog, execution::Result, solidity_interface, types::*, solidity, weight};
-use evm_coder::{types::Signature};
+use evm_coder::{
+ abi::AbiType, ToLog, execution::Result, solidity_interface, types::*, solidity, weight,
+};
pub struct Impls;
crates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/solidity_generation.rs
+++ b/crates/evm-coder/tests/solidity_generation.rs
@@ -14,8 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
-use evm_coder::{types::Signature};
+use evm_coder::{abi::AbiType, execution::Result, generate_stubgen, solidity_interface, types::*};
pub struct ERC20;
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -17,6 +17,7 @@
//! This module contains the implementation of pallet methods for evm.
use evm_coder::{
+ abi::AbiType,
solidity_interface, solidity, ToLog,
types::*,
execution::{Result, Error},
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -19,7 +19,11 @@
extern crate alloc;
use core::marker::PhantomData;
use evm_coder::{
- abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
+ abi::{AbiWriter, AbiType},
+ 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,7 +19,9 @@
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};
+use evm_coder::{
+ abi::AbiType, 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,7 +24,10 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ abi::AbiType, 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,7 +25,10 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ abi::AbiType, 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,7 +29,9 @@
convert::TryInto,
ops::Deref,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
+use evm_coder::{
+ abi::AbiType, ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight,
+};
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
pallets/unique/Cargo.tomldiffbeforeafterboth--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -35,6 +35,7 @@
try-runtime = ["frame-support/try-runtime"]
limit-testing = ["up-data-structs/limit-testing"]
stubgen = ["evm-coder/stubgen", "pallet-common/stubgen"]
+
################################################################################
# Standart Dependencies
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -18,14 +18,16 @@
use core::marker::PhantomData;
use ethereum as _;
-use evm_coder::{execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ abi::AbiType, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight,
+};
use frame_support::traits::Get;
use crate::Pallet;
use pallet_common::{
CollectionById,
dispatch::CollectionDispatch,
- erc::{static_property::key, CollectionHelpersEvents},
+ erc::{CollectionHelpersEvents, static_property::key},
Pallet as PalletCommon,
};
use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};