difftreelog
feat delegate erc call to other struct
in: master
9 files changed
crates/evm-coder-macros/src/solidity_interface.rsdiffbeforeafterboth--- a/crates/evm-coder-macros/src/solidity_interface.rs
+++ b/crates/evm-coder-macros/src/solidity_interface.rs
@@ -23,6 +23,7 @@
use syn::{
Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
MetaNameValue, NestedMeta, PatType, Path, PathArguments, ReturnType, Type, spanned::Spanned,
+ parse_str,
};
use crate::{
@@ -35,16 +36,21 @@
name: Ident,
pascal_call_name: Ident,
snake_call_name: Ident,
+ via: Option<(Type, Ident)>,
}
impl Is {
- fn try_from(path: &Path) -> syn::Result<Self> {
+ fn new_via(path: &Path, via: Option<(Type, Ident)>) -> syn::Result<Self> {
let name = parse_ident_from_path(path, false)?.clone();
Ok(Self {
pascal_call_name: pascal_ident_to_call(&name),
snake_call_name: pascal_ident_to_snake_call(&name),
name,
+ via,
})
}
+ fn new(path: &Path) -> syn::Result<Self> {
+ Self::new_via(path, None)
+ }
fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let name = &self.name;
@@ -85,8 +91,18 @@
) -> proc_macro2::TokenStream {
let name = &self.name;
let pascal_call_name = &self.pascal_call_name;
+ let via_typ = self
+ .via
+ .as_ref()
+ .map(|(t, _)| quote! {#t})
+ .unwrap_or_else(|| quote! {Self});
+ let via_map = self
+ .via
+ .as_ref()
+ .map(|(_, i)| quote! {.#i()})
+ .unwrap_or_default();
quote! {
- #call_name::#name(call) => return <Self as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self, Msg {
+ #call_name::#name(call) => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {
call,
caller: c.caller,
value: c.value,
@@ -126,8 +142,46 @@
let mut out = Vec::new();
for item in items {
match item {
- NestedMeta::Meta(Meta::Path(path)) => out.push(Is::try_from(path)?),
- _ => return Err(syn::Error::new(item.span(), "expected path").into()),
+ NestedMeta::Meta(Meta::Path(path)) => out.push(Is::new(path)?),
+ // TODO: replace meta parsing with manual
+ NestedMeta::Meta(Meta::List(list))
+ if list.path.is_ident("via") && list.nested.len() == 3 =>
+ {
+ let mut data = list.nested.iter();
+ let typ = match data.next().expect("len == 3") {
+ NestedMeta::Lit(Lit::Str(s)) => {
+ let v = s.value();
+ let typ: Type = parse_str(&v)?;
+ typ
+ }
+ _ => {
+ return Err(syn::Error::new(
+ item.span(),
+ "via typ should be type in string",
+ )
+ .into())
+ }
+ };
+ let via = match data.next().expect("len == 3") {
+ NestedMeta::Meta(Meta::Path(path)) => path
+ .get_ident()
+ .ok_or_else(|| syn::Error::new(item.span(), "via should be ident"))?,
+ _ => return Err(syn::Error::new(item.span(), "via should be ident").into()),
+ };
+ let path = match data.next().expect("len == 3") {
+ NestedMeta::Meta(Meta::Path(path)) => path,
+ _ => return Err(syn::Error::new(item.span(), "path should be path").into()),
+ };
+
+ out.push(Is::new_via(path, Some((typ, via.clone())))?)
+ }
+ _ => {
+ return Err(syn::Error::new(
+ item.span(),
+ "expected either Name or via(\"Type\", getter, Name)",
+ )
+ .into())
+ }
}
}
Ok(Self(out))
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -14,9 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-pub use pallet_evm::PrecompileOutput;
-pub use pallet_evm::PrecompileResult;
+use evm_coder::{solidity_interface, types::*, execution::Result};
+pub use pallet_evm::{PrecompileOutput, PrecompileResult, account::CrossAccountId};
+use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
+use sp_std::vec::Vec;
+use up_data_structs::Property;
+
+use crate::{Pallet, CollectionHandle, Config};
/// Does not always represent a full collection, for RFT it is either
/// collection (Implementing ERC721), or specific collection token (Implementing ERC20)
@@ -25,3 +30,27 @@
fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult>;
}
+
+#[solidity_interface(name = "CollectionProperties")]
+impl<T: Config> CollectionHandle<T> {
+ fn set_property(&mut self, caller: caller, key: string, value: string) -> Result<()> {
+ <Pallet<T>>::set_collection_property(
+ self,
+ &T::CrossAccountId::from_eth(caller),
+ Property {
+ key: <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "key too large")?,
+ value: <Vec<u8>>::from(value)
+ .try_into()
+ .map_err(|_| "value too large")?,
+ },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn delete_property(&mut self, caller: caller, key: string) -> Result<()> {
+ self.set_property(caller, key, string::new())
+ }
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -595,7 +595,7 @@
.iter()
.map(|(key, value)| Property {
key: key.clone(),
- value: value.clone()
+ value: value.clone(),
})
.collect();
@@ -680,19 +680,20 @@
};
let mut collection_properties = up_data_structs::CollectionProperties::get();
- collection_properties.try_set_from_iter(
- data.properties.into_iter()
- .map(|p| (p.key, p.value))
- ).map_err(|e| -> Error<T> { e.into() })?;
+ collection_properties
+ .try_set_from_iter(data.properties.into_iter().map(|p| (p.key, p.value)))
+ .map_err(|e| -> Error<T> { e.into() })?;
CollectionProperties::<T>::insert(id, collection_properties);
let mut token_props_permissions = PropertiesPermissionMap::new();
- token_props_permissions.try_set_from_iter(
- data.token_property_permissions
- .into_iter()
- .map(|property| (property.key, property.permission))
- ).map_err(|e| -> Error<T> { e.into() })?;
+ token_props_permissions
+ .try_set_from_iter(
+ data.token_property_permissions
+ .into_iter()
+ .map(|property| (property.key, property.permission)),
+ )
+ .map_err(|e| -> Error<T> { e.into() })?;
CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
@@ -806,7 +807,8 @@
CollectionProperties::<T>::try_mutate(collection.id, |properties| {
properties.remove(&property_key)
- }).map_err(|e| -> Error<T> { e.into() })?;
+ })
+ .map_err(|e| -> Error<T> { e.into() })?;
Self::deposit_event(Event::CollectionPropertyDeleted(
collection.id,
@@ -903,11 +905,10 @@
let properties = keys
.into_iter()
.filter_map(|key| {
- properties.get(&key)
- .map(|value| Property {
- key,
- value: value.clone(),
- })
+ properties.get(&key).map(|value| Property {
+ key,
+ value: value.clone(),
+ })
})
.collect();
pallets/fungible/src/erc.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/>.1617use core::char::{REPLACEMENT_CHARACTER, decode_utf16};18use core::convert::TryInto;19use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};20use up_data_structs::CollectionMode;21use pallet_common::erc::{CommonEvmHandler, PrecompileResult};22use sp_core::{H160, U256};23use sp_std::vec::Vec;24use pallet_evm::account::CrossAccountId;25use pallet_evm_coder_substrate::{call, dispatch_to_evm};26use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};2728use crate::{29 Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,30 weights::WeightInfo,31};3233#[derive(ToLog)]34pub enum ERC20Events {35 Transfer {36 #[indexed]37 from: address,38 #[indexed]39 to: address,40 value: uint256,41 },42 Approval {43 #[indexed]44 owner: address,45 #[indexed]46 spender: address,47 value: uint256,48 },49}5051#[solidity_interface(name = "ERC20", events(ERC20Events))]52impl<T: Config> FungibleHandle<T> {53 fn name(&self) -> Result<string> {54 Ok(decode_utf16(self.name.iter().copied())55 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))56 .collect::<string>())57 }58 fn symbol(&self) -> Result<string> {59 Ok(string::from_utf8_lossy(&self.token_prefix).into())60 }61 fn total_supply(&self) -> Result<uint256> {62 self.consume_store_reads(1)?;63 Ok(<TotalSupply<T>>::get(self.id).into())64 }6566 fn decimals(&self) -> Result<uint8> {67 Ok(if let CollectionMode::Fungible(decimals) = &self.mode {68 *decimals69 } else {70 unreachable!()71 })72 }73 fn balance_of(&self, owner: address) -> Result<uint256> {74 self.consume_store_reads(1)?;75 let owner = T::CrossAccountId::from_eth(owner);76 let balance = <Balance<T>>::get((self.id, owner));77 Ok(balance.into())78 }79 #[weight(<SelfWeightOf<T>>::transfer())]80 fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {81 let caller = T::CrossAccountId::from_eth(caller);82 let to = T::CrossAccountId::from_eth(to);83 let amount = amount.try_into().map_err(|_| "amount overflow")?;84 let budget = self85 .recorder86 .weight_calls_budget(<StructureWeight<T>>::find_parent());8788 <Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;89 Ok(true)90 }91 #[weight(<SelfWeightOf<T>>::transfer_from())]92 fn transfer_from(93 &mut self,94 caller: caller,95 from: address,96 to: address,97 amount: uint256,98 ) -> Result<bool> {99 let caller = T::CrossAccountId::from_eth(caller);100 let from = T::CrossAccountId::from_eth(from);101 let to = T::CrossAccountId::from_eth(to);102 let amount = amount.try_into().map_err(|_| "amount overflow")?;103 let budget = self104 .recorder105 .weight_calls_budget(<StructureWeight<T>>::find_parent());106107 <Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)108 .map_err(dispatch_to_evm::<T>)?;109 Ok(true)110 }111 #[weight(<SelfWeightOf<T>>::approve())]112 fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {113 let caller = T::CrossAccountId::from_eth(caller);114 let spender = T::CrossAccountId::from_eth(spender);115 let amount = amount.try_into().map_err(|_| "amount overflow")?;116117 <Pallet<T>>::set_allowance(self, &caller, &spender, amount)118 .map_err(dispatch_to_evm::<T>)?;119 Ok(true)120 }121 fn allowance(&self, owner: address, spender: address) -> Result<uint256> {122 self.consume_store_reads(1)?;123 let owner = T::CrossAccountId::from_eth(owner);124 let spender = T::CrossAccountId::from_eth(spender);125126 Ok(<Allowance<T>>::get((self.id, owner, spender)).into())127 }128}129130#[solidity_interface(name = "ERC20UniqueExtensions")]131impl<T: Config> FungibleHandle<T> {132 #[weight(<SelfWeightOf<T>>::burn_from())]133 fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {134 let caller = T::CrossAccountId::from_eth(caller);135 let from = T::CrossAccountId::from_eth(from);136 let amount = amount.try_into().map_err(|_| "amount overflow")?;137 let budget = self138 .recorder139 .weight_calls_budget(<StructureWeight<T>>::find_parent());140141 <Pallet<T>>::burn_from(self, &caller, &from, amount, &budget)142 .map_err(dispatch_to_evm::<T>)?;143 Ok(true)144 }145}146147#[solidity_interface(name = "UniqueFungible", is(ERC20))]148impl<T: Config> FungibleHandle<T> {}149150generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);151generate_stubgen!(gen_iface, UniqueFungibleCall<()>, false);152153impl<T: Config> CommonEvmHandler for FungibleHandle<T> {154 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");155156 fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {157 call::<T, UniqueFungibleCall<T>, _>(*source, self, value, input)158 }159}pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -110,6 +110,9 @@
pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
self.0
}
+ pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {
+ &mut self.0
+ }
}
impl<T: Config> WithRecorder<T> for FungibleHandle<T> {
fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -391,11 +391,10 @@
keys.into_iter()
.filter_map(|key| {
- properties.get(&key)
- .map(|value| Property {
- key,
- value: value.clone(),
- })
+ properties.get(&key).map(|value| Property {
+ key,
+ value: value.clone(),
+ })
})
.collect()
}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -26,7 +26,8 @@
use sp_core::{H160, U256};
use sp_std::{vec::Vec, vec};
use pallet_common::{
- erc::{CommonEvmHandler, PrecompileResult},
+ erc::{CommonEvmHandler, PrecompileResult, CollectionPropertiesCall},
+ CollectionHandle,
};
use pallet_evm::account::CrossAccountId;
use pallet_evm_coder_substrate::call;
@@ -504,6 +505,7 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
+ via("CollectionHandle<T>", common_mut, CollectionProperties)
)
)]
impl<T: Config> NonfungibleHandle<T> {}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -142,6 +142,9 @@
pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
self.0
}
+ pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {
+ &mut self.0
+ }
}
impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
@@ -302,7 +305,8 @@
<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
properties.remove(&property_key)
- }).map_err(|e| -> CommonError<T> { e.into() })?;
+ })
+ .map_err(|e| -> CommonError<T> { e.into() })?;
<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
collection.id,
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -699,7 +699,7 @@
fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>
where
- I: Iterator<Item=(PropertyKey, Self::Value)>
+ I: Iterator<Item = (PropertyKey, Self::Value)>,
{
for (key, value) in iter {
self.try_set(key, value)?;
@@ -711,7 +711,9 @@
#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]
#[derivative(Default(bound = ""))]
-pub struct PropertiesMap<Value>(BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>);
+pub struct PropertiesMap<Value>(
+ BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,
+);
impl<Value> PropertiesMap<Value> {
pub fn new() -> Self {