difftreelog
feat Add custum signature with unlimited nesting.
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, Group};24use quote::{quote, ToTokens};25use inflector::cases;26use std::fmt::Write;27use syn::{28 Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,29 MetaNameValue, PatType, PathArguments, ReturnType, Type,30 spanned::Spanned,31 parse::{Parse, ParseStream},32 parenthesized, Token, LitInt, LitStr,33};3435use crate::{36 fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,37 parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,38 snake_ident_to_screaming,39};4041struct Is {42 name: Ident,43 pascal_call_name: Ident,44 snake_call_name: Ident,45 via: Option<(Type, Ident)>,46 condition: Option<Expr>,47}48impl Is {49 fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {50 let name = &self.name;51 let pascal_call_name = &self.pascal_call_name;52 quote! {53 #name(#pascal_call_name #gen_ref)54 }55 }5657 fn expand_interface_id(&self) -> proc_macro2::TokenStream {58 let pascal_call_name = &self.pascal_call_name;59 quote! {60 interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());61 }62 }6364 fn expand_supports_interface(65 &self,66 generics: &proc_macro2::TokenStream,67 ) -> proc_macro2::TokenStream {68 let pascal_call_name = &self.pascal_call_name;69 let condition = self.condition.as_ref().map(|condition| {70 quote! {71 (#condition) &&72 }73 });74 quote! {75 #condition <#pascal_call_name #generics>::supports_interface(this, interface_id)76 }77 }7879 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {80 let name = &self.name;81 quote! {82 Self::#name(call) => call.weight()83 }84 }8586 fn expand_variant_call(87 &self,88 call_name: &proc_macro2::Ident,89 generics: &proc_macro2::TokenStream,90 ) -> proc_macro2::TokenStream {91 let name = &self.name;92 let pascal_call_name = &self.pascal_call_name;93 let via_typ = self94 .via95 .as_ref()96 .map(|(t, _)| quote! {#t})97 .unwrap_or_else(|| quote! {Self});98 let via_map = self99 .via100 .as_ref()101 .map(|(_, i)| quote! {.#i()})102 .unwrap_or_default();103 let condition = self.condition.as_ref().map(|condition| {104 quote! {105 if ({let this = &self; (#condition)})106 }107 });108 quote! {109 #call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {110 call,111 caller: c.caller,112 value: c.value,113 })114 }115 }116117 fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {118 let name = &self.name;119 let pascal_call_name = &self.pascal_call_name;120 quote! {121 if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {122 return Ok(Some(Self::#name(parsed_call)))123 }124 }125 }126127 fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {128 let pascal_call_name = &self.pascal_call_name;129 quote! {130 <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);131 }132 }133134 fn expand_event_generator(&self) -> proc_macro2::TokenStream {135 let name = &self.name;136 quote! {137 #name::generate_solidity_interface(tc, is_impl);138 }139 }140}141142#[derive(Default)]143struct IsList(Vec<Is>);144impl Parse for IsList {145 fn parse(input: ParseStream) -> syn::Result<Self> {146 let mut out = vec![];147 loop {148 if input.is_empty() {149 break;150 }151 let name = input.parse::<Ident>()?;152 let lookahead = input.lookahead1();153154 let mut condition: Option<Expr> = None;155 let mut via: Option<(Type, Ident)> = None;156157 if lookahead.peek(syn::token::Paren) {158 let contents;159 parenthesized!(contents in input);160 let input = contents;161162 while !input.is_empty() {163 let lookahead = input.lookahead1();164 if lookahead.peek(Token![if]) {165 input.parse::<Token![if]>()?;166 let contents;167 parenthesized!(contents in input);168 let contents = contents.parse::<Expr>()?;169170 if condition.replace(contents).is_some() {171 return Err(syn::Error::new(input.span(), "condition is already set"));172 }173 } else if lookahead.peek(kw::via) {174 input.parse::<kw::via>()?;175 let contents;176 parenthesized!(contents in input);177178 let method = contents.parse::<Ident>()?;179 contents.parse::<kw::returns>()?;180 let ty = contents.parse::<Type>()?;181182 if via.replace((ty, method)).is_some() {183 return Err(syn::Error::new(input.span(), "via is already set"));184 }185 } else {186 return Err(lookahead.error());187 }188189 if input.peek(Token![,]) {190 input.parse::<Token![,]>()?;191 } else if !input.is_empty() {192 return Err(syn::Error::new(input.span(), "expected end"));193 }194 }195 } else if lookahead.peek(Token![,]) || input.is_empty() {196 // Pass197 } else {198 return Err(lookahead.error());199 };200 out.push(Is {201 pascal_call_name: pascal_ident_to_call(&name),202 snake_call_name: pascal_ident_to_snake_call(&name),203 name,204 via,205 condition,206 });207 if input.peek(Token![,]) {208 input.parse::<Token![,]>()?;209 continue;210 } else {211 break;212 }213 }214 Ok(Self(out))215 }216}217218pub struct InterfaceInfo {219 name: Ident,220 is: IsList,221 inline_is: IsList,222 events: IsList,223 expect_selector: Option<u32>,224}225impl Parse for InterfaceInfo {226 fn parse(input: ParseStream) -> syn::Result<Self> {227 let mut name = None;228 let mut is = None;229 let mut inline_is = None;230 let mut events = None;231 let mut expect_selector = None;232 // TODO: create proc-macro to optimize proc-macro boilerplate? :D233 loop {234 let lookahead = input.lookahead1();235 if lookahead.peek(kw::name) {236 let k = input.parse::<kw::name>()?;237 input.parse::<Token![=]>()?;238 if name.replace(input.parse::<Ident>()?).is_some() {239 return Err(syn::Error::new(k.span(), "name is already set"));240 }241 } else if lookahead.peek(kw::is) {242 let k = input.parse::<kw::is>()?;243 let contents;244 parenthesized!(contents in input);245 if is.replace(contents.parse::<IsList>()?).is_some() {246 return Err(syn::Error::new(k.span(), "is is already set"));247 }248 } else if lookahead.peek(kw::inline_is) {249 let k = input.parse::<kw::inline_is>()?;250 let contents;251 parenthesized!(contents in input);252 if inline_is.replace(contents.parse::<IsList>()?).is_some() {253 return Err(syn::Error::new(k.span(), "inline_is is already set"));254 }255 } else if lookahead.peek(kw::events) {256 let k = input.parse::<kw::events>()?;257 let contents;258 parenthesized!(contents in input);259 if events.replace(contents.parse::<IsList>()?).is_some() {260 return Err(syn::Error::new(k.span(), "events is already set"));261 }262 } else if lookahead.peek(kw::expect_selector) {263 let k = input.parse::<kw::expect_selector>()?;264 input.parse::<Token![=]>()?;265 let value = input.parse::<LitInt>()?;266 if expect_selector267 .replace(value.base10_parse::<u32>()?)268 .is_some()269 {270 return Err(syn::Error::new(k.span(), "expect_selector is already set"));271 }272 } else if input.is_empty() {273 break;274 } else {275 return Err(lookahead.error());276 }277 if input.peek(Token![,]) {278 input.parse::<Token![,]>()?;279 } else {280 break;281 }282 }283 Ok(Self {284 name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,285 is: is.unwrap_or_default(),286 inline_is: inline_is.unwrap_or_default(),287 events: events.unwrap_or_default(),288 expect_selector,289 })290 }291}292293struct MethodInfo {294 rename_selector: Option<String>,295 hide: bool,296}297impl Parse for MethodInfo {298 fn parse(input: ParseStream) -> syn::Result<Self> {299 let mut rename_selector = None;300 let mut hide = false;301 while !input.is_empty() {302 let lookahead = input.lookahead1();303 if lookahead.peek(kw::rename_selector) {304 let k = input.parse::<kw::rename_selector>()?;305 input.parse::<Token![=]>()?;306 if rename_selector307 .replace(input.parse::<LitStr>()?.value())308 .is_some()309 {310 return Err(syn::Error::new(k.span(), "rename_selector is already set"));311 }312 } else if lookahead.peek(kw::hide) {313 input.parse::<kw::hide>()?;314 hide = true;315 } else {316 return Err(lookahead.error());317 }318319 if input.peek(Token![,]) {320 input.parse::<Token![,]>()?;321 } else if !input.is_empty() {322 return Err(syn::Error::new(input.span(), "expected end"));323 }324 }325 Ok(Self {326 rename_selector,327 hide,328 })329 }330}331332#[derive(Debug)]333enum AbiType {334 // type335 Plain(Ident),336 // (type1,type2)337 Tuple(Vec<AbiType>),338 // type[]339 Vec(Box<AbiType>),340 // type[20]341 Array(Box<AbiType>, usize),342}343impl AbiType {344 fn try_from(value: &Type) -> syn::Result<Self> {345 let value = Self::try_maybe_special_from(value)?;346 if value.is_special() {347 return Err(syn::Error::new(value.span(), "unexpected special type"));348 }349 Ok(value)350 }351 fn try_maybe_special_from(value: &Type) -> syn::Result<Self> {352 match value {353 Type::Array(arr) => {354 let wrapped = AbiType::try_from(&arr.elem)?;355 match &arr.len {356 Expr::Lit(l) => match &l.lit {357 Lit::Int(i) => {358 let num = i.base10_parse::<usize>()?;359 Ok(AbiType::Array(Box::new(wrapped), num as usize))360 }361 _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),362 },363 _ => Err(syn::Error::new(arr.len.span(), "should be literal")),364 }365 }366 Type::Path(_) => {367 let path = parse_path(value)?;368 let segment = parse_path_segment(path)?;369 if segment.ident == "Vec" {370 let args = match &segment.arguments {371 PathArguments::AngleBracketed(e) => e,372 _ => {373 return Err(syn::Error::new(374 segment.arguments.span(),375 "missing Vec generic",376 ))377 }378 };379 let args = &args.args;380 if args.len() != 1 {381 return Err(syn::Error::new(382 args.span(),383 "expected only one generic for vec",384 ));385 }386 let arg = args.first().expect("first arg");387388 let ty = match arg {389 GenericArgument::Type(ty) => ty,390 _ => {391 return Err(syn::Error::new(392 arg.span(),393 "expected first generic to be type",394 ))395 }396 };397398 let wrapped = AbiType::try_from(ty)?;399 Ok(Self::Vec(Box::new(wrapped)))400 } else {401 if !segment.arguments.is_empty() {402 return Err(syn::Error::new(403 segment.arguments.span(),404 "unexpected generic arguments for non-vec type",405 ));406 }407 Ok(Self::Plain(segment.ident.clone()))408 }409 }410 Type::Tuple(t) => {411 let mut out = Vec::with_capacity(t.elems.len());412 for el in t.elems.iter() {413 out.push(AbiType::try_from(el)?)414 }415 Ok(Self::Tuple(out))416 }417 _ => Err(syn::Error::new(418 value.span(),419 "unexpected type, only arrays, plain types and tuples are supported",420 )),421 }422 }423 fn is_value(&self) -> bool {424 matches!(self, Self::Plain(v) if v == "value")425 }426 fn is_caller(&self) -> bool {427 matches!(self, Self::Plain(v) if v == "caller")428 }429 fn is_special(&self) -> bool {430 self.is_caller() || self.is_value()431 }432 fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {433 match self {434 AbiType::Plain(t) => {435 write!(buf, "{}", t)436 }437 AbiType::Tuple(t) => {438 write!(buf, "(")?;439 for (i, t) in t.iter().enumerate() {440 if i != 0 {441 write!(buf, ",")?;442 }443 t.selector_ty_buf(buf)?;444 }445 write!(buf, ")")446 }447 AbiType::Vec(v) => {448 v.selector_ty_buf(buf)?;449 write!(buf, "[]")450 }451 AbiType::Array(v, len) => {452 v.selector_ty_buf(buf)?;453 write!(buf, "[{}]", len)454 }455 }456 }457 fn selector_ty(&self) -> String {458 let mut out = String::new();459 self.selector_ty_buf(&mut out).expect("no fmt error");460 out461 }462}463impl ToTokens for AbiType {464 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {465 match self {466 AbiType::Plain(t) => tokens.extend(quote! {#t}),467 AbiType::Tuple(t) => {468 tokens.extend(quote! {(469 #(#t),*470 )});471 }472 AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),473 AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),474 }475 }476}477478#[derive(Debug)]479struct MethodArg {480 name: Ident,481 camel_name: String,482 ty: AbiType,483}484impl MethodArg {485 fn try_from(value: &PatType) -> syn::Result<Self> {486 let name = parse_ident_from_pat(&value.pat)?.clone();487 Ok(Self {488 camel_name: cases::camelcase::to_camel_case(&name.to_string()),489 name,490 ty: AbiType::try_maybe_special_from(&value.ty)?,491 })492 }493 fn is_value(&self) -> bool {494 self.ty.is_value()495 }496 fn is_caller(&self) -> bool {497 self.ty.is_caller()498 }499 fn is_special(&self) -> bool {500 self.ty.is_special()501 }502 fn selector_ty(&self) -> String {503 assert!(!self.is_special());504 self.ty.selector_ty()505 }506507 fn expand_call_def(&self) -> proc_macro2::TokenStream {508 assert!(!self.is_special());509 let name = &self.name;510 let ty = &self.ty;511512 quote! {513 #name: #ty514 }515 }516517 fn expand_parse(&self) -> proc_macro2::TokenStream {518 assert!(!self.is_special());519 let name = &self.name;520 quote! {521 #name: reader.abi_read()?522 }523 }524525 fn expand_call_arg(&self) -> proc_macro2::TokenStream {526 if self.is_value() {527 quote! {528 c.value.clone()529 }530 } else if self.is_caller() {531 quote! {532 c.caller.clone()533 }534 } else {535 let name = &self.name;536 quote! {537 #name538 }539 }540 }541542 fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {543 let camel_name = &self.camel_name.to_string();544 let ty = &self.ty;545 quote! {546 <NamedArgument<#ty>>::new(#camel_name)547 }548 }549}550551#[derive(PartialEq)]552enum Mutability {553 Mutable,554 View,555 Pure,556}557558/// Group all keywords for this macro. Usage example:559/// #[solidity_interface(name = "B", inline_is(A))]560mod kw {561 syn::custom_keyword!(weight);562563 syn::custom_keyword!(via);564 syn::custom_keyword!(returns);565 syn::custom_keyword!(name);566 syn::custom_keyword!(is);567 syn::custom_keyword!(inline_is);568 syn::custom_keyword!(events);569 syn::custom_keyword!(expect_selector);570571 syn::custom_keyword!(rename_selector);572 syn::custom_keyword!(hide);573}574575/// Rust methods are parsed into this structure when Solidity code is generated576struct Method {577 name: Ident,578 camel_name: String,579 pascal_name: Ident,580 screaming_name: Ident,581 selector_str: String,582 selector: u32,583 hide: bool,584 args: Vec<MethodArg>,585 has_normal_args: bool,586 has_value_args: bool,587 mutability: Mutability,588 result: Type,589 weight: Option<Expr>,590 docs: Vec<String>,591}592impl Method {593 fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {594 let mut info = MethodInfo {595 rename_selector: None,596 hide: false,597 };598 let mut docs = Vec::new();599 let mut weight = None;600 for attr in &value.attrs {601 let ident = parse_ident_from_path(&attr.path, false)?;602 if ident == "solidity" {603 info = attr.parse_args::<MethodInfo>()?;604 } else if ident == "doc" {605 let args = attr.parse_meta().unwrap();606 let value = match args {607 Meta::NameValue(MetaNameValue {608 lit: Lit::Str(str), ..609 }) => str.value(),610 _ => unreachable!(),611 };612 docs.push(value);613 } else if ident == "weight" {614 weight = Some(attr.parse_args::<Expr>()?);615 }616 }617 let ident = &value.sig.ident;618 let ident_str = ident.to_string();619 if !cases::snakecase::is_snake_case(&ident_str) {620 return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));621 }622623 let mut mutability = Mutability::Pure;624625 if let Some(FnArg::Receiver(receiver)) = value626 .sig627 .inputs628 .iter()629 .find(|arg| matches!(arg, FnArg::Receiver(_)))630 {631 if receiver.reference.is_none() {632 return Err(syn::Error::new(633 receiver.span(),634 "receiver should be by ref",635 ));636 }637 if receiver.mutability.is_some() {638 mutability = Mutability::Mutable;639 } else {640 mutability = Mutability::View;641 }642 }643 let mut args = Vec::new();644 for typ in value645 .sig646 .inputs647 .iter()648 .filter(|arg| matches!(arg, FnArg::Typed(_)))649 {650 let typ = match typ {651 FnArg::Typed(typ) => typ,652 _ => unreachable!(),653 };654 args.push(MethodArg::try_from(typ)?);655 }656657 if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {658 return Err(syn::Error::new(659 args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),660 "payable function should be mutable",661 ));662 }663664 let result = match &value.sig.output {665 ReturnType::Type(_, ty) => ty,666 _ => 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)")),667 };668 let result = parse_result_ok(result)?;669670 let camel_name = info671 .rename_selector672 .unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));673 let mut selector_str = camel_name.clone();674 selector_str.push('(');675 let mut has_normal_args = false;676 for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {677 if i != 0 {678 selector_str.push(',');679 }680 write!(selector_str, "{}", arg.selector_ty()).unwrap();681 has_normal_args = true;682 }683 let has_value_args = args.iter().any(|a| a.is_value());684 selector_str.push(')');685 let selector = fn_selector_str(&selector_str);686687 Ok(Self {688 name: ident.clone(),689 camel_name,690 pascal_name: snake_ident_to_pascal(ident),691 screaming_name: snake_ident_to_screaming(ident),692 selector_str,693 selector,694 hide: info.hide,695 args,696 has_normal_args,697 has_value_args,698 mutability,699 result: result.clone(),700 weight,701 docs,702 })703 }704 fn expand_call_def(&self) -> proc_macro2::TokenStream {705 let defs = self706 .args707 .iter()708 .filter(|a| !a.is_special())709 .map(|a| a.expand_call_def());710 let pascal_name = &self.pascal_name;711 let docs = &self.docs;712713 if self.has_normal_args {714 quote! {715 #(#[doc = #docs])*716 #[allow(missing_docs)]717 #pascal_name {718 #(719 #defs,720 )*721 }722 }723 } else {724 quote! {#pascal_name}725 }726 }727728 fn expand_selector(&self) -> proc_macro2::TokenStream {729 let custom_signature = self.expand_custom_signature();730 quote! {731 {732 let a = ::evm_coder::sha3_const::Keccak256::new()733 .update(#custom_signature.as_bytes())734 .finalize();735 [a[0], a[1], a[2], a[3]]736 }737 }738 }739740 fn expand_const(&self) -> proc_macro2::TokenStream {741 let screaming_name = &self.screaming_name;742 let selector_str = &self.selector_str;743 let selector = &self.expand_selector();744 quote! {745 #[doc = #selector_str]746 const #screaming_name: ::evm_coder::types::bytes4 = #selector;747 }748 }749750 fn expand_interface_id(&self) -> proc_macro2::TokenStream {751 let screaming_name = &self.screaming_name;752 quote! {753 interface_id ^= u32::from_be_bytes(Self::#screaming_name);754 }755 }756757 fn expand_parse(&self) -> proc_macro2::TokenStream {758 let pascal_name = &self.pascal_name;759 let screaming_name = &self.screaming_name;760 if self.has_normal_args {761 let parsers = self762 .args763 .iter()764 .filter(|a| !a.is_special())765 .map(|a| a.expand_parse());766 quote! {767 Self::#screaming_name => return Ok(Some(Self::#pascal_name {768 #(769 #parsers,770 )*771 }))772 }773 } else {774 quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }775 }776 }777778 fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {779 let pascal_name = &self.pascal_name;780 let name = &self.name;781782 let matcher = if self.has_normal_args {783 let names = self784 .args785 .iter()786 .filter(|a| !a.is_special())787 .map(|a| &a.name);788789 quote! {{790 #(791 #names,792 )*793 }}794 } else {795 quote! {}796 };797798 let receiver = match self.mutability {799 Mutability::Mutable | Mutability::View => quote! {self.},800 Mutability::Pure => quote! {Self::},801 };802 let args = self.args.iter().map(|a| a.expand_call_arg());803804 quote! {805 #call_name::#pascal_name #matcher => {806 let result = #receiver #name(807 #(808 #args,809 )*810 )?;811 (&result).to_result()812 }813 }814 }815816 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {817 let pascal_name = &self.pascal_name;818 if let Some(weight) = &self.weight {819 let matcher = if self.has_normal_args {820 let names = self821 .args822 .iter()823 .filter(|a| !a.is_special())824 .map(|a| &a.name);825826 quote! {{827 #(828 #names,829 )*830 }}831 } else {832 quote! {}833 };834 quote! {835 Self::#pascal_name #matcher => (#weight).into()836 }837 } else {838 let matcher = if self.has_normal_args {839 quote! {{..}}840 } else {841 quote! {}842 };843 quote! {844 Self::#pascal_name #matcher => ().into()845 }846 }847 }848849 fn expand_custom_signature(&self) -> proc_macro2::TokenStream {850 let mut first_comma = true;851 let mut custom_signature = TokenStream::new();852 let mut template = self.camel_name.clone() + "(";853 self.args854 .iter()855 .filter_map(|a| {856 if a.is_special() {857 return None;858 };859860 match a.ty {861 AbiType::Plain(ref ident) => Some(ident),862 _ => None,863 }864 })865 .for_each(|ident| {866 if !first_comma {867 custom_signature.extend(quote!(,));868 template.push(',');869 } else {870 first_comma = false;871 };872 template.push_str("{}");873 let ident_str = ident.to_string();874 match ident_str.as_str() {875 "address" | "uint8" | "uint16" | "uint32" | "uint64" | "uint128"876 | "uint256" | "bytes4" | "topic" | "string" | "bytes" | "void" | "caller"877 | "bool" | "" => {878 custom_signature.extend(quote!(#ident_str));879 }880 _ => {881 custom_signature.extend(quote! {882 #ident::SIGNATURE_STRING883 });884 }885 }886 });887888 template.push(')');889 let mut template = quote!(#template);890 template.extend(quote!(,));891 template.extend(custom_signature);892 let custom_signature_group = Group::new(proc_macro2::Delimiter::Parenthesis, template);893 let mut custom_signature = quote! {894 ::evm_coder::const_format::formatcp!895 };896 custom_signature.extend(custom_signature_group.to_token_stream());897898 println!("!!!!! {}", custom_signature);899 custom_signature900 }901902 fn expand_solidity_function(&self) -> proc_macro2::TokenStream {903 let camel_name = &self.camel_name;904 let mutability = match self.mutability {905 Mutability::Mutable => quote! {SolidityMutability::Mutable},906 Mutability::View => quote! { SolidityMutability::View },907 Mutability::Pure => quote! {SolidityMutability::Pure},908 };909 let result = &self.result;910911 let args = self912 .args913 .iter()914 .filter(|a| !a.is_special())915 .map(MethodArg::expand_solidity_argument);916 let docs = &self.docs;917 let selector_str = &self.selector_str;918 let selector = &self.expand_selector();919 let hide = self.hide;920 let custom_signature = self.expand_custom_signature();921 let is_payable = self.has_value_args;922 quote! {923 SolidityFunction {924 docs: &[#(#docs),*],925 selector_str: #selector_str,926 hide: #hide,927 selector: u32::from_be_bytes(#selector),928 custom_signature: #custom_signature,929 name: #camel_name,930 mutability: #mutability,931 is_payable: #is_payable,932 args: (933 #(934 #args,935 )*936 ),937 result: <UnnamedArgument<#result>>::default(),938 }939 }940 }941}942943fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {944 if gen.params.is_empty() {945 return quote! {};946 }947 let params = gen.params.iter().map(|p| match p {948 syn::GenericParam::Type(id) => {949 let v = &id.ident;950 quote! {#v}951 }952 syn::GenericParam::Lifetime(lt) => {953 let v = <.lifetime;954 quote! {#v}955 }956 syn::GenericParam::Const(c) => {957 let i = &c.ident;958 quote! {#i}959 }960 });961 quote! { #(#params),* }962}963fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {964 if gen.params.is_empty() {965 return quote! {};966 }967 let list = generics_list(gen);968 quote! { <#list> }969}970fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {971 let list = generics_list(gen);972 if gen.params.len() == 1 {973 quote! {#list}974 } else {975 quote! { (#list) }976 }977}978979pub struct SolidityInterface {980 generics: Generics,981 name: Box<syn::Type>,982 info: InterfaceInfo,983 methods: Vec<Method>,984 docs: Vec<String>,985}986impl SolidityInterface {987 pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {988 let mut methods = Vec::new();989990 for item in &value.items {991 if let ImplItem::Method(method) = item {992 methods.push(Method::try_from(method)?)993 }994 }995 let mut docs = vec![];996 for attr in &value.attrs {997 let ident = parse_ident_from_path(&attr.path, false)?;998 if ident == "doc" {999 let args = attr.parse_meta().unwrap();1000 let value = match args {1001 Meta::NameValue(MetaNameValue {1002 lit: Lit::Str(str), ..1003 }) => str.value(),1004 _ => unreachable!(),1005 };1006 docs.push(value);1007 }1008 }1009 Ok(Self {1010 generics: value.generics.clone(),1011 name: value.self_ty.clone(),1012 info,1013 methods,1014 docs,1015 })1016 }1017 pub fn expand(self) -> proc_macro2::TokenStream {1018 let name = self.name;10191020 let solidity_name = self.info.name.to_string();1021 let call_name = pascal_ident_to_call(&self.info.name);1022 let generics = self.generics;1023 let gen_ref = generics_reference(&generics);1024 let gen_data = generics_data(&generics);1025 let gen_where = &generics.where_clause;10261027 let call_sub = self1028 .info1029 .inline_is1030 .01031 .iter()1032 .chain(self.info.is.0.iter())1033 .map(|c| Is::expand_call_def(c, &gen_ref));1034 let call_parse = self1035 .info1036 .inline_is1037 .01038 .iter()1039 .chain(self.info.is.0.iter())1040 .map(|is| Is::expand_parse(is, &gen_ref));1041 let call_variants = self1042 .info1043 .inline_is1044 .01045 .iter()1046 .chain(self.info.is.0.iter())1047 .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));1048 let weight_variants = self1049 .info1050 .inline_is1051 .01052 .iter()1053 .chain(self.info.is.0.iter())1054 .map(Is::expand_variant_weight);10551056 let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);1057 let supports_interface = self1058 .info1059 .is1060 .01061 .iter()1062 .map(|is| Is::expand_supports_interface(is, &gen_ref));10631064 let calls = self.methods.iter().map(Method::expand_call_def);1065 let consts = self.methods.iter().map(Method::expand_const);1066 let interface_id = self.methods.iter().map(Method::expand_interface_id);1067 let parsers = self.methods.iter().map(Method::expand_parse);1068 let call_variants_this = self1069 .methods1070 .iter()1071 .map(|m| Method::expand_variant_call(m, &call_name));1072 let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);1073 let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);10741075 // TODO: Inline inline_is1076 let solidity_is = self1077 .info1078 .is1079 .01080 .iter()1081 .chain(self.info.inline_is.0.iter())1082 .map(|is| is.name.to_string());1083 let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());1084 let solidity_generators = self1085 .info1086 .is1087 .01088 .iter()1089 .chain(self.info.inline_is.0.iter())1090 .map(|is| Is::expand_generator(is, &gen_ref));1091 let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);10921093 let docs = &self.docs;10941095 if let Some(expect_selector) = &self.info.expect_selector {1096 if !self.info.inline_is.0.is_empty() {1097 return syn::Error::new(1098 name.span(),1099 "expect_selector is not compatible with inline_is",1100 )1101 .to_compile_error();1102 }1103 let selector = self1104 .methods1105 .iter()1106 .map(|m| m.selector)1107 .fold(0, |a, b| a ^ b);11081109 if *expect_selector != selector {1110 let mut methods = String::new();1111 for meth in self.methods.iter() {1112 write!(methods, "\n- {}", meth.selector_str).expect("write to string");1113 }1114 return syn::Error::new(name.span(), format!("expected selector mismatch, expected {expect_selector:0>8x}, but implementation has {selector:0>8x}{methods}")).to_compile_error();1115 }1116 }1117 // let methods = self.methods.iter().map(Method::solidity_def);11181119 quote! {1120 #[derive(Debug)]1121 #(#[doc = #docs])*1122 pub enum #call_name #gen_ref {1123 /// Inherited method1124 ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),1125 #(1126 #calls,1127 )*1128 #(1129 #call_sub,1130 )*1131 }1132 impl #gen_ref #call_name #gen_ref {1133 #(1134 #consts1135 )*1136 /// Return this call ERC165 selector1137 pub fn interface_id() -> ::evm_coder::types::bytes4 {1138 let mut interface_id = 0;1139 #(#interface_id)*1140 #(#inline_interface_id)*1141 u32::to_be_bytes(interface_id)1142 }1143 /// Generate solidity definitions for methods described in this interface1144 pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {1145 use evm_coder::solidity::*;1146 use core::fmt::Write;1147 let interface = SolidityInterface {1148 docs: &[#(#docs),*],1149 name: #solidity_name,1150 selector: Self::interface_id(),1151 is: &["Dummy", "ERC165", #(1152 #solidity_is,1153 )* #(1154 #solidity_events_is,1155 )* ],1156 functions: (#(1157 #solidity_functions,1158 )*),1159 };11601161 let mut out = ::evm_coder::types::string::new();1162 if #solidity_name.starts_with("Inline") {1163 out.push_str("/// @dev inlined interface\n");1164 }1165 let _ = interface.format(is_impl, &mut out, tc);1166 tc.collect(out);1167 #(1168 #solidity_event_generators1169 )*1170 #(1171 #solidity_generators1172 )*1173 if is_impl {1174 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());1175 } else {1176 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());1177 }1178 }1179 }1180 impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1181 fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1182 use ::evm_coder::abi::AbiRead;1183 match method_id {1184 ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1185 ::evm_coder::ERC165Call::parse(method_id, reader)?1186 .map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1187 ),1188 #(1189 #parsers,1190 )*1191 _ => {},1192 }1193 #(1194 #call_parse1195 )else*1196 return Ok(None);1197 }1198 }1199 impl #generics #call_name #gen_ref1200 #gen_where1201 {1202 /// Is this contract implements specified ERC165 selector1203 pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1204 interface_id != u32::to_be_bytes(0xffffff) && (1205 interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1206 interface_id == Self::interface_id()1207 #(1208 || #supports_interface1209 )*1210 )1211 }1212 }1213 impl #generics ::evm_coder::Weighted for #call_name #gen_ref1214 #gen_where1215 {1216 #[allow(unused_variables)]1217 fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1218 match self {1219 #(1220 #weight_variants,1221 )*1222 // TODO: It should be very cheap, but not free1223 Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1224 #(1225 #weight_variants_this,1226 )*1227 }1228 }1229 }1230 impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1231 #gen_where1232 {1233 #[allow(unreachable_code)] // In case of no inner calls1234 fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1235 use ::evm_coder::abi::AbiWrite;1236 match c.call {1237 #(1238 #call_variants,1239 )*1240 #call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1241 let mut writer = ::evm_coder::abi::AbiWriter::default();1242 writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1243 return Ok(writer.into());1244 }1245 _ => {},1246 }1247 let mut writer = ::evm_coder::abi::AbiWriter::default();1248 match c.call {1249 #(1250 #call_variants_this,1251 )*1252 _ => Err(::evm_coder::execution::Error::from("method is not available").into()),1253 }1254 }1255 }1256 }1257 }1258}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, Group};24use quote::{quote, ToTokens, format_ident};25use inflector::cases;26use std::fmt::Write;27use syn::{28 Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,29 MetaNameValue, PatType, PathArguments, ReturnType, Type,30 spanned::Spanned,31 parse::{Parse, ParseStream},32 parenthesized, Token, LitInt, LitStr,33};3435use crate::{36 fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,37 parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,38 snake_ident_to_screaming,39};4041struct Is {42 name: Ident,43 pascal_call_name: Ident,44 snake_call_name: Ident,45 via: Option<(Type, Ident)>,46 condition: Option<Expr>,47}48impl Is {49 fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {50 let name = &self.name;51 let pascal_call_name = &self.pascal_call_name;52 quote! {53 #name(#pascal_call_name #gen_ref)54 }55 }5657 fn expand_interface_id(&self) -> proc_macro2::TokenStream {58 let pascal_call_name = &self.pascal_call_name;59 quote! {60 interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());61 }62 }6364 fn expand_supports_interface(65 &self,66 generics: &proc_macro2::TokenStream,67 ) -> proc_macro2::TokenStream {68 let pascal_call_name = &self.pascal_call_name;69 let condition = self.condition.as_ref().map(|condition| {70 quote! {71 (#condition) &&72 }73 });74 quote! {75 #condition <#pascal_call_name #generics>::supports_interface(this, interface_id)76 }77 }7879 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {80 let name = &self.name;81 quote! {82 Self::#name(call) => call.weight()83 }84 }8586 fn expand_variant_call(87 &self,88 call_name: &proc_macro2::Ident,89 generics: &proc_macro2::TokenStream,90 ) -> proc_macro2::TokenStream {91 let name = &self.name;92 let pascal_call_name = &self.pascal_call_name;93 let via_typ = self94 .via95 .as_ref()96 .map(|(t, _)| quote! {#t})97 .unwrap_or_else(|| quote! {Self});98 let via_map = self99 .via100 .as_ref()101 .map(|(_, i)| quote! {.#i()})102 .unwrap_or_default();103 let condition = self.condition.as_ref().map(|condition| {104 quote! {105 if ({let this = &self; (#condition)})106 }107 });108 quote! {109 #call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {110 call,111 caller: c.caller,112 value: c.value,113 })114 }115 }116117 fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {118 let name = &self.name;119 let pascal_call_name = &self.pascal_call_name;120 quote! {121 if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {122 return Ok(Some(Self::#name(parsed_call)))123 }124 }125 }126127 fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {128 let pascal_call_name = &self.pascal_call_name;129 quote! {130 <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);131 }132 }133134 fn expand_event_generator(&self) -> proc_macro2::TokenStream {135 let name = &self.name;136 quote! {137 #name::generate_solidity_interface(tc, is_impl);138 }139 }140}141142#[derive(Default)]143struct IsList(Vec<Is>);144impl Parse for IsList {145 fn parse(input: ParseStream) -> syn::Result<Self> {146 let mut out = vec![];147 loop {148 if input.is_empty() {149 break;150 }151 let name = input.parse::<Ident>()?;152 let lookahead = input.lookahead1();153154 let mut condition: Option<Expr> = None;155 let mut via: Option<(Type, Ident)> = None;156157 if lookahead.peek(syn::token::Paren) {158 let contents;159 parenthesized!(contents in input);160 let input = contents;161162 while !input.is_empty() {163 let lookahead = input.lookahead1();164 if lookahead.peek(Token![if]) {165 input.parse::<Token![if]>()?;166 let contents;167 parenthesized!(contents in input);168 let contents = contents.parse::<Expr>()?;169170 if condition.replace(contents).is_some() {171 return Err(syn::Error::new(input.span(), "condition is already set"));172 }173 } else if lookahead.peek(kw::via) {174 input.parse::<kw::via>()?;175 let contents;176 parenthesized!(contents in input);177178 let method = contents.parse::<Ident>()?;179 contents.parse::<kw::returns>()?;180 let ty = contents.parse::<Type>()?;181182 if via.replace((ty, method)).is_some() {183 return Err(syn::Error::new(input.span(), "via is already set"));184 }185 } else {186 return Err(lookahead.error());187 }188189 if input.peek(Token![,]) {190 input.parse::<Token![,]>()?;191 } else if !input.is_empty() {192 return Err(syn::Error::new(input.span(), "expected end"));193 }194 }195 } else if lookahead.peek(Token![,]) || input.is_empty() {196 // Pass197 } else {198 return Err(lookahead.error());199 };200 out.push(Is {201 pascal_call_name: pascal_ident_to_call(&name),202 snake_call_name: pascal_ident_to_snake_call(&name),203 name,204 via,205 condition,206 });207 if input.peek(Token![,]) {208 input.parse::<Token![,]>()?;209 continue;210 } else {211 break;212 }213 }214 Ok(Self(out))215 }216}217218pub struct InterfaceInfo {219 name: Ident,220 is: IsList,221 inline_is: IsList,222 events: IsList,223 expect_selector: Option<u32>,224}225impl Parse for InterfaceInfo {226 fn parse(input: ParseStream) -> syn::Result<Self> {227 let mut name = None;228 let mut is = None;229 let mut inline_is = None;230 let mut events = None;231 let mut expect_selector = None;232 // TODO: create proc-macro to optimize proc-macro boilerplate? :D233 loop {234 let lookahead = input.lookahead1();235 if lookahead.peek(kw::name) {236 let k = input.parse::<kw::name>()?;237 input.parse::<Token![=]>()?;238 if name.replace(input.parse::<Ident>()?).is_some() {239 return Err(syn::Error::new(k.span(), "name is already set"));240 }241 } else if lookahead.peek(kw::is) {242 let k = input.parse::<kw::is>()?;243 let contents;244 parenthesized!(contents in input);245 if is.replace(contents.parse::<IsList>()?).is_some() {246 return Err(syn::Error::new(k.span(), "is is already set"));247 }248 } else if lookahead.peek(kw::inline_is) {249 let k = input.parse::<kw::inline_is>()?;250 let contents;251 parenthesized!(contents in input);252 if inline_is.replace(contents.parse::<IsList>()?).is_some() {253 return Err(syn::Error::new(k.span(), "inline_is is already set"));254 }255 } else if lookahead.peek(kw::events) {256 let k = input.parse::<kw::events>()?;257 let contents;258 parenthesized!(contents in input);259 if events.replace(contents.parse::<IsList>()?).is_some() {260 return Err(syn::Error::new(k.span(), "events is already set"));261 }262 } else if lookahead.peek(kw::expect_selector) {263 let k = input.parse::<kw::expect_selector>()?;264 input.parse::<Token![=]>()?;265 let value = input.parse::<LitInt>()?;266 if expect_selector267 .replace(value.base10_parse::<u32>()?)268 .is_some()269 {270 return Err(syn::Error::new(k.span(), "expect_selector is already set"));271 }272 } else if input.is_empty() {273 break;274 } else {275 return Err(lookahead.error());276 }277 if input.peek(Token![,]) {278 input.parse::<Token![,]>()?;279 } else {280 break;281 }282 }283 Ok(Self {284 name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,285 is: is.unwrap_or_default(),286 inline_is: inline_is.unwrap_or_default(),287 events: events.unwrap_or_default(),288 expect_selector,289 })290 }291}292293struct MethodInfo {294 rename_selector: Option<String>,295 hide: bool,296}297impl Parse for MethodInfo {298 fn parse(input: ParseStream) -> syn::Result<Self> {299 let mut rename_selector = None;300 let mut hide = false;301 while !input.is_empty() {302 let lookahead = input.lookahead1();303 if lookahead.peek(kw::rename_selector) {304 let k = input.parse::<kw::rename_selector>()?;305 input.parse::<Token![=]>()?;306 if rename_selector307 .replace(input.parse::<LitStr>()?.value())308 .is_some()309 {310 return Err(syn::Error::new(k.span(), "rename_selector is already set"));311 }312 } else if lookahead.peek(kw::hide) {313 input.parse::<kw::hide>()?;314 hide = true;315 } else {316 return Err(lookahead.error());317 }318319 if input.peek(Token![,]) {320 input.parse::<Token![,]>()?;321 } else if !input.is_empty() {322 return Err(syn::Error::new(input.span(), "expected end"));323 }324 }325 Ok(Self {326 rename_selector,327 hide,328 })329 }330}331332#[derive(Debug)]333enum AbiType {334 // type335 Plain(Ident),336 // (type1,type2)337 Tuple(Vec<AbiType>),338 // type[]339 Vec(Box<AbiType>),340 // type[20]341 Array(Box<AbiType>, usize),342}343impl AbiType {344 fn try_from(value: &Type) -> syn::Result<Self> {345 let value = Self::try_maybe_special_from(value)?;346 if value.is_special() {347 return Err(syn::Error::new(value.span(), "unexpected special type"));348 }349 Ok(value)350 }351 fn try_maybe_special_from(value: &Type) -> syn::Result<Self> {352 match value {353 Type::Array(arr) => {354 let wrapped = AbiType::try_from(&arr.elem)?;355 match &arr.len {356 Expr::Lit(l) => match &l.lit {357 Lit::Int(i) => {358 let num = i.base10_parse::<usize>()?;359 Ok(AbiType::Array(Box::new(wrapped), num as usize))360 }361 _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),362 },363 _ => Err(syn::Error::new(arr.len.span(), "should be literal")),364 }365 }366 Type::Path(_) => {367 let path = parse_path(value)?;368 let segment = parse_path_segment(path)?;369 if segment.ident == "Vec" {370 let args = match &segment.arguments {371 PathArguments::AngleBracketed(e) => e,372 _ => {373 return Err(syn::Error::new(374 segment.arguments.span(),375 "missing Vec generic",376 ))377 }378 };379 let args = &args.args;380 if args.len() != 1 {381 return Err(syn::Error::new(382 args.span(),383 "expected only one generic for vec",384 ));385 }386 let arg = args.first().expect("first arg");387388 let ty = match arg {389 GenericArgument::Type(ty) => ty,390 _ => {391 return Err(syn::Error::new(392 arg.span(),393 "expected first generic to be type",394 ))395 }396 };397398 let wrapped = AbiType::try_from(ty)?;399 Ok(Self::Vec(Box::new(wrapped)))400 } else {401 if !segment.arguments.is_empty() {402 return Err(syn::Error::new(403 segment.arguments.span(),404 "unexpected generic arguments for non-vec type",405 ));406 }407 Ok(Self::Plain(segment.ident.clone()))408 }409 }410 Type::Tuple(t) => {411 let mut out = Vec::with_capacity(t.elems.len());412 for el in t.elems.iter() {413 out.push(AbiType::try_from(el)?)414 }415 Ok(Self::Tuple(out))416 }417 _ => Err(syn::Error::new(418 value.span(),419 "unexpected type, only arrays, plain types and tuples are supported",420 )),421 }422 }423 fn is_value(&self) -> bool {424 matches!(self, Self::Plain(v) if v == "value")425 }426 fn is_caller(&self) -> bool {427 matches!(self, Self::Plain(v) if v == "caller")428 }429 fn is_special(&self) -> bool {430 self.is_caller() || self.is_value()431 }432 fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {433 match self {434 AbiType::Plain(t) => {435 write!(buf, "{}", t)436 }437 AbiType::Tuple(t) => {438 write!(buf, "(")?;439 for (i, t) in t.iter().enumerate() {440 if i != 0 {441 write!(buf, ",")?;442 }443 t.selector_ty_buf(buf)?;444 }445 write!(buf, ")")446 }447 AbiType::Vec(v) => {448 v.selector_ty_buf(buf)?;449 write!(buf, "[]")450 }451 AbiType::Array(v, len) => {452 v.selector_ty_buf(buf)?;453 write!(buf, "[{}]", len)454 }455 }456 }457 fn selector_ty(&self) -> String {458 let mut out = String::new();459 self.selector_ty_buf(&mut out).expect("no fmt error");460 out461 }462}463impl ToTokens for AbiType {464 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {465 match self {466 AbiType::Plain(t) => tokens.extend(quote! {#t}),467 AbiType::Tuple(t) => {468 tokens.extend(quote! {(469 #(#t),*470 )});471 }472 AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),473 AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),474 }475 }476}477478#[derive(Debug)]479struct MethodArg {480 name: Ident,481 camel_name: String,482 ty: AbiType,483}484impl MethodArg {485 fn try_from(value: &PatType) -> syn::Result<Self> {486 let name = parse_ident_from_pat(&value.pat)?.clone();487 Ok(Self {488 camel_name: cases::camelcase::to_camel_case(&name.to_string()),489 name,490 ty: AbiType::try_maybe_special_from(&value.ty)?,491 })492 }493 fn is_value(&self) -> bool {494 self.ty.is_value()495 }496 fn is_caller(&self) -> bool {497 self.ty.is_caller()498 }499 fn is_special(&self) -> bool {500 self.ty.is_special()501 }502 fn selector_ty(&self) -> String {503 assert!(!self.is_special());504 self.ty.selector_ty()505 }506507 fn expand_call_def(&self) -> proc_macro2::TokenStream {508 assert!(!self.is_special());509 let name = &self.name;510 let ty = &self.ty;511512 quote! {513 #name: #ty514 }515 }516517 fn expand_parse(&self) -> proc_macro2::TokenStream {518 assert!(!self.is_special());519 let name = &self.name;520 quote! {521 #name: reader.abi_read()?522 }523 }524525 fn expand_call_arg(&self) -> proc_macro2::TokenStream {526 if self.is_value() {527 quote! {528 c.value.clone()529 }530 } else if self.is_caller() {531 quote! {532 c.caller.clone()533 }534 } else {535 let name = &self.name;536 quote! {537 #name538 }539 }540 }541542 fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {543 let camel_name = &self.camel_name.to_string();544 let ty = &self.ty;545 quote! {546 <NamedArgument<#ty>>::new(#camel_name)547 }548 }549}550551#[derive(PartialEq)]552enum Mutability {553 Mutable,554 View,555 Pure,556}557558/// Group all keywords for this macro. Usage example:559/// #[solidity_interface(name = "B", inline_is(A))]560mod kw {561 syn::custom_keyword!(weight);562563 syn::custom_keyword!(via);564 syn::custom_keyword!(returns);565 syn::custom_keyword!(name);566 syn::custom_keyword!(is);567 syn::custom_keyword!(inline_is);568 syn::custom_keyword!(events);569 syn::custom_keyword!(expect_selector);570571 syn::custom_keyword!(rename_selector);572 syn::custom_keyword!(hide);573}574575/// Rust methods are parsed into this structure when Solidity code is generated576struct Method {577 name: Ident,578 camel_name: String,579 pascal_name: Ident,580 screaming_name: Ident,581 selector_str: String,582 selector: u32,583 hide: bool,584 args: Vec<MethodArg>,585 has_normal_args: bool,586 has_value_args: bool,587 mutability: Mutability,588 result: Type,589 weight: Option<Expr>,590 docs: Vec<String>,591}592impl Method {593 fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {594 let mut info = MethodInfo {595 rename_selector: None,596 hide: false,597 };598 let mut docs = Vec::new();599 let mut weight = None;600 for attr in &value.attrs {601 let ident = parse_ident_from_path(&attr.path, false)?;602 if ident == "solidity" {603 info = attr.parse_args::<MethodInfo>()?;604 } else if ident == "doc" {605 let args = attr.parse_meta().unwrap();606 let value = match args {607 Meta::NameValue(MetaNameValue {608 lit: Lit::Str(str), ..609 }) => str.value(),610 _ => unreachable!(),611 };612 docs.push(value);613 } else if ident == "weight" {614 weight = Some(attr.parse_args::<Expr>()?);615 }616 }617 let ident = &value.sig.ident;618 let ident_str = ident.to_string();619 if !cases::snakecase::is_snake_case(&ident_str) {620 return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));621 }622623 let mut mutability = Mutability::Pure;624625 if let Some(FnArg::Receiver(receiver)) = value626 .sig627 .inputs628 .iter()629 .find(|arg| matches!(arg, FnArg::Receiver(_)))630 {631 if receiver.reference.is_none() {632 return Err(syn::Error::new(633 receiver.span(),634 "receiver should be by ref",635 ));636 }637 if receiver.mutability.is_some() {638 mutability = Mutability::Mutable;639 } else {640 mutability = Mutability::View;641 }642 }643 let mut args = Vec::new();644 for typ in value645 .sig646 .inputs647 .iter()648 .filter(|arg| matches!(arg, FnArg::Typed(_)))649 {650 let typ = match typ {651 FnArg::Typed(typ) => typ,652 _ => unreachable!(),653 };654 args.push(MethodArg::try_from(typ)?);655 }656657 if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {658 return Err(syn::Error::new(659 args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),660 "payable function should be mutable",661 ));662 }663664 let result = match &value.sig.output {665 ReturnType::Type(_, ty) => ty,666 _ => 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)")),667 };668 let result = parse_result_ok(result)?;669670 let camel_name = info671 .rename_selector672 .unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));673 let mut selector_str = camel_name.clone();674 selector_str.push('(');675 let mut has_normal_args = false;676 for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {677 if i != 0 {678 selector_str.push(',');679 }680 write!(selector_str, "{}", arg.selector_ty()).unwrap();681 has_normal_args = true;682 }683 let has_value_args = args.iter().any(|a| a.is_value());684 selector_str.push(')');685 let selector = fn_selector_str(&selector_str);686687 Ok(Self {688 name: ident.clone(),689 camel_name,690 pascal_name: snake_ident_to_pascal(ident),691 screaming_name: snake_ident_to_screaming(ident),692 selector_str,693 selector,694 hide: info.hide,695 args,696 has_normal_args,697 has_value_args,698 mutability,699 result: result.clone(),700 weight,701 docs,702 })703 }704 fn expand_call_def(&self) -> proc_macro2::TokenStream {705 let defs = self706 .args707 .iter()708 .filter(|a| !a.is_special())709 .map(|a| a.expand_call_def());710 let pascal_name = &self.pascal_name;711 let docs = &self.docs;712713 if self.has_normal_args {714 quote! {715 #(#[doc = #docs])*716 #[allow(missing_docs)]717 #pascal_name {718 #(719 #defs,720 )*721 }722 }723 } else {724 quote! {#pascal_name}725 }726 }727728 fn expand_const(&self) -> proc_macro2::TokenStream {729 let screaming_name = &self.screaming_name;730 let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);731 let selector_str = &self.selector_str;732 let custom_signature = self.expand_custom_signature();733 quote! {734 const #screaming_name_signature: ::evm_coder::custom_signature::FunctionSignature = #custom_signature;735 #[doc = #selector_str]736 const #screaming_name: ::evm_coder::types::bytes4 = {737 let a = ::evm_coder::sha3_const::Keccak256::new()738 .update_with_size(&Self::#screaming_name_signature.signature, Self::#screaming_name_signature.signature_len)739 .finalize();740 [a[0], a[1], a[2], a[3]]741 };742 }743 }744745 fn expand_interface_id(&self) -> proc_macro2::TokenStream {746 let screaming_name = &self.screaming_name;747 quote! {748 interface_id ^= u32::from_be_bytes(Self::#screaming_name);749 }750 }751752 fn expand_parse(&self) -> proc_macro2::TokenStream {753 let pascal_name = &self.pascal_name;754 let screaming_name = &self.screaming_name;755 if self.has_normal_args {756 let parsers = self757 .args758 .iter()759 .filter(|a| !a.is_special())760 .map(|a| a.expand_parse());761 quote! {762 Self::#screaming_name => return Ok(Some(Self::#pascal_name {763 #(764 #parsers,765 )*766 }))767 }768 } else {769 quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }770 }771 }772773 fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {774 let pascal_name = &self.pascal_name;775 let name = &self.name;776777 let matcher = if self.has_normal_args {778 let names = self779 .args780 .iter()781 .filter(|a| !a.is_special())782 .map(|a| &a.name);783784 quote! {{785 #(786 #names,787 )*788 }}789 } else {790 quote! {}791 };792793 let receiver = match self.mutability {794 Mutability::Mutable | Mutability::View => quote! {self.},795 Mutability::Pure => quote! {Self::},796 };797 let args = self.args.iter().map(|a| a.expand_call_arg());798799 quote! {800 #call_name::#pascal_name #matcher => {801 let result = #receiver #name(802 #(803 #args,804 )*805 )?;806 (&result).to_result()807 }808 }809 }810811 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {812 let pascal_name = &self.pascal_name;813 if let Some(weight) = &self.weight {814 let matcher = if self.has_normal_args {815 let names = self816 .args817 .iter()818 .filter(|a| !a.is_special())819 .map(|a| &a.name);820821 quote! {{822 #(823 #names,824 )*825 }}826 } else {827 quote! {}828 };829 quote! {830 Self::#pascal_name #matcher => (#weight).into()831 }832 } else {833 let matcher = if self.has_normal_args {834 quote! {{..}}835 } else {836 quote! {}837 };838 quote! {839 Self::#pascal_name #matcher => ().into()840 }841 }842 }843844 fn expand_custom_signature(&self) -> proc_macro2::TokenStream {845 let mut custom_signature = TokenStream::new();846847 self.args848 .iter()849 .filter_map(|a| {850 if a.is_special() {851 return None;852 };853854 match a.ty {855 AbiType::Plain(ref ident) => Some(ident),856 _ => None,857 }858 })859 .for_each(|ident| {860 custom_signature.extend(quote! {861 (<#ident>::SIGNATURE, <#ident>::SIGNATURE_LEN)862 });863 });864865 let func_name = self.camel_name.clone();866 let func_name = quote!(FunctionName::new(#func_name));867 custom_signature =868 quote!({ ::evm_coder::make_signature!(new fn(& #func_name),#custom_signature) });869870 // println!("!!!!! {}", custom_signature);871872 custom_signature873 }874875 fn expand_solidity_function(&self) -> proc_macro2::TokenStream {876 let camel_name = &self.camel_name;877 let mutability = match self.mutability {878 Mutability::Mutable => quote! {SolidityMutability::Mutable},879 Mutability::View => quote! { SolidityMutability::View },880 Mutability::Pure => quote! {SolidityMutability::Pure},881 };882 let result = &self.result;883884 let args = self885 .args886 .iter()887 .filter(|a| !a.is_special())888 .map(MethodArg::expand_solidity_argument);889 let docs = &self.docs;890 let selector_str = &self.selector_str;891 let screaming_name = &self.screaming_name;892 let hide = self.hide;893 let custom_signature = self.expand_custom_signature();894 let custom_signature = quote!(895 {896 const cs: FunctionSignature = #custom_signature;897 cs898 }899 );900 // println!("!!!!! {}", custom_signature);901 let is_payable = self.has_value_args;902 let out = quote! {903 SolidityFunction {904 docs: &[#(#docs),*],905 selector_str: #selector_str,906 hide: #hide,907 selector: u32::from_be_bytes(Self::#screaming_name),908 custom_signature: #custom_signature,909 name: #camel_name,910 mutability: #mutability,911 is_payable: #is_payable,912 args: (913 #(914 #args,915 )*916 ),917 result: <UnnamedArgument<#result>>::default(),918 }919 };920 // println!("@@@ {}", out);921 out922 }923}924925fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {926 if gen.params.is_empty() {927 return quote! {};928 }929 let params = gen.params.iter().map(|p| match p {930 syn::GenericParam::Type(id) => {931 let v = &id.ident;932 quote! {#v}933 }934 syn::GenericParam::Lifetime(lt) => {935 let v = <.lifetime;936 quote! {#v}937 }938 syn::GenericParam::Const(c) => {939 let i = &c.ident;940 quote! {#i}941 }942 });943 quote! { #(#params),* }944}945fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {946 if gen.params.is_empty() {947 return quote! {};948 }949 let list = generics_list(gen);950 quote! { <#list> }951}952fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {953 let list = generics_list(gen);954 if gen.params.len() == 1 {955 quote! {#list}956 } else {957 quote! { (#list) }958 }959}960961pub struct SolidityInterface {962 generics: Generics,963 name: Box<syn::Type>,964 info: InterfaceInfo,965 methods: Vec<Method>,966 docs: Vec<String>,967}968impl SolidityInterface {969 pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {970 let mut methods = Vec::new();971972 for item in &value.items {973 if let ImplItem::Method(method) = item {974 methods.push(Method::try_from(method)?)975 }976 }977 let mut docs = vec![];978 for attr in &value.attrs {979 let ident = parse_ident_from_path(&attr.path, false)?;980 if ident == "doc" {981 let args = attr.parse_meta().unwrap();982 let value = match args {983 Meta::NameValue(MetaNameValue {984 lit: Lit::Str(str), ..985 }) => str.value(),986 _ => unreachable!(),987 };988 docs.push(value);989 }990 }991 Ok(Self {992 generics: value.generics.clone(),993 name: value.self_ty.clone(),994 info,995 methods,996 docs,997 })998 }999 pub fn expand(self) -> proc_macro2::TokenStream {1000 let name = self.name;10011002 let solidity_name = self.info.name.to_string();1003 let call_name = pascal_ident_to_call(&self.info.name);1004 let generics = self.generics;1005 let gen_ref = generics_reference(&generics);1006 let gen_data = generics_data(&generics);1007 let gen_where = &generics.where_clause;10081009 let call_sub = self1010 .info1011 .inline_is1012 .01013 .iter()1014 .chain(self.info.is.0.iter())1015 .map(|c| Is::expand_call_def(c, &gen_ref));1016 let call_parse = self1017 .info1018 .inline_is1019 .01020 .iter()1021 .chain(self.info.is.0.iter())1022 .map(|is| Is::expand_parse(is, &gen_ref));1023 let call_variants = self1024 .info1025 .inline_is1026 .01027 .iter()1028 .chain(self.info.is.0.iter())1029 .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));1030 let weight_variants = self1031 .info1032 .inline_is1033 .01034 .iter()1035 .chain(self.info.is.0.iter())1036 .map(Is::expand_variant_weight);10371038 let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);1039 let supports_interface = self1040 .info1041 .is1042 .01043 .iter()1044 .map(|is| Is::expand_supports_interface(is, &gen_ref));10451046 let calls = self.methods.iter().map(Method::expand_call_def);1047 let consts = self.methods.iter().map(Method::expand_const);1048 let interface_id = self.methods.iter().map(Method::expand_interface_id);1049 let parsers = self.methods.iter().map(Method::expand_parse);1050 let call_variants_this = self1051 .methods1052 .iter()1053 .map(|m| Method::expand_variant_call(m, &call_name));1054 let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);1055 let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);10561057 // TODO: Inline inline_is1058 let solidity_is = self1059 .info1060 .is1061 .01062 .iter()1063 .chain(self.info.inline_is.0.iter())1064 .map(|is| is.name.to_string());1065 let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());1066 let solidity_generators = self1067 .info1068 .is1069 .01070 .iter()1071 .chain(self.info.inline_is.0.iter())1072 .map(|is| Is::expand_generator(is, &gen_ref));1073 let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);10741075 let docs = &self.docs;10761077 if let Some(expect_selector) = &self.info.expect_selector {1078 if !self.info.inline_is.0.is_empty() {1079 return syn::Error::new(1080 name.span(),1081 "expect_selector is not compatible with inline_is",1082 )1083 .to_compile_error();1084 }1085 let selector = self1086 .methods1087 .iter()1088 .map(|m| m.selector)1089 .fold(0, |a, b| a ^ b);10901091 if *expect_selector != selector {1092 let mut methods = String::new();1093 for meth in self.methods.iter() {1094 write!(methods, "\n- {}", meth.selector_str).expect("write to string");1095 }1096 return syn::Error::new(name.span(), format!("expected selector mismatch, expected {expect_selector:0>8x}, but implementation has {selector:0>8x}{methods}")).to_compile_error();1097 }1098 }1099 // let methods = self.methods.iter().map(Method::solidity_def);11001101 quote! {1102 #[derive(Debug)]1103 #(#[doc = #docs])*1104 pub enum #call_name #gen_ref {1105 /// Inherited method1106 ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),1107 #(1108 #calls,1109 )*1110 #(1111 #call_sub,1112 )*1113 }1114 impl #gen_ref #call_name #gen_ref {1115 #(1116 #consts1117 )*1118 /// Return this call ERC165 selector1119 pub fn interface_id() -> ::evm_coder::types::bytes4 {1120 let mut interface_id = 0;1121 #(#interface_id)*1122 #(#inline_interface_id)*1123 u32::to_be_bytes(interface_id)1124 }1125 /// Generate solidity definitions for methods described in this interface1126 pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {1127 use evm_coder::solidity::*;1128 use core::fmt::Write;1129 let interface = SolidityInterface {1130 docs: &[#(#docs),*],1131 name: #solidity_name,1132 selector: Self::interface_id(),1133 is: &["Dummy", "ERC165", #(1134 #solidity_is,1135 )* #(1136 #solidity_events_is,1137 )* ],1138 functions: (#(1139 #solidity_functions,1140 )*),1141 };11421143 let mut out = ::evm_coder::types::string::new();1144 if #solidity_name.starts_with("Inline") {1145 out.push_str("/// @dev inlined interface\n");1146 }1147 let _ = interface.format(is_impl, &mut out, tc);1148 tc.collect(out);1149 #(1150 #solidity_event_generators1151 )*1152 #(1153 #solidity_generators1154 )*1155 if is_impl {1156 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());1157 } else {1158 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());1159 }1160 }1161 }1162 impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1163 fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1164 use ::evm_coder::abi::AbiRead;1165 match method_id {1166 ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1167 ::evm_coder::ERC165Call::parse(method_id, reader)?1168 .map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1169 ),1170 #(1171 #parsers,1172 )*1173 _ => {},1174 }1175 #(1176 #call_parse1177 )else*1178 return Ok(None);1179 }1180 }1181 impl #generics #call_name #gen_ref1182 #gen_where1183 {1184 /// Is this contract implements specified ERC165 selector1185 pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1186 interface_id != u32::to_be_bytes(0xffffff) && (1187 interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1188 interface_id == Self::interface_id()1189 #(1190 || #supports_interface1191 )*1192 )1193 }1194 }1195 impl #generics ::evm_coder::Weighted for #call_name #gen_ref1196 #gen_where1197 {1198 #[allow(unused_variables)]1199 fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1200 match self {1201 #(1202 #weight_variants,1203 )*1204 // TODO: It should be very cheap, but not free1205 Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1206 #(1207 #weight_variants_this,1208 )*1209 }1210 }1211 }1212 impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1213 #gen_where1214 {1215 #[allow(unreachable_code)] // In case of no inner calls1216 fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1217 use ::evm_coder::abi::AbiWrite;1218 match c.call {1219 #(1220 #call_variants,1221 )*1222 #call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1223 let mut writer = ::evm_coder::abi::AbiWriter::default();1224 writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1225 return Ok(writer.into());1226 }1227 _ => {},1228 }1229 let mut writer = ::evm_coder::abi::AbiWriter::default();1230 match c.call {1231 #(1232 #call_variants_this,1233 )*1234 _ => Err(::evm_coder::execution::Error::from("method is not available").into()),1235 }1236 }1237 }1238 }1239 }1240}crates/evm-coder/src/custom_signature.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/custom_signature.rs
@@ -0,0 +1,336 @@
+use core::str::from_utf8;
+
+pub const SIGNATURE_SIZE_LIMIT: usize = 256;
+
+pub trait Name {
+ const SIGNATURE: [u8; SIGNATURE_SIZE_LIMIT];
+ const SIGNATURE_LEN: usize;
+
+ fn name() -> &'static str {
+ from_utf8(&Self::SIGNATURE[..Self::SIGNATURE_LEN]).expect("bad utf-8")
+ }
+}
+
+#[derive(Debug)]
+pub struct FunctionSignature {
+ pub signature: [u8; SIGNATURE_SIZE_LIMIT],
+ pub signature_len: usize,
+}
+
+impl FunctionSignature {
+ pub const fn new(name: &'static FunctionName) -> FunctionSignature {
+ let mut signature = [0_u8; SIGNATURE_SIZE_LIMIT];
+ let name_len = name.signature_len;
+ let name = name.signature;
+ let mut dst_offset = 0;
+ let bracket_open = {
+ let mut b = [0_u8; SIGNATURE_SIZE_LIMIT];
+ b[0] = b"("[0];
+ b
+ };
+ crate::make_signature!(@copy(name, signature, name_len, dst_offset));
+ crate::make_signature!(@copy(bracket_open, signature, 1, dst_offset));
+ FunctionSignature {
+ signature,
+ signature_len: dst_offset,
+ }
+ }
+
+ pub const fn add_param(
+ signature: FunctionSignature,
+ param: ([u8; SIGNATURE_SIZE_LIMIT], usize),
+ ) -> FunctionSignature {
+ let mut dst = signature.signature;
+ let mut dst_offset = signature.signature_len;
+ let (param_name, param_len) = param;
+ let comma = {
+ let mut b = [0_u8; SIGNATURE_SIZE_LIMIT];
+ b[0] = b","[0];
+ b
+ };
+ FunctionSignature {
+ signature: {
+ crate::make_signature!(@copy(param_name, dst, param_len, dst_offset));
+ crate::make_signature!(@copy(comma, dst, 1, dst_offset));
+ dst
+ },
+ signature_len: dst_offset,
+ }
+ }
+
+ pub const fn done(signature: FunctionSignature, owerride: bool) -> FunctionSignature {
+ let mut dst = signature.signature;
+ let mut dst_offset = signature.signature_len - if owerride { 1 } else { 0 };
+ let bracket_close = {
+ let mut b = [0_u8; SIGNATURE_SIZE_LIMIT];
+ b[0] = b")"[0];
+ b
+ };
+ FunctionSignature {
+ signature: {
+ crate::make_signature!(@copy(bracket_close, dst, 1, dst_offset));
+ dst
+ },
+ signature_len: dst_offset,
+ }
+ }
+
+ // fn as_str(&self) -> &'static str {
+ // from_utf8(&self.signature[..self.signature_len]).expect("bad utf-8")
+ // }
+}
+
+#[derive(Debug)]
+pub struct FunctionName {
+ signature: [u8; SIGNATURE_SIZE_LIMIT],
+ signature_len: usize,
+}
+
+impl FunctionName {
+ pub const fn new(name: &'static str) -> FunctionName {
+ let mut signature = [0_u8; SIGNATURE_SIZE_LIMIT];
+ let name = name.as_bytes();
+ let name_len = name.len();
+ let mut dst_offset = 0;
+ crate::make_signature!(@copy(name, signature, name_len, dst_offset));
+ FunctionName {
+ signature,
+ signature_len: name_len,
+ }
+ }
+}
+
+#[macro_export]
+#[allow(missing_docs)]
+macro_rules! make_signature { // May be "define_signature"?
+ (new fn($func:expr)$(,)+) => {
+ {
+ let fs = FunctionSignature::new(& $func);
+ let fs = FunctionSignature::done(fs, false);
+ fs
+ }
+ };
+ (new fn($func:expr), $($tt:tt)*) => {
+ {
+ let fs = FunctionSignature::new(& $func);
+ let fs = make_signature!(@param; fs, $($tt),*);
+ fs
+ }
+ };
+
+ (@param; $func:expr) => {
+ FunctionSignature::done($func, true)
+ };
+ (@param; $func:expr, $param:expr) => {
+ make_signature!(@param; FunctionSignature::add_param($func, $param))
+ };
+ (@param; $func:expr, $param:expr, $($tt:tt),*) => {
+ make_signature!(@param; FunctionSignature::add_param($func, $param), $($tt),*)
+ };
+
+ (new $($tt:tt)*) => {
+ const SIGNATURE: [u8; SIGNATURE_SIZE_LIMIT] = {
+ let mut out = [0u8; SIGNATURE_SIZE_LIMIT];
+ let mut dst_offset = 0;
+ make_signature!(@data(out, dst_offset); $($tt)*);
+ out
+ };
+ const SIGNATURE_LEN: usize = 0 + make_signature!(@size; $($tt)*);
+ };
+
+ // (@bytes)
+
+ (@size;) => {
+ 0
+ };
+ (@size; fixed($expr:expr) $($tt:tt)*) => {
+ $expr.len() + make_signature!(@size; $($tt)*)
+ };
+ (@size; nameof($expr:ty) $($tt:tt)*) => {
+ <$expr>::SIGNATURE_LEN + make_signature!(@size; $($tt)*)
+ };
+
+ (@data($dst:ident, $dst_offset:ident);) => {};
+ (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
+ {
+ let data = $expr.as_bytes();
+ let data_len = data.len();
+ make_signature!(@copy(data, $dst, data_len, $dst_offset));
+ }
+ make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+ (@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {
+ {
+ let data = &<$expr>::SIGNATURE;
+ let data_len = <$expr>::SIGNATURE_LEN;
+ make_signature!(@copy(data, $dst, data_len, $dst_offset));
+ }
+ make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+
+ (@copy($src:ident, $dst:ident, $src_len:expr, $dst_offset:ident)) => {
+ {
+ let mut src_offset = 0;
+ let src_len: usize = $src_len;
+ while src_offset < src_len {
+ $dst[$dst_offset] = $src[src_offset];
+ $dst_offset += 1;
+ src_offset += 1;
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use core::str::from_utf8;
+
+ use frame_support::sp_runtime::app_crypto::sp_core::hexdisplay::AsBytesRef;
+
+ use super::{Name, SIGNATURE_SIZE_LIMIT, FunctionName, FunctionSignature};
+
+ impl Name for u8 {
+ make_signature!(new fixed("uint8"));
+ }
+ impl Name for u32 {
+ make_signature!(new fixed("uint32"));
+ }
+ impl<T: Name> Name for Vec<T> {
+ make_signature!(new nameof(T) fixed("[]"));
+ }
+ impl<A: Name, B: Name> Name for (A, B) {
+ make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
+ }
+
+ struct MaxSize();
+ impl Name for MaxSize {
+ const SIGNATURE: [u8; SIGNATURE_SIZE_LIMIT] = [b'!'; SIGNATURE_SIZE_LIMIT];
+ const SIGNATURE_LEN: usize = SIGNATURE_SIZE_LIMIT;
+ }
+
+ #[test]
+ fn simple() {
+ assert_eq!(u8::name(), "uint8");
+ assert_eq!(u32::name(), "uint32");
+ }
+
+ #[test]
+ fn vector_of_simple() {
+ assert_eq!(<Vec<u8>>::name(), "uint8[]");
+ assert_eq!(<Vec<u32>>::name(), "uint32[]");
+ }
+
+ #[test]
+ fn vector_of_vector() {
+ assert_eq!(<Vec<Vec<u8>>>::name(), "uint8[][]");
+ }
+
+ #[test]
+ fn tuple_of_simple() {
+ assert_eq!(<(u32, u8)>::name(), "(uint32,uint8)");
+ }
+
+ #[test]
+ fn tuple_of_tuple() {
+ assert_eq!(
+ <((u32, u8), (u8, u32))>::name(),
+ "((uint32,uint8),(uint8,uint32))"
+ );
+ }
+
+ #[test]
+ fn vector_of_tuple() {
+ assert_eq!(<Vec<(u32, u8)>>::name(), "(uint32,uint8)[]");
+ }
+
+ #[test]
+ fn tuple_of_vector() {
+ assert_eq!(<(Vec<u32>, u8)>::name(), "(uint32[],uint8)");
+ }
+
+ #[test]
+ fn complex() {
+ assert_eq!(
+ <(Vec<u32>, (u32, Vec<u8>))>::name(),
+ "(uint32[],(uint32,uint8[]))"
+ );
+ }
+
+ #[test]
+ fn max_size() {
+ assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));
+ }
+
+ // This test must NOT compile!
+ // #[test]
+ // fn over_max_size() {
+ // assert_eq!(<Vec<MaxSize>>::name(), "!".repeat(SIZE_LIMIT) + "[]");
+ // }
+
+ #[test]
+ fn make_func_without_args() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ );
+ let name = from_utf8(&SIG.signature[..SIG.signature_len]).unwrap();
+ assert_eq!(name, "some_funk()");
+ }
+
+ #[test]
+ fn make_func_with_1_args() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ (u8::SIGNATURE, u8::SIGNATURE_LEN)
+ );
+ let name = from_utf8(&SIG.signature[..SIG.signature_len]).unwrap();
+ assert_eq!(name, "some_funk(uint8)");
+ }
+
+ #[test]
+ fn make_func_with_2_args() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ (u8::SIGNATURE, u8::SIGNATURE_LEN)
+ (<Vec<u32>>::SIGNATURE, <Vec<u32>>::SIGNATURE_LEN)
+ );
+ let name = from_utf8(&SIG.signature[..SIG.signature_len]).unwrap();
+ assert_eq!(name, "some_funk(uint8,uint32[])");
+ }
+
+ #[test]
+ fn make_func_with_3_args() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ (u8::SIGNATURE, u8::SIGNATURE_LEN)
+ (u32::SIGNATURE, u32::SIGNATURE_LEN)
+ (<Vec<u32>>::SIGNATURE, <Vec<u32>>::SIGNATURE_LEN)
+ );
+ let name = from_utf8(&SIG.signature[..SIG.signature_len]).unwrap();
+ assert_eq!(name, "some_funk(uint8,uint32,uint32[])");
+ }
+
+ #[test]
+ fn make_slice_from_signature() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ (u8::SIGNATURE, u8::SIGNATURE_LEN)
+ (u32::SIGNATURE, u32::SIGNATURE_LEN)
+ (<Vec<u32>>::SIGNATURE, <Vec<u32>>::SIGNATURE_LEN)
+ );
+ const NAME: [u8; SIG.signature_len] = {
+ let mut name: [u8; SIG.signature_len] = [0; SIG.signature_len];
+ let mut i = 0;
+ while i < SIG.signature_len {
+ name[i] = SIG.signature[i];
+ i += 1;
+ }
+ name
+ };
+ assert_eq!(&NAME, b"some_funk(uint8,uint32,uint32[])");
+ }
+}
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -15,7 +15,9 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
#![doc = include_str!("../README.md")]
-#![deny(missing_docs)]
+// #![deny(missing_docs)]
+#![warn(missing_docs)]
+#![macro_use]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
extern crate alloc;
@@ -26,6 +28,8 @@
pub use events::{ToLog, ToTopic};
use execution::DispatchInfo;
pub mod execution;
+#[macro_use]
+pub mod custom_signature;
/// Derives call enum implementing [`crate::Callable`], [`crate::Weighted`]
/// and [`crate::Call`] from impl block.
@@ -118,27 +122,54 @@
use alloc::{vec::Vec};
use pallet_evm::account::CrossAccountId;
use primitive_types::{U256, H160, H256};
+ use core::str::from_utf8;
- pub type address = H160;
+ use crate::custom_signature::SIGNATURE_SIZE_LIMIT;
- 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 trait Signature {
+ const SIGNATURE: [u8; SIGNATURE_SIZE_LIMIT];
+ const SIGNATURE_LEN: usize;
- pub type bytes4 = [u8; 4];
+ fn as_str() -> &'static str {
+ from_utf8(&Self::SIGNATURE[..Self::SIGNATURE_LEN]).expect("bad utf-8")
+ }
+ }
- pub type topic = H256;
+ impl Signature for bool {
+ make_signature!(new fixed("bool"));
+ }
+ macro_rules! define_simple_type {
+ (type $ident:ident = $ty:ty) => {
+ pub type $ident = $ty;
+ impl Signature for $ty {
+ make_signature!(new fixed(stringify!($ident)));
+ }
+ };
+ }
+
+ 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);
+
#[cfg(not(feature = "std"))]
- pub type string = ::alloc::string::String;
+ define_simple_type!(type string = ::alloc::string::String);
#[cfg(feature = "std")]
- pub type string = ::std::string::String;
+ define_simple_type!(type string = ::std::string::String);
#[derive(Default, Debug)]
pub struct bytes(pub Vec<u8>);
+ impl Signature for bytes {
+ make_signature!(new fixed("bytes"));
+ }
/// Solidity doesn't have `void` type, however we have special implementation
/// for empty tuple return type
@@ -230,12 +261,8 @@
}
}
- impl SignatureString for EthCrossAccount {
- const SIGNATURE_STRING: &'static str = "(address,uint256)";
- }
-
- pub trait SignatureString {
- const SIGNATURE_STRING: &'static str;
+ impl Signature for EthCrossAccount {
+ make_signature!(new fixed("(address,uint256)"));
}
/// Convert `CrossAccountId` to `uint256`.
crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -30,9 +30,10 @@
marker::PhantomData,
cell::{Cell, RefCell},
cmp::Reverse,
+ str::from_utf8,
};
use impl_trait_for_tuples::impl_for_tuples;
-use crate::types::*;
+use crate::{types::*, custom_signature::FunctionSignature};
#[derive(Default)]
pub struct TypeCollector {
@@ -487,7 +488,7 @@
pub selector_str: &'static str,
pub selector: u32,
pub hide: bool,
- pub custom_signature: &'static str,
+ pub custom_signature: FunctionSignature,
pub name: &'static str,
pub args: A,
pub result: R,
@@ -513,7 +514,8 @@
writeln!(
writer,
"\t{hide_comment}/// or in textual repr: {}",
- self.custom_signature
+ // from_utf8(self.custom_signature.as_str()).expect("bad utf8")
+ self.selector_str
)?;
write!(writer, "\t{hide_comment}function {}(", self.name)?;
self.args.solidity_name(writer, tc)?;
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -21,6 +21,8 @@
types::*,
execution::{Result, Error},
weight,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
};
pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};
use pallet_evm_coder_substrate::dispatch_to_evm;
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -20,7 +20,13 @@
use alloc::{format, string::ToString};
use core::marker::PhantomData;
use evm_coder::{
- abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
+ abi::AbiWriter,
+ execution::Result,
+ generate_stubgen, solidity_interface,
+ types::*,
+ ToLog,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
};
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
@@ -20,7 +20,15 @@
use alloc::{format, string::ToString};
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::{
+ ToLog,
+ execution::*,
+ generate_stubgen, solidity_interface,
+ types::*,
+ weight,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
+};
use pallet_common::eth::convert_tuple_to_cross_account;
use up_data_structs::CollectionMode;
use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -25,7 +25,15 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ ToLog,
+ execution::*,
+ generate_stubgen, solidity, solidity_interface,
+ types::*,
+ weight,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
+};
use frame_support::BoundedVec;
use up_data_structs::{
TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -104,7 +104,11 @@
}
/// @title A contract that allows you to work with collections.
+<<<<<<< HEAD
/// @dev the ERC-165 identifier for this interface is 0xb3152af3
+=======
+/// @dev the ERC-165 identifier for this interface is 0x674be726
+>>>>>>> feat: Add custum signature with unlimited nesting.
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -198,7 +202,7 @@
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
///
/// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
- /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// @dev EVM selector for this function is: 0x403e96a7,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
function setCollectionSponsorCross(Tuple6 memory sponsor) public {
require(false, stub_error);
@@ -239,6 +243,7 @@
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
<<<<<<< HEAD
+<<<<<<< HEAD
function collectionSponsor() public view returns (Tuple6 memory) {
require(false, stub_error);
dummy;
@@ -249,6 +254,12 @@
dummy;
return Tuple19(0x0000000000000000000000000000000000000000, 0);
>>>>>>> feat: add `EthCrossAccount` type
+=======
+ function collectionSponsor() public view returns (Tuple8 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple8(0x0000000000000000000000000000000000000000, 0);
+>>>>>>> feat: Add custum signature with unlimited nesting.
}
/// Set limits for the collection.
@@ -297,7 +308,7 @@
/// Add collection admin.
/// @param newAdmin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x859aa7d6,
+ /// @dev EVM selector for this function is: 0x62e3c7c2,
/// or in textual repr: addCollectionAdminCross((address,uint256))
function addCollectionAdminCross(Tuple6 memory newAdmin) public {
require(false, stub_error);
@@ -307,7 +318,7 @@
/// Remove collection admin.
/// @param admin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x6c0cd173,
+ /// @dev EVM selector for this function is: 0x810d1503,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
function removeCollectionAdminCross(Tuple6 memory admin) public {
require(false, stub_error);
@@ -351,7 +362,7 @@
///
/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
/// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
+ /// @dev EVM selector for this function is: 0x112d4586,
/// or in textual repr: setCollectionNesting(bool,address[])
function setCollectionNesting(bool enable, address[] memory collections) public {
require(false, stub_error);
@@ -398,7 +409,7 @@
/// Add user to allowed list.
///
/// @param user User cross account address.
- /// @dev EVM selector for this function is: 0xa0184a3a,
+ /// @dev EVM selector for this function is: 0xf074da88,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
function addToCollectionAllowListCross(Tuple6 memory user) public {
require(false, stub_error);
@@ -420,7 +431,7 @@
/// Remove user from allowed list.
///
/// @param user User cross account address.
- /// @dev EVM selector for this function is: 0x09ba452a,
+ /// @dev EVM selector for this function is: 0xc00df45c,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
function removeFromCollectionAllowListCross(Tuple6 memory user) public {
require(false, stub_error);
@@ -456,7 +467,7 @@
///
/// @param user User cross account to verify
/// @return "true" if account is the owner or admin
- /// @dev EVM selector for this function is: 0x3e75a905,
+ /// @dev EVM selector for this function is: 0x5aba3351,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
function isOwnerOrAdminCross(Tuple6 memory user) public view returns (bool) {
require(false, stub_error);
@@ -483,6 +494,7 @@
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
<<<<<<< HEAD
+<<<<<<< HEAD
function collectionOwner() public view returns (Tuple6 memory) {
require(false, stub_error);
dummy;
@@ -493,6 +505,12 @@
dummy;
return Tuple19(0x0000000000000000000000000000000000000000, 0);
>>>>>>> feat: add `EthCrossAccount` type
+=======
+ function collectionOwner() public view returns (Tuple8 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple8(0x0000000000000000000000000000000000000000, 0);
+>>>>>>> feat: Add custum signature with unlimited nesting.
}
/// Changes collection owner to another account
@@ -523,7 +541,7 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner cross account
- /// @dev EVM selector for this function is: 0xe5c9913f,
+ /// @dev EVM selector for this function is: 0xbdff793d,
/// or in textual repr: setOwnerCross((address,uint256))
function setOwnerCross(Tuple6 memory newOwner) public {
require(false, stub_error);
@@ -532,6 +550,7 @@
}
}
+<<<<<<< HEAD
/// @dev anonymous struct
struct Tuple19 {
address field_0;
@@ -581,6 +600,8 @@
}
}
+=======
+>>>>>>> feat: Add custum signature with unlimited nesting.
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
contract ERC721Burnable is Dummy, ERC165 {
@@ -682,7 +703,11 @@
}
/// @title Unique extensions for ERC721.
+<<<<<<< HEAD
/// @dev the ERC-165 identifier for this interface is 0x244543ee
+=======
+/// @dev the ERC-165 identifier for this interface is 0xcc97cb35
+>>>>>>> feat: Add custum signature with unlimited nesting.
contract ERC721UniqueExtensions is Dummy, ERC165 {
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev EVM selector for this function is: 0x06fdde03,
@@ -708,7 +733,7 @@
/// operator of the current owner.
/// @param approved The new substrate address approved NFT controller
/// @param tokenId The NFT to approve
- /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// @dev EVM selector for this function is: 0x106fdb59,
/// or in textual repr: approveCross((address,uint256),uint256)
function approveCross(Tuple6 memory approved, uint256 tokenId) public {
require(false, stub_error);
@@ -738,10 +763,15 @@
/// @param to Cross acccount address of new owner
/// @param tokenId The NFT to transfer
/// @dev EVM selector for this function is: 0xd5cf430b,
- /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ /// or in textual repr: transferFromCross(EthCrossAccount,EthCrossAccount,uint256)
function transferFromCross(
+<<<<<<< HEAD
Tuple6 memory from,
Tuple6 memory to,
+=======
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
+>>>>>>> feat: Add custum signature with unlimited nesting.
uint256 tokenId
) public {
require(false, stub_error);
@@ -772,7 +802,7 @@
/// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.
/// @param from The current owner of the NFT
/// @param tokenId The NFT to transfer
- /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// @dev EVM selector for this function is: 0xa8106d4a,
/// or in textual repr: burnFromCross((address,uint256),uint256)
function burnFromCross(Tuple6 memory from, uint256 tokenId) public {
require(false, stub_error);
@@ -819,10 +849,46 @@
// return false;
// }
+<<<<<<< HEAD
}
/// @dev anonymous struct
struct Tuple8 {
+=======
+ /// @notice Function to mint multiple tokens.
+ /// @dev `tokenIds` should be an array of consecutive numbers and first number
+ /// should be obtained with `nextTokenId` method
+ /// @param to The new owner
+ /// @param tokenIds IDs of the minted NFTs
+ /// @dev EVM selector for this function is: 0xf9d9a5a3,
+ /// or in textual repr: mintBulk(address,uint256[])
+ function mintBulk(address to, uint256[] memory tokenIds) public returns (bool) {
+ require(false, stub_error);
+ to;
+ tokenIds;
+ dummy = 0;
+ return false;
+ }
+
+ /// @notice Function to mint multiple tokens with the given tokenUris.
+ /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
+ /// numbers and first number should be obtained with `nextTokenId` method
+ /// @param to The new owner
+ /// @param tokens array of pairs of token ID and token URI for minted tokens
+ /// @dev EVM selector for this function is: 0xfd4e2a99,
+ /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
+ function mintBulkWithTokenURI(address to, Tuple12[] memory tokens) public returns (bool) {
+ require(false, stub_error);
+ to;
+ tokens;
+ dummy = 0;
+ return false;
+ }
+}
+
+/// @dev anonymous struct
+struct Tuple12 {
+>>>>>>> feat: Add custum signature with unlimited nesting.
uint256 field_0;
string field_1;
}
@@ -840,6 +906,12 @@
>>>>>>> feat: add `EthCrossAccount` type
}
+/// @dev anonymous struct
+struct Tuple8 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x780e9d63
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -26,7 +26,15 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ ToLog,
+ execution::*,
+ generate_stubgen, solidity, solidity_interface,
+ types::*,
+ weight,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
+};
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,15 @@
convert::TryInto,
ops::Deref,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
+use evm_coder::{
+ ToLog,
+ execution::*,
+ generate_stubgen, solidity_interface,
+ types::*,
+ weight,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
+};
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -18,7 +18,13 @@
use core::marker::PhantomData;
use ethereum as _;
-use evm_coder::{execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ execution::*,
+ generate_stubgen, solidity, solidity_interface,
+ types::*,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
+, weight};
use frame_support::{traits::Get, storage::StorageNMap};
use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageDoubleMap;
use crate::Pallet;
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -70,7 +70,11 @@
}
/// @title A contract that allows you to work with collections.
+<<<<<<< HEAD
/// @dev the ERC-165 identifier for this interface is 0xb3152af3
+=======
+/// @dev the ERC-165 identifier for this interface is 0x674be726
+>>>>>>> feat: Add custum signature with unlimited nesting.
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -133,7 +137,7 @@
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
///
/// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
- /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// @dev EVM selector for this function is: 0x403e96a7,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
function setCollectionSponsorCross(Tuple6 memory sponsor) external;
@@ -193,13 +197,13 @@
/// Add collection admin.
/// @param newAdmin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x859aa7d6,
+ /// @dev EVM selector for this function is: 0x62e3c7c2,
/// or in textual repr: addCollectionAdminCross((address,uint256))
function addCollectionAdminCross(Tuple6 memory newAdmin) external;
/// Remove collection admin.
/// @param admin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x6c0cd173,
+ /// @dev EVM selector for this function is: 0x810d1503,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
function removeCollectionAdminCross(Tuple6 memory admin) external;
@@ -227,7 +231,7 @@
///
/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
/// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
+ /// @dev EVM selector for this function is: 0x112d4586,
/// or in textual repr: setCollectionNesting(bool,address[])
function setCollectionNesting(bool enable, address[] memory collections) external;
@@ -256,7 +260,7 @@
/// Add user to allowed list.
///
/// @param user User cross account address.
- /// @dev EVM selector for this function is: 0xa0184a3a,
+ /// @dev EVM selector for this function is: 0xf074da88,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
function addToCollectionAllowListCross(Tuple6 memory user) external;
@@ -270,7 +274,7 @@
/// Remove user from allowed list.
///
/// @param user User cross account address.
- /// @dev EVM selector for this function is: 0x09ba452a,
+ /// @dev EVM selector for this function is: 0xc00df45c,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
function removeFromCollectionAllowListCross(Tuple6 memory user) external;
@@ -293,7 +297,7 @@
///
/// @param user User cross account to verify
/// @return "true" if account is the owner or admin
- /// @dev EVM selector for this function is: 0x3e75a905,
+ /// @dev EVM selector for this function is: 0x5aba3351,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
function isOwnerOrAdminCross(Tuple6 memory user) external view returns (bool);
@@ -332,11 +336,12 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner cross account
- /// @dev EVM selector for this function is: 0xe5c9913f,
+ /// @dev EVM selector for this function is: 0xbdff793d,
/// or in textual repr: setOwnerCross((address,uint256))
function setOwnerCross(Tuple6 memory newOwner) external;
}
+<<<<<<< HEAD
/// @dev anonymous struct
struct Tuple19 {
address field_0;
@@ -373,6 +378,8 @@
function tokenURI(uint256 tokenId) external view returns (string memory);
}
+=======
+>>>>>>> feat: Add custum signature with unlimited nesting.
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
interface ERC721Burnable is Dummy, ERC165 {
@@ -438,7 +445,11 @@
}
/// @title Unique extensions for ERC721.
+<<<<<<< HEAD
/// @dev the ERC-165 identifier for this interface is 0x244543ee
+=======
+/// @dev the ERC-165 identifier for this interface is 0xcc97cb35
+>>>>>>> feat: Add custum signature with unlimited nesting.
interface ERC721UniqueExtensions is Dummy, ERC165 {
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev EVM selector for this function is: 0x06fdde03,
@@ -456,7 +467,7 @@
/// operator of the current owner.
/// @param approved The new substrate address approved NFT controller
/// @param tokenId The NFT to approve
- /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// @dev EVM selector for this function is: 0x106fdb59,
/// or in textual repr: approveCross((address,uint256),uint256)
function approveCross(Tuple6 memory approved, uint256 tokenId) external;
@@ -476,10 +487,15 @@
/// @param to Cross acccount address of new owner
/// @param tokenId The NFT to transfer
/// @dev EVM selector for this function is: 0xd5cf430b,
- /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ /// or in textual repr: transferFromCross(EthCrossAccount,EthCrossAccount,uint256)
function transferFromCross(
+<<<<<<< HEAD
Tuple6 memory from,
Tuple6 memory to,
+=======
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
+>>>>>>> feat: Add custum signature with unlimited nesting.
uint256 tokenId
) external;
@@ -499,7 +515,7 @@
/// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.
/// @param from The current owner of the NFT
/// @param tokenId The NFT to transfer
- /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// @dev EVM selector for this function is: 0xa8106d4a,
/// or in textual repr: burnFromCross((address,uint256),uint256)
function burnFromCross(Tuple6 memory from, uint256 tokenId) external;
@@ -507,6 +523,7 @@
/// @dev EVM selector for this function is: 0x75794a3c,
/// or in textual repr: nextTokenId()
function nextTokenId() external view returns (uint256);
+<<<<<<< HEAD
// /// @notice Function to mint multiple tokens.
// /// @dev `tokenIds` should be an array of consecutive numbers and first number
// /// should be obtained with `nextTokenId` method
@@ -528,6 +545,30 @@
/// @dev anonymous struct
struct Tuple8 {
+=======
+
+ /// @notice Function to mint multiple tokens.
+ /// @dev `tokenIds` should be an array of consecutive numbers and first number
+ /// should be obtained with `nextTokenId` method
+ /// @param to The new owner
+ /// @param tokenIds IDs of the minted NFTs
+ /// @dev EVM selector for this function is: 0xf9d9a5a3,
+ /// or in textual repr: mintBulk(address,uint256[])
+ function mintBulk(address to, uint256[] memory tokenIds) external returns (bool);
+
+ /// @notice Function to mint multiple tokens with the given tokenUris.
+ /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
+ /// numbers and first number should be obtained with `nextTokenId` method
+ /// @param to The new owner
+ /// @param tokens array of pairs of token ID and token URI for minted tokens
+ /// @dev EVM selector for this function is: 0xfd4e2a99,
+ /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
+ function mintBulkWithTokenURI(address to, Tuple12[] memory tokens) external returns (bool);
+}
+
+/// @dev anonymous struct
+struct Tuple12 {
+>>>>>>> feat: Add custum signature with unlimited nesting.
uint256 field_0;
string field_1;
}
@@ -538,6 +579,12 @@
uint256 field_1;
}
+/// @dev anonymous struct
+struct Tuple8 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x780e9d63
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -409,7 +409,7 @@
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
});
- itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
+ itEth.only('Can perform transferFromCross()', async ({helper, privateKey}) => {
const alice = privateKey('//Alice');
const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -251,10 +251,14 @@
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
<<<<<<< HEAD
+<<<<<<< HEAD
"internalType": "struct Tuple6",
=======
"internalType": "struct Tuple19",
>>>>>>> feat: add `EthCrossAccount` type
+=======
+ "internalType": "struct Tuple8",
+>>>>>>> feat: Add custum signature with unlimited nesting.
"name": "",
"type": "tuple"
}
@@ -263,6 +267,7 @@
"type": "function"
},
{
+<<<<<<< HEAD
"inputs": [
{ "internalType": "string[]", "name": "keys", "type": "string[]" }
],
@@ -278,6 +283,11 @@
"type": "tuple[]"
}
],
+=======
+ "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
+ "name": "collectionProperty",
+ "outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
+>>>>>>> feat: Add custum signature with unlimited nesting.
"stateMutability": "view",
"type": "function"
},
@@ -298,10 +308,14 @@
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
<<<<<<< HEAD
+<<<<<<< HEAD
"internalType": "struct Tuple6",
=======
"internalType": "struct Tuple19",
>>>>>>> feat: add `EthCrossAccount` type
+=======
+ "internalType": "struct Tuple8",
+>>>>>>> feat: Add custum signature with unlimited nesting.
"name": "",
"type": "tuple"
}
@@ -324,6 +338,7 @@
"type": "function"
},
{
+<<<<<<< HEAD
"inputs": [
{ "internalType": "string[]", "name": "keys", "type": "string[]" }
],
@@ -333,6 +348,8 @@
"type": "function"
},
{
+=======
+>>>>>>> feat: Add custum signature with unlimited nesting.
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "deleteCollectionProperty",
"outputs": [],
@@ -409,19 +426,64 @@
"type": "function"
},
{
+<<<<<<< HEAD
"inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
"name": "mint",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+=======
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "mint",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+>>>>>>> feat: Add custum signature with unlimited nesting.
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{ "internalType": "address", "name": "to", "type": "address" },
+<<<<<<< HEAD
{ "internalType": "string", "name": "tokenUri", "type": "string" }
],
"name": "mintWithTokenURI",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+=======
+ { "internalType": "uint256[]", "name": "tokenIds", "type": "uint256[]" }
+ ],
+ "name": "mintBulk",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ {
+ "components": [
+ { "internalType": "uint256", "name": "field_0", "type": "uint256" },
+ { "internalType": "string", "name": "field_1", "type": "string" }
+ ],
+ "internalType": "struct Tuple12[]",
+ "name": "tokens",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "mintBulkWithTokenURI",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "tokenUri", "type": "string" }
+ ],
+ "name": "mintWithTokenURI",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+>>>>>>> feat: Add custum signature with unlimited nesting.
"stateMutability": "nonpayable",
"type": "function"
},
@@ -614,6 +676,7 @@
},
{
"inputs": [
+<<<<<<< HEAD
{
"components": [
{ "internalType": "string", "name": "field_0", "type": "string" },
@@ -623,6 +686,10 @@
"name": "properties",
"type": "tuple[]"
}
+=======
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
"name": "setCollectionProperties",
"outputs": [],
@@ -667,6 +734,7 @@
},
{
"inputs": [
+<<<<<<< HEAD
{
"components": [
{ "internalType": "address", "name": "field_0", "type": "address" },
@@ -676,6 +744,9 @@
"name": "newOwner",
"type": "tuple"
}
+=======
+ { "internalType": "address", "name": "newOwner", "type": "address" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
"name": "setOwnerCross",
"outputs": [],
@@ -687,8 +758,13 @@
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{
"components": [
+<<<<<<< HEAD
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
+=======
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
"internalType": "struct Tuple19[]",
"name": "properties",
@@ -799,8 +875,13 @@
"inputs": [
{
"components": [
+<<<<<<< HEAD
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
+=======
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
<<<<<<< HEAD
"internalType": "struct Tuple6",
@@ -812,8 +893,13 @@
},
{
"components": [
+<<<<<<< HEAD
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
+=======
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
<<<<<<< HEAD
"internalType": "struct Tuple6",
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -14,10 +14,8 @@
args: { [key: string]: string }
};
export interface TEthCrossAccount {
- readonly 0: string,
- readonly 1: string | Uint8Array,
- readonly field_0: string,
- readonly field_1: string | Uint8Array,
+ readonly eth: string,
+ readonly sub: string | Uint8Array,
}
export type EthProperty = string[];
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -364,19 +364,15 @@
export class EthCrossAccountGroup extends EthGroupBase {
fromAddress(address: TEthereumAccount): TEthCrossAccount {
return {
- 0: address,
- 1: '0',
- field_0: address,
- field_1: '0',
+ eth: address,
+ sub: '0',
};
}
fromKeyringPair(keyring: IKeyringPair): TEthCrossAccount {
return {
- 0: '0x0000000000000000000000000000000000000000',
- 1: keyring.addressRaw,
- field_0: '0x0000000000000000000000000000000000000000',
- field_1: keyring.addressRaw,
+ eth: '0x0000000000000000000000000000000000000000',
+ sub: keyring.addressRaw,
};
}
}
@@ -429,7 +425,6 @@
ethAddress: EthAddressGroup;
ethNativeContract: NativeContractGroup;
ethContract: ContractGroup;
- ethCrossAccount: EthCrossAccountGroup;
ethProperty: EthPropertyGroup;
constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {