difftreelog
feat Implementations solidity traits to generate solidity code for macro AbiCoder
in: master
3 files changed
crates/evm-coder/procedural/src/abi_derive.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/abi_derive.rs
+++ b/crates/evm-coder/procedural/src/abi_derive.rs
@@ -28,15 +28,25 @@
let can_be_plcaed_in_vec = impl_can_be_placed_in_vec(name);
let abi_type = impl_abi_type(name, field_types.clone());
- let abi_read = impl_abi_read(name, is_named_fields, field_names.clone(), field_types);
- let abi_write = impl_abi_write(name, is_named_fields, params_count, field_names);
- // let solidity_tuple_type =
+ let abi_read = impl_abi_read(
+ name,
+ is_named_fields,
+ field_names.clone(),
+ field_types.clone(),
+ );
+ let abi_write = impl_abi_write(name, is_named_fields, params_count, field_names.clone());
+ let solidity_type = impl_solidity_type(name, field_types.clone(), params_count);
+ let solidity_type_name = impl_solidity_type_name(name, field_types.clone(), params_count);
+ let solidity_struct_collect = impl_solidity_struct_collect(name, field_names, field_types);
Ok(quote! {
#can_be_plcaed_in_vec
#abi_type
#abi_read
#abi_write
+ #solidity_type
+ #solidity_type_name
+ #solidity_struct_collect
})
}
@@ -173,3 +183,112 @@
}
)
}
+
+fn impl_solidity_type<'a>(
+ name: &syn::Ident,
+ field_types: impl Iterator<Item = &'a syn::Type> + Clone,
+ params_count: usize,
+) -> proc_macro2::TokenStream {
+ let len = proc_macro2::Literal::usize_suffixed(params_count);
+ quote! {
+ #[cfg(feature = "stubgen")]
+ impl ::evm_coder::solidity::SolidityType for #name {
+ fn names(tc: &::evm_coder::solidity::TypeCollector) -> Vec<String> {
+ let mut collected =
+ Vec::with_capacity(<Self as ::evm_coder::solidity::SolidityType>::len());
+ #({
+ let mut out = String::new();
+ <#field_types as ::evm_coder::solidity::SolidityTypeName>::solidity_name(&mut out, tc)
+ .expect("no fmt error");
+ collected.push(out);
+ })*
+ collected
+ }
+
+ fn len() -> usize {
+ #len
+ }
+ }
+ }
+}
+
+fn impl_solidity_type_name<'a>(
+ name: &syn::Ident,
+ field_types: impl Iterator<Item = &'a syn::Type> + Clone,
+ params_count: usize,
+) -> proc_macro2::TokenStream {
+ let arg_dafaults = field_types.enumerate().map(|(i, ty)| {
+ let mut defult_value = quote!(<#ty as ::evm_coder::solidity::SolidityTypeName
+ >::solidity_default(writer, tc)?;);
+ let last_item = params_count - 1;
+ if i != last_item {
+ defult_value.extend(quote! {write!(writer, ",")?;})
+ }
+ defult_value
+ });
+
+ quote! {
+ #[cfg(feature = "stubgen")]
+ impl ::evm_coder::solidity::SolidityTypeName for #name {
+ fn solidity_name(
+ writer: &mut impl ::core::fmt::Write,
+ tc: &::evm_coder::solidity::TypeCollector,
+ ) -> ::core::fmt::Result {
+ write!(writer, "{}", tc.collect_struct::<Self>())
+ }
+
+ fn is_simple() -> bool {
+ false
+ }
+
+ fn solidity_default(
+ writer: &mut impl ::core::fmt::Write,
+ tc: &::evm_coder::solidity::TypeCollector,
+ ) -> ::core::fmt::Result {
+ write!(writer, "{}(", tc.collect_struct::<Self>())?;
+
+ #(#arg_dafaults)*
+
+ write!(writer, ")")
+ }
+ }
+ }
+}
+
+fn impl_solidity_struct_collect<'a>(
+ name: &syn::Ident,
+ field_names: impl Iterator<Item = proc_macro2::Ident> + Clone,
+ field_types: impl Iterator<Item = &'a syn::Type> + Clone,
+) -> proc_macro2::TokenStream {
+ let string_name = name.to_string();
+ let name_type = field_names
+ .into_iter()
+ .zip(field_types.into_iter())
+ .map(|(name, ty)| {
+ let name = format!("{}", name);
+ quote!(
+ write!(str, "\t{} ", <#ty as ::evm_coder::solidity::StructCollect>::name()).unwrap();
+ write!(str, "{};", #name).unwrap();
+ )
+ });
+
+ quote! {
+ #[cfg(feature = "stubgen")]
+ impl ::evm_coder::solidity::StructCollect for #name {
+ fn name() -> String {
+ #string_name.into()
+ }
+
+ fn declaration() -> String {
+ use std::fmt::Write;
+
+ let mut str = String::new();
+ writeln!(str, "/// @dev Cross account struct").unwrap();
+ writeln!(str, "struct {} {{", Self::name()).unwrap();
+ #(#name_type)*
+ writeln!(str, "}}").unwrap();
+ str
+ }
+ }
+ }
+}
crates/evm-coder/src/solidity/impls.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity/impls.rs
+++ b/crates/evm-coder/src/solidity/impls.rs
@@ -1,4 +1,4 @@
-use super::{TypeCollector, SolidityTypeName, SolidityType};
+use super::{TypeCollector, SolidityTypeName, SolidityType, StructCollect};
use crate::{sealed, types::*};
use core::fmt;
@@ -16,6 +16,16 @@
write!(writer, $default)
}
}
+
+ impl StructCollect for $ty {
+ fn name() -> String {
+ $name.to_string()
+ }
+
+ fn declaration() -> String {
+ String::default()
+ }
+ }
)*
};
}
pallets/common/src/eth.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The module contains a number of functions for converting and checking ethereum identifiers.1819use evm_coder::{20 AbiCoder,21 types::{uint256, address},22};23pub use pallet_evm::{Config, account::CrossAccountId};24use sp_core::H160;25use up_data_structs::CollectionId;2627// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 128// TODO: Unhardcode prefix29const ETH_COLLECTION_PREFIX: [u8; 16] = [30 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,31];3233/// Maps the ethereum address of the collection in substrate.34pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {35 if eth[0..16] != ETH_COLLECTION_PREFIX {36 return None;37 }38 let mut id_bytes = [0; 4];39 id_bytes.copy_from_slice(ð[16..20]);40 Some(CollectionId(u32::from_be_bytes(id_bytes)))41}4243/// Maps the substrate collection id in ethereum.44pub fn collection_id_to_address(id: CollectionId) -> H160 {45 let mut out = [0; 20];46 out[0..16].copy_from_slice(Ð_COLLECTION_PREFIX);47 out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));48 H160(out)49}5051/// Check if the ethereum address is a collection.52pub fn is_collection(address: &H160) -> bool {53 address[0..16] == ETH_COLLECTION_PREFIX54}5556/// Convert `CrossAccountId` to `uint256`.57pub fn convert_cross_account_to_uint256<T: Config>(from: &T::CrossAccountId) -> uint25658where59 T::AccountId: AsRef<[u8; 32]>,60{61 let slice = from.as_sub().as_ref();62 uint256::from_big_endian(slice)63}6465/// Convert `uint256` to `CrossAccountId`.66pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId67where68 T::AccountId: From<[u8; 32]>,69{70 let mut new_admin_arr = [0_u8; 32];71 from.to_big_endian(&mut new_admin_arr);72 let account_id = T::AccountId::from(new_admin_arr);73 T::CrossAccountId::from_sub(account_id)74}7576/// Convert `CrossAccountId` to `(address, uint256)`.77pub fn convert_cross_account_to_tuple<T: Config>(78 cross_account_id: &T::CrossAccountId,79) -> (address, uint256)80where81 T::AccountId: AsRef<[u8; 32]>,82{83 if cross_account_id.is_canonical_substrate() {84 let sub = convert_cross_account_to_uint256::<T>(cross_account_id);85 (Default::default(), sub)86 } else {87 let eth = *cross_account_id.as_eth();88 (eth, Default::default())89 }90}9192/// Convert tuple `(address, uint256)` to `CrossAccountId`.93///94/// If `address` in the tuple has *default* value, then the canonical form is substrate,95/// if `uint256` has *default* value, then the ethereum form is canonical,96/// if both values are *default* or *non default*, then this is considered an invalid address and `Error` is returned.97pub fn convert_tuple_to_cross_account<T: Config>(98 eth_cross_account_id: (address, uint256),99) -> evm_coder::execution::Result<T::CrossAccountId>100where101 T::AccountId: From<[u8; 32]>,102{103 if eth_cross_account_id == Default::default() {104 Err("All fields of cross account is zeroed".into())105 } else if eth_cross_account_id.0 == Default::default() {106 Ok(convert_uint256_to_cross_account::<T>(107 eth_cross_account_id.1,108 ))109 } else if eth_cross_account_id.1 == Default::default() {110 Ok(T::CrossAccountId::from_eth(eth_cross_account_id.0))111 } else {112 Err("All fields of cross account is non zeroed".into())113 }114}115116#[derive(Debug, Default, AbiCoder)]117pub struct EthCrossAccount {118 pub(crate) eth: address,119 pub(crate) sub: uint256,120}121122impl EthCrossAccount {123 pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self124 where125 T: pallet_evm::account::Config,126 T::AccountId: AsRef<[u8; 32]>,127 {128 if cross_account_id.is_canonical_substrate() {129 Self {130 eth: Default::default(),131 sub: convert_cross_account_to_uint256::<T>(cross_account_id),132 }133 } else {134 Self {135 eth: *cross_account_id.as_eth(),136 sub: Default::default(),137 }138 }139 }140141 pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>142 where143 T: pallet_evm::account::Config,144 T::AccountId: From<[u8; 32]>,145 {146 if self.eth == Default::default() && self.sub == Default::default() {147 Err("All fields of cross account is zeroed".into())148 } else if self.eth == Default::default() {149 Ok(convert_uint256_to_cross_account::<T>(self.sub))150 } else if self.sub == Default::default() {151 Ok(T::CrossAccountId::from_eth(self.eth))152 } else {153 Err("All fields of cross account is non zeroed".into())154 }155 }156}157158#[cfg(feature = "stubgen")]159impl ::evm_coder::solidity::SolidityType for EthCrossAccount {160 fn names(tc: &::evm_coder::solidity::TypeCollector) -> Vec<String> {161 let mut collected =162 Vec::with_capacity(<Self as ::evm_coder::solidity::SolidityType>::len());163 {164 let mut out = String::new();165 <address as ::evm_coder::solidity::SolidityTypeName>::solidity_name(&mut out, tc)166 .expect("no fmt error");167 collected.push(out);168 }169 {170 let mut out = String::new();171 <uint256 as ::evm_coder::solidity::SolidityTypeName>::solidity_name(&mut out, tc)172 .expect("no fmt error");173 collected.push(out);174 }175 collected176 }177178 fn len() -> usize {179 2180 }181}182183#[cfg(feature = "stubgen")]184impl ::evm_coder::solidity::SolidityTypeName for EthCrossAccount {185 fn solidity_name(186 writer: &mut impl ::core::fmt::Write,187 tc: &::evm_coder::solidity::TypeCollector,188 ) -> ::core::fmt::Result {189 write!(writer, "{}", tc.collect_struct::<Self>())190 }191192 fn is_simple() -> bool {193 false194 }195196 fn solidity_default(197 writer: &mut impl ::core::fmt::Write,198 tc: &::evm_coder::solidity::TypeCollector,199 ) -> ::core::fmt::Result {200 write!(writer, "{}(", tc.collect_struct::<Self>())?;201 address::solidity_default(writer, tc)?;202 write!(writer, ",")?;203 uint256::solidity_default(writer, tc)?;204 write!(writer, ")")205 }206}207208#[cfg(feature = "stubgen")]209impl ::evm_coder::solidity::StructCollect for EthCrossAccount {210 fn name() -> String {211 "EthCrossAccount".into()212 }213214 fn declaration() -> String {215 use std::fmt::Write;216217 let mut str = String::new();218 writeln!(str, "/// @dev Cross account struct").unwrap();219 writeln!(str, "struct {} {{", Self::name()).unwrap();220 writeln!(str, "\taddress eth;").unwrap();221 writeln!(str, "\tuint256 sub;").unwrap();222 writeln!(str, "}}").unwrap();223 str224 }225}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//! The module contains a number of functions for converting and checking ethereum identifiers.1819use evm_coder::{20 AbiCoder,21 types::{uint256, address},22};23pub use pallet_evm::{Config, account::CrossAccountId};24use sp_core::H160;25use up_data_structs::CollectionId;2627// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 128// TODO: Unhardcode prefix29const ETH_COLLECTION_PREFIX: [u8; 16] = [30 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,31];3233/// Maps the ethereum address of the collection in substrate.34pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {35 if eth[0..16] != ETH_COLLECTION_PREFIX {36 return None;37 }38 let mut id_bytes = [0; 4];39 id_bytes.copy_from_slice(ð[16..20]);40 Some(CollectionId(u32::from_be_bytes(id_bytes)))41}4243/// Maps the substrate collection id in ethereum.44pub fn collection_id_to_address(id: CollectionId) -> H160 {45 let mut out = [0; 20];46 out[0..16].copy_from_slice(Ð_COLLECTION_PREFIX);47 out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));48 H160(out)49}5051/// Check if the ethereum address is a collection.52pub fn is_collection(address: &H160) -> bool {53 address[0..16] == ETH_COLLECTION_PREFIX54}5556/// Convert `CrossAccountId` to `uint256`.57pub fn convert_cross_account_to_uint256<T: Config>(from: &T::CrossAccountId) -> uint25658where59 T::AccountId: AsRef<[u8; 32]>,60{61 let slice = from.as_sub().as_ref();62 uint256::from_big_endian(slice)63}6465/// Convert `uint256` to `CrossAccountId`.66pub fn convert_uint256_to_cross_account<T: Config>(from: uint256) -> T::CrossAccountId67where68 T::AccountId: From<[u8; 32]>,69{70 let mut new_admin_arr = [0_u8; 32];71 from.to_big_endian(&mut new_admin_arr);72 let account_id = T::AccountId::from(new_admin_arr);73 T::CrossAccountId::from_sub(account_id)74}7576/// Convert `CrossAccountId` to `(address, uint256)`.77pub fn convert_cross_account_to_tuple<T: Config>(78 cross_account_id: &T::CrossAccountId,79) -> (address, uint256)80where81 T::AccountId: AsRef<[u8; 32]>,82{83 if cross_account_id.is_canonical_substrate() {84 let sub = convert_cross_account_to_uint256::<T>(cross_account_id);85 (Default::default(), sub)86 } else {87 let eth = *cross_account_id.as_eth();88 (eth, Default::default())89 }90}9192/// Convert tuple `(address, uint256)` to `CrossAccountId`.93///94/// If `address` in the tuple has *default* value, then the canonical form is substrate,95/// if `uint256` has *default* value, then the ethereum form is canonical,96/// if both values are *default* or *non default*, then this is considered an invalid address and `Error` is returned.97pub fn convert_tuple_to_cross_account<T: Config>(98 eth_cross_account_id: (address, uint256),99) -> evm_coder::execution::Result<T::CrossAccountId>100where101 T::AccountId: From<[u8; 32]>,102{103 if eth_cross_account_id == Default::default() {104 Err("All fields of cross account is zeroed".into())105 } else if eth_cross_account_id.0 == Default::default() {106 Ok(convert_uint256_to_cross_account::<T>(107 eth_cross_account_id.1,108 ))109 } else if eth_cross_account_id.1 == Default::default() {110 Ok(T::CrossAccountId::from_eth(eth_cross_account_id.0))111 } else {112 Err("All fields of cross account is non zeroed".into())113 }114}115116#[derive(Debug, Default, AbiCoder)]117pub struct EthCrossAccount {118 pub(crate) eth: address,119 pub(crate) sub: uint256,120}121122impl EthCrossAccount {123 pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self124 where125 T: pallet_evm::account::Config,126 T::AccountId: AsRef<[u8; 32]>,127 {128 if cross_account_id.is_canonical_substrate() {129 Self {130 eth: Default::default(),131 sub: convert_cross_account_to_uint256::<T>(cross_account_id),132 }133 } else {134 Self {135 eth: *cross_account_id.as_eth(),136 sub: Default::default(),137 }138 }139 }140141 pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>142 where143 T: pallet_evm::account::Config,144 T::AccountId: From<[u8; 32]>,145 {146 if self.eth == Default::default() && self.sub == Default::default() {147 Err("All fields of cross account is zeroed".into())148 } else if self.eth == Default::default() {149 Ok(convert_uint256_to_cross_account::<T>(self.sub))150 } else if self.sub == Default::default() {151 Ok(T::CrossAccountId::from_eth(self.eth))152 } else {153 Err("All fields of cross account is non zeroed".into())154 }155 }156}