difftreelog
feat implement #[weight] macro for evm support
in: master
35 files changed
crates/evm-coder-macros/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder-macros/src/lib.rs
+++ b/crates/evm-coder-macros/src/lib.rs
@@ -211,6 +211,10 @@
pub fn solidity(_args: TokenStream, stream: TokenStream) -> TokenStream {
stream
}
+#[proc_macro_attribute]
+pub fn weight(_args: TokenStream, stream: TokenStream) -> TokenStream {
+ stream
+}
#[proc_macro_derive(ToLog, attributes(indexed))]
pub fn to_log(value: TokenStream) -> TokenStream {
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
@@ -30,11 +30,11 @@
})
}
- fn expand_call_def(&self) -> proc_macro2::TokenStream {
+ fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let name = &self.name;
let pascal_call_name = &self.pascal_call_name;
quote! {
- #name(#pascal_call_name)
+ #name(#pascal_call_name #gen_ref)
}
}
@@ -45,18 +45,32 @@
}
}
- fn expand_supports_interface(&self) -> proc_macro2::TokenStream {
+ fn expand_supports_interface(
+ &self,
+ generics: &proc_macro2::TokenStream,
+ ) -> proc_macro2::TokenStream {
let pascal_call_name = &self.pascal_call_name;
quote! {
- #pascal_call_name::supports_interface(interface_id)
+ <#pascal_call_name #generics>::supports_interface(interface_id)
+ }
+ }
+
+ fn expand_variant_weight(&self) -> proc_macro2::TokenStream {
+ let name = &self.name;
+ quote! {
+ Self::#name(call) => call.weight()
}
}
- fn expand_variant_call(&self) -> proc_macro2::TokenStream {
+ fn expand_variant_call(
+ &self,
+ call_name: &proc_macro2::Ident,
+ generics: &proc_macro2::TokenStream,
+ ) -> proc_macro2::TokenStream {
let name = &self.name;
let pascal_call_name = &self.pascal_call_name;
quote! {
- InternalCall::#name(call) => return <Self as ::evm_coder::Callable<#pascal_call_name>>::call(self, Msg {
+ #call_name::#name(call) => return <Self as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self, Msg {
call,
caller: c.caller,
value: c.value,
@@ -64,20 +78,20 @@
}
}
- fn expand_parse(&self) -> proc_macro2::TokenStream {
+ fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let name = &self.name;
let pascal_call_name = &self.pascal_call_name;
quote! {
- if let Some(parsed_call) = #pascal_call_name::parse(method_id, reader)? {
+ if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {
return Ok(Some(Self::#name(parsed_call)))
}
}
}
- fn expand_generator(&self) -> proc_macro2::TokenStream {
+ fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let pascal_call_name = &self.pascal_call_name;
quote! {
- #pascal_call_name::generate_solidity_interface(tc, is_impl);
+ <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);
}
}
@@ -351,6 +365,25 @@
Pure,
}
+pub struct WeightAttr(syn::Expr);
+
+mod keyword {
+ syn::custom_keyword!(weight);
+}
+
+impl syn::parse::Parse for WeightAttr {
+ fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
+ input.parse::<syn::Token![#]>()?;
+ let content;
+ syn::bracketed!(content in input);
+ content.parse::<keyword::weight>()?;
+
+ let weight_content;
+ syn::parenthesized!(weight_content in content);
+ Ok(WeightAttr(weight_content.parse::<syn::Expr>()?))
+ }
+}
+
struct Method {
name: Ident,
camel_name: String,
@@ -362,6 +395,7 @@
has_normal_args: bool,
mutability: Mutability,
result: Type,
+ weight: Option<Expr>,
docs: Vec<String>,
}
impl Method {
@@ -370,6 +404,7 @@
rename_selector: None,
};
let mut docs = Vec::new();
+ let mut weight = None;
for attr in &value.attrs {
let ident = parse_ident_from_path(&attr.path, false)?;
if ident == "solidity" {
@@ -384,6 +419,8 @@
_ => unreachable!(),
};
docs.push(value);
+ } else if ident == "weight" {
+ weight = Some(syn::parse2::<WeightAttr>(attr.to_token_stream())?.0);
}
}
let ident = &value.sig.ident;
@@ -466,6 +503,7 @@
has_normal_args,
mutability,
result: result.clone(),
+ weight,
docs,
})
}
@@ -528,7 +566,7 @@
}
}
- fn expand_variant_call(&self) -> proc_macro2::TokenStream {
+ fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {
let pascal_name = &self.pascal_name;
let name = &self.name;
@@ -555,17 +593,50 @@
let args = self.args.iter().map(|a| a.expand_call_arg());
quote! {
- InternalCall::#pascal_name #matcher => {
+ #call_name::#pascal_name #matcher => {
let result = #receiver #name(
#(
#args,
)*
)?;
- (&result).abi_write(&mut writer);
+ (&result).into_result()
}
}
}
+ fn expand_variant_weight(&self) -> proc_macro2::TokenStream {
+ let pascal_name = &self.pascal_name;
+ if let Some(weight) = &self.weight {
+ let matcher = if self.has_normal_args {
+ let names = self
+ .args
+ .iter()
+ .filter(|a| !a.is_special())
+ .map(|a| &a.name);
+
+ quote! {{
+ #(
+ #names,
+ )*
+ }}
+ } else {
+ quote! {}
+ };
+ quote! {
+ Self::#pascal_name #matcher => (#weight).into()
+ }
+ } else {
+ let matcher = if self.has_normal_args {
+ quote! {{..}}
+ } else {
+ quote! {}
+ };
+ quote! {
+ Self::#pascal_name #matcher => ().into()
+ }
+ }
+ }
+
fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
let camel_name = &self.camel_name;
let mutability = match self.mutability {
@@ -600,6 +671,42 @@
}
}
+fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {
+ if gen.params.is_empty() {
+ return quote! {};
+ }
+ let params = gen.params.iter().map(|p| match p {
+ syn::GenericParam::Type(id) => {
+ let v = &id.ident;
+ quote! {#v}
+ }
+ syn::GenericParam::Lifetime(lt) => {
+ let v = <.lifetime;
+ quote! {#v}
+ }
+ syn::GenericParam::Const(c) => {
+ let i = &c.ident;
+ quote! {#i}
+ }
+ });
+ quote! { #(#params),* }
+}
+fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {
+ if gen.params.is_empty() {
+ return quote! {};
+ }
+ let list = generics_list(gen);
+ quote! { <#list> }
+}
+fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {
+ let list = generics_list(gen);
+ if gen.params.len() == 1 {
+ quote! {#list}
+ } else {
+ quote! { (#list) }
+ }
+}
+
pub struct SolidityInterface {
generics: Generics,
name: Box<syn::Type>,
@@ -628,6 +735,8 @@
let solidity_name = self.info.name.to_string();
let call_name = pascal_ident_to_call(&self.info.name);
let generics = self.generics;
+ let gen_ref = generics_reference(&generics);
+ let gen_data = generics_data(&generics);
let call_sub = self
.info
@@ -635,30 +744,46 @@
.0
.iter()
.chain(self.info.is.0.iter())
- .map(Is::expand_call_def);
+ .map(|c| Is::expand_call_def(c, &gen_ref));
let call_parse = self
.info
.inline_is
.0
.iter()
.chain(self.info.is.0.iter())
- .map(Is::expand_parse);
+ .map(|is| Is::expand_parse(is, &gen_ref));
let call_variants = self
.info
.inline_is
.0
.iter()
.chain(self.info.is.0.iter())
- .map(Is::expand_variant_call);
+ .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));
+ let weight_variants = self
+ .info
+ .inline_is
+ .0
+ .iter()
+ .chain(self.info.is.0.iter())
+ .map(Is::expand_variant_weight);
let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);
- let supports_interface = self.info.is.0.iter().map(Is::expand_supports_interface);
+ let supports_interface = self
+ .info
+ .is
+ .0
+ .iter()
+ .map(|is| Is::expand_supports_interface(is, &gen_ref));
let calls = self.methods.iter().map(Method::expand_call_def);
let consts = self.methods.iter().map(Method::expand_const);
let interface_id = self.methods.iter().map(Method::expand_interface_id);
let parsers = self.methods.iter().map(Method::expand_parse);
- let call_variants_this = self.methods.iter().map(Method::expand_variant_call);
+ let call_variants_this = self
+ .methods
+ .iter()
+ .map(|m| Method::expand_variant_call(m, &call_name));
+ let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);
let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);
// TODO: Inline inline_is
@@ -676,15 +801,15 @@
.0
.iter()
.chain(self.info.inline_is.0.iter())
- .map(Is::expand_generator);
+ .map(|is| Is::expand_generator(is, &gen_ref));
let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);
// let methods = self.methods.iter().map(Method::solidity_def);
quote! {
#[derive(Debug)]
- pub enum #call_name {
- ERC165Call(::evm_coder::ERC165Call),
+ pub enum #call_name #gen_ref {
+ ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),
#(
#calls,
)*
@@ -692,11 +817,11 @@
#call_sub,
)*
}
- impl #call_name {
+ impl #gen_ref #call_name #gen_ref {
#(
#consts
)*
- pub const fn interface_id() -> u32 {
+ pub fn interface_id() -> u32 {
let mut interface_id = 0;
#(#interface_id)*
#(#inline_interface_id)*
@@ -748,11 +873,14 @@
tc.collect(out);
}
}
- impl ::evm_coder::Call for #call_name {
+ impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {
fn parse(method_id: u32, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {
use ::evm_coder::abi::AbiRead;
match method_id {
- ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(::evm_coder::ERC165Call::parse(method_id, reader)?.map(Self::ERC165Call)),
+ ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(
+ ::evm_coder::ERC165Call::parse(method_id, reader)?
+ .map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))
+ ),
#(
#parsers,
)*
@@ -764,19 +892,33 @@
return Ok(None);
}
}
- impl #generics ::evm_coder::Callable<#call_name> for #name {
+ impl #generics ::evm_coder::Weighted for #call_name #gen_ref {
+ #[allow(unused_variables)]
+ fn weight(&self) -> ::evm_coder::execution::DispatchInfo {
+ match self {
+ #(
+ #weight_variants,
+ )*
+ // TODO: It should be very cheap, but not free
+ Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => 100u64.into(),
+ #(
+ #weight_variants_this,
+ )*
+ }
+ }
+ }
+ impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name {
#[allow(unreachable_code)] // In case of no inner calls
- fn call(&mut self, c: Msg<#call_name>) -> Result<::evm_coder::abi::AbiWriter> {
+ fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {
use ::evm_coder::abi::AbiWrite;
- type InternalCall = #call_name;
match c.call {
#(
#call_variants,
)*
- InternalCall::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}) => {
+ #call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {
let mut writer = ::evm_coder::abi::AbiWriter::default();
- writer.bool(&InternalCall::supports_interface(interface_id));
- return Ok(writer);
+ writer.bool(&<#call_name #gen_ref>::supports_interface(interface_id));
+ return Ok(writer.into());
}
_ => {},
}
@@ -787,7 +929,6 @@
)*
_ => unreachable!()
}
- Ok(writer)
}
}
}
crates/evm-coder/src/abi.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi.rs
+++ b/crates/evm-coder/src/abi.rs
@@ -11,7 +11,10 @@
use evm_core::ExitError;
use primitive_types::{H160, U256};
-use crate::{execution::Error, types::string};
+use crate::{
+ execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},
+ types::string,
+};
use crate::execution::Result;
const ABI_ALIGNMENT: usize = 32;
@@ -244,6 +247,7 @@
}
impl_abi_readable!(u32, uint32);
+impl_abi_readable!(u64, uint64);
impl_abi_readable!(u128, uint128);
impl_abi_readable!(U256, uint256);
impl_abi_readable!(H160, address);
@@ -306,6 +310,36 @@
pub trait AbiWrite {
fn abi_write(&self, writer: &mut AbiWriter);
+ fn into_result(&self) -> ResultWithPostInfo<AbiWriter> {
+ let mut writer = AbiWriter::new();
+ self.abi_write(&mut writer);
+ Ok(writer.into())
+ }
+}
+
+impl<T: AbiWrite> AbiWrite for ResultWithPostInfo<T> {
+ // this particular AbiWrite implementation should be split to another trait,
+ // which only implements [`into_result`]
+ //
+ // But due to lack of specialization feature in stable Rust, we can't have
+ // blanket impl of this trait `for T where T: AbiWrite`, so here we abusing
+ // default trait methods for it
+ fn abi_write(&self, _writer: &mut AbiWriter) {
+ debug_assert!(false, "shouldn't be called, see comment")
+ }
+ fn into_result(&self) -> ResultWithPostInfo<AbiWriter> {
+ match self {
+ Ok(v) => Ok(WithPostDispatchInfo {
+ post_info: v.post_info.clone(),
+ data: {
+ let mut out = AbiWriter::new();
+ v.data.abi_write(&mut out);
+ out
+ },
+ }),
+ Err(e) => Err(e.clone()),
+ }
+ }
}
macro_rules! impl_abi_writeable {
crates/evm-coder/src/execution.rsdiffbeforeafterboth--- a/crates/evm-coder/src/execution.rs
+++ b/crates/evm-coder/src/execution.rs
@@ -4,7 +4,9 @@
#[cfg(feature = "std")]
use std::string::{String, ToString};
-#[derive(Debug)]
+use crate::Weight;
+
+#[derive(Debug, Clone)]
pub enum Error {
Revert(String),
Fatal(ExitFatal),
@@ -21,3 +23,55 @@
}
pub type Result<T> = core::result::Result<T, Error>;
+
+pub struct DispatchInfo {
+ pub weight: Weight,
+}
+
+impl From<Weight> for DispatchInfo {
+ fn from(weight: Weight) -> Self {
+ Self { weight }
+ }
+}
+impl From<()> for DispatchInfo {
+ fn from(_: ()) -> Self {
+ Self { weight: 0 }
+ }
+}
+
+#[derive(Default, Clone)]
+pub struct PostDispatchInfo {
+ actual_weight: Option<Weight>,
+}
+
+impl PostDispatchInfo {
+ pub fn calc_unspent(&self, info: &DispatchInfo) -> Weight {
+ info.weight - self.calc_actual_weight(info)
+ }
+
+ pub fn calc_actual_weight(&self, info: &DispatchInfo) -> Weight {
+ if let Some(actual_weight) = self.actual_weight {
+ actual_weight.min(info.weight)
+ } else {
+ info.weight
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct WithPostDispatchInfo<T> {
+ pub data: T,
+ pub post_info: PostDispatchInfo,
+}
+
+impl<T> From<T> for WithPostDispatchInfo<T> {
+ fn from(data: T) -> Self {
+ Self {
+ data,
+ post_info: Default::default(),
+ }
+ }
+}
+
+pub type ResultWithPostInfo<T> =
+ core::result::Result<WithPostDispatchInfo<T>, WithPostDispatchInfo<Error>>;
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -3,10 +3,11 @@
extern crate alloc;
use abi::{AbiRead, AbiReader, AbiWriter};
-pub use evm_coder_macros::{event_topic, fn_selector, solidity_interface, solidity, ToLog};
+pub use evm_coder_macros::{event_topic, fn_selector, solidity_interface, solidity, weight, ToLog};
pub mod abi;
pub mod events;
pub use events::ToLog;
+use execution::DispatchInfo;
pub mod execution;
pub mod solidity;
@@ -57,8 +58,14 @@
fn parse(selector: u32, input: &mut AbiReader) -> execution::Result<Option<Self>>;
}
+pub type Weight = u64;
+
+pub trait Weighted: Call {
+ fn weight(&self) -> DispatchInfo;
+}
+
pub trait Callable<C: Call> {
- fn call(&mut self, call: types::Msg<C>) -> execution::Result<AbiWriter>;
+ fn call(&mut self, call: types::Msg<C>) -> execution::ResultWithPostInfo<AbiWriter>;
}
/// Implementation is implicitly provided for all interfaces
@@ -84,15 +91,20 @@
}
}
+/// Generate "tests", which will generate solidity code on execution and print it to stdout
+/// Script at .maintain/scripts/generate_api.sh can split this output from test runtime
+///
+/// This macro receives type usage as second argument, but you can use anything as generics,
+/// because no bounds are implied
#[macro_export]
macro_rules! generate_stubgen {
- ($name:ident, $decl:ident, $is_impl:literal) => {
+ ($name:ident, $decl:ty, $is_impl:literal) => {
#[test]
#[ignore]
fn $name() {
use evm_coder::solidity::TypeCollector;
let mut out = TypeCollector::new();
- $decl::generate_solidity_interface(&mut out, $is_impl);
+ <$decl>::generate_solidity_interface(&mut out, $is_impl);
println!("=== SNIP START ===");
println!("// SPDX-License-Identifier: OTHER");
println!("// This code is automatically generated");
crates/evm-coder/tests/a.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/a.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-#![allow(dead_code)] // This test only checks that macros is not panicking
-
-use evm_coder::{solidity_interface, types::*, ToLog, execution::Result};
-use evm_coder_macros::solidity;
-
-struct Impls;
-
-#[solidity_interface(name = "OurInterface")]
-impl Impls {
- fn fn_a(&self, _input: uint256) -> Result<bool> {
- todo!()
- }
-}
-
-#[solidity_interface(name = "OurInterface1")]
-impl Impls {
- fn fn_b(&self, _input: uint128) -> Result<uint32> {
- todo!()
- }
-}
-
-#[solidity_interface(
- name = "OurInterface2",
- is(OurInterface),
- inline_is(OurInterface1),
- events(ERC721Log)
-)]
-impl Impls {
- #[solidity(rename_selector = "fnK")]
- fn fn_c(&self, _input: uint32) -> Result<uint8> {
- todo!()
- }
- fn fn_d(&self, _value: uint32) -> Result<uint32> {
- todo!()
- }
-
- fn caller_sensitive(&self, _caller: caller) -> Result<uint8> {
- todo!()
- }
- fn payable(&mut self, _value: value) -> Result<uint8> {
- todo!()
- }
-}
-
-#[derive(ToLog)]
-enum ERC721Log {
- Transfer {
- #[indexed]
- from: address,
- #[indexed]
- to: address,
- value: uint256,
- },
- Eee {
- #[indexed]
- aaa: address,
- bbb: uint256,
- },
-}
-
-struct ERC20;
-
-#[solidity_interface(name = "ERC20")]
-impl ERC20 {
- fn decimals(&self) -> Result<uint8> {
- todo!()
- }
- fn balance_of(&self, _owner: address) -> Result<uint256> {
- todo!()
- }
- fn transfer(&mut self, _caller: caller, _to: address, _value: uint256) -> Result<bool> {
- todo!()
- }
- fn transfer_from(
- &mut self,
- _caller: caller,
- _from: address,
- _to: address,
- _value: uint256,
- ) -> Result<bool> {
- todo!()
- }
- fn approve(&mut self, _caller: caller, _spender: address, _value: uint256) -> Result<bool> {
- todo!()
- }
- fn allowance(&self, _owner: address, _spender: address) -> Result<uint256> {
- todo!()
- }
-}
crates/evm-coder/tests/generics.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/tests/generics.rs
@@ -0,0 +1,20 @@
+use std::marker::PhantomData;
+use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
+
+struct Generic<T>(PhantomData<T>);
+
+#[solidity_interface(name = "GenericIs")]
+impl<T> Generic<T> {
+ fn test_1(&self) -> Result<uint256> {
+ todo!()
+ }
+}
+
+#[solidity_interface(name = "Generic", is(GenericIs))]
+impl<T: Into<u32>> Generic<T> {
+ fn test_2(&self) -> Result<uint256> {
+ todo!()
+ }
+}
+
+generate_stubgen!(gen_iface, GenericCall<()>, false);
crates/evm-coder/tests/log.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/tests/log.rs
@@ -0,0 +1,17 @@
+use evm_coder::{ToLog, types::*};
+
+#[derive(ToLog)]
+enum ERC721Log {
+ Transfer {
+ #[indexed]
+ from: address,
+ #[indexed]
+ to: address,
+ value: uint256,
+ },
+ Eee {
+ #[indexed]
+ aaa: address,
+ bbb: uint256,
+ },
+}
crates/evm-coder/tests/random.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/tests/random.rs
@@ -0,0 +1,65 @@
+#![allow(dead_code)] // This test only checks that macros is not panicking
+
+use evm_coder::{ToLog, execution::Result, solidity_interface, types::*};
+use evm_coder_macros::{solidity, weight};
+
+struct Impls;
+
+#[solidity_interface(name = "OurInterface")]
+impl Impls {
+ fn fn_a(&self, _input: uint256) -> Result<bool> {
+ todo!()
+ }
+}
+
+#[solidity_interface(name = "OurInterface1")]
+impl Impls {
+ fn fn_b(&self, _input: uint128) -> Result<uint32> {
+ todo!()
+ }
+}
+
+#[derive(ToLog)]
+enum OurEvents {
+ Event1 {
+ field1: uint32,
+ },
+ Event2 {
+ field1: uint32,
+ #[indexed]
+ field2: uint32,
+ },
+}
+
+#[solidity_interface(
+ name = "OurInterface2",
+ is(OurInterface),
+ inline_is(OurInterface1),
+ events(OurEvents)
+)]
+impl Impls {
+ #[solidity(rename_selector = "fnK")]
+ fn fn_c(&self, _input: uint32) -> Result<uint8> {
+ todo!()
+ }
+ fn fn_d(&self, _value: uint32) -> Result<uint32> {
+ todo!()
+ }
+
+ fn caller_sensitive(&self, _caller: caller) -> Result<uint8> {
+ todo!()
+ }
+ fn payable(&mut self, _value: value) -> Result<uint8> {
+ todo!()
+ }
+
+ #[weight(*_weight)]
+ fn with_weight(&self, _weight: uint64) -> Result<void> {
+ todo!()
+ }
+
+ /// Doccoment example
+ fn with_doc(&self) -> Result<void> {
+ todo!()
+ }
+}
crates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/tests/solidity_generation.rs
@@ -0,0 +1,35 @@
+use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
+
+struct ERC20;
+
+#[solidity_interface(name = "ERC20")]
+impl ERC20 {
+ fn decimals(&self) -> Result<uint8> {
+ todo!()
+ }
+ /// Get balance of specified owner
+ fn balance_of(&self, _owner: address) -> Result<uint256> {
+ todo!()
+ }
+ fn transfer(&mut self, _caller: caller, _to: address, _value: uint256) -> Result<bool> {
+ todo!()
+ }
+ fn transfer_from(
+ &mut self,
+ _caller: caller,
+ _from: address,
+ _to: address,
+ _value: uint256,
+ ) -> Result<bool> {
+ todo!()
+ }
+ fn approve(&mut self, _caller: caller, _spender: address, _value: uint256) -> Result<bool> {
+ todo!()
+ }
+ fn allowance(&self, _owner: address, _spender: address) -> Result<uint256> {
+ todo!()
+ }
+}
+
+generate_stubgen!(gen_impl, ERC20Call, true);
+generate_stubgen!(gen_iface, ERC20Call, false);
node/cli/Cargo.tomldiffbeforeafterboth--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -268,13 +268,13 @@
jsonrpc-core = '18.0.0'
jsonrpc-pubsub = "18.0.0"
-fc-rpc-core = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fc-consensus = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fc-mapping-sync = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fc-rpc = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fc-db = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fp-rpc = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-pallet-ethereum = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+fc-rpc-core = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fc-consensus = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fc-mapping-sync = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fc-rpc = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fc-db = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fp-rpc = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+pallet-ethereum = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
nft-rpc = { path = "../rpc" }
node/rpc/Cargo.tomldiffbeforeafterboth--- a/node/rpc/Cargo.toml
+++ b/node/rpc/Cargo.toml
@@ -41,12 +41,12 @@
substrate-frame-rpc-system = { git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
tokio = { version = "0.2.25", features = ["macros", "sync"] }
-pallet-ethereum = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fc-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fc-rpc-core = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fc-db = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fc-mapping-sync = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+pallet-ethereum = { git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fc-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fc-rpc-core = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fc-db = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fc-mapping-sync = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
pallet-nft = { path = "../../pallets/nft" }
uc-rpc = { path = "../../client/rpc" }
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -19,7 +19,7 @@
pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
-pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
serde = { version = "1.0.130", default-features = false }
scale-info = { version = "1.0.0", default-features = false, features = [
"derive",
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1,6 +1,7 @@
#![cfg_attr(not(feature = "std"), no_std)]
use core::ops::{Deref, DerefMut};
+use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use sp_std::vec::Vec;
use account::CrossAccountId;
use frame_support::{
@@ -8,6 +9,7 @@
ensure, fail,
traits::{Imbalance, Get, Currency},
};
+use pallet_evm::GasWeightMapping;
use nft_data_structs::{
COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
@@ -27,17 +29,22 @@
pub struct CollectionHandle<T: Config> {
pub id: CollectionId,
collection: Collection<T>,
- pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,
+ pub recorder: SubstrateRecorder<T>,
}
+impl<T: Config> WithRecorder<T> for CollectionHandle<T> {
+ fn recorder(&self) -> &SubstrateRecorder<T> {
+ &self.recorder
+ }
+ fn into_recorder(self) -> SubstrateRecorder<T> {
+ self.recorder
+ }
+}
impl<T: Config> CollectionHandle<T> {
pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {
<CollectionById<T>>::get(id).map(|collection| Self {
id,
collection,
- recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(
- eth::collection_id_to_address(id),
- gas_limit,
- ),
+ recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),
})
}
pub fn new(id: CollectionId) -> Option<Self> {
@@ -46,33 +53,30 @@
pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {
Ok(Self::new(id).ok_or_else(|| <Error<T>>::CollectionNotFound)?)
}
- pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {
- self.recorder.log_sub(log)
+ pub fn log(&self, log: impl evm_coder::ToLog) {
+ self.recorder.log(log)
}
- pub fn log_infallible(&self, log: impl evm_coder::ToLog) {
- self.recorder.log_infallible(log)
+ pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {
+ self.recorder
+ .consume_gas(T::GasWeightMapping::weight_to_gas(
+ <T as frame_system::Config>::DbWeight::get()
+ .read
+ .saturating_mul(reads),
+ ))
}
- #[allow(dead_code)]
- fn consume_gas(&self, gas: u64) -> DispatchResult {
- self.recorder.consume_gas_sub(gas)
- }
- pub fn consume_sload(&self) -> DispatchResult {
- self.recorder.consume_sload_sub()
+ pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {
+ self.recorder
+ .consume_gas(T::GasWeightMapping::weight_to_gas(
+ <T as frame_system::Config>::DbWeight::get()
+ .write
+ .saturating_mul(writes),
+ ))
}
- pub fn consume_sstores(&self, amount: usize) -> DispatchResult {
- self.recorder.consume_sstores_sub(amount)
- }
- pub fn consume_sstore(&self) -> DispatchResult {
- self.recorder.consume_sstore_sub()
- }
- pub fn consume_log(&self, topics: usize, data: usize) -> DispatchResult {
- self.recorder.consume_log_sub(topics, data)
- }
- pub fn submit_logs(self) -> DispatchResult {
+ pub fn submit_logs(self) {
self.recorder.submit_logs()
}
pub fn save(self) -> DispatchResult {
- self.recorder.submit_logs()?;
+ self.recorder.submit_logs();
<CollectionById<T>>::insert(self.id, self.collection);
Ok(())
}
@@ -96,24 +100,20 @@
ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);
Ok(())
}
- pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> Result<bool, DispatchError> {
- self.consume_sload()?;
-
- Ok(*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject)))
+ pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {
+ *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))
}
pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {
- ensure!(self.is_owner_or_admin(subject)?, <Error<T>>::NoPermission);
+ ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);
Ok(())
}
- pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {
- Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)
+ pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {
+ self.limits.owner_can_transfer() && self.is_owner_or_admin(user)
}
- pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {
- Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)
+ pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {
+ self.limits.owner_can_transfer() && self.is_owner_or_admin(user)
}
pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {
- self.consume_sload()?;
-
ensure!(
<Allowlist<T>>::get((self.id, user)),
<Error<T>>::AddressNotInAllowlist
pallets/evm-coder-substrate/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-coder-substrate/Cargo.toml
+++ b/pallets/evm-coder-substrate/Cargo.toml
@@ -4,15 +4,18 @@
edition = "2018"
[dependencies]
-scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
ethereum = { version = "0.9", git = "https://github.com/purestake/ethereum", branch = "joshy-scale-info", default-features = false }
evm-coder = { default-features = false, path = "../../crates/evm-coder" }
-pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
[dependencies.codec]
default-features = false
@@ -31,4 +34,6 @@
"pallet-evm/std",
"frame-support/std",
"frame-system/std",
+ 'frame-benchmarking/std',
]
+runtime-benchmarks = ['frame-benchmarking']
pallets/evm-coder-substrate/src/benchmarking.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/evm-coder-substrate/src/benchmarking.rs
@@ -0,0 +1,8 @@
+use super::*;
+
+use frame_benchmarking::benchmarks;
+
+benchmarks! {
+ // gas_per_second {
+ // }: (pallet_evm::)
+}
pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -2,6 +2,8 @@
#[cfg(not(feature = "std"))]
extern crate alloc;
+// #[cfg(feature = "runtime-benchmarks")]
+// pub mod benchmarking;
pub use pallet::*;
@@ -17,7 +19,10 @@
types::{Msg, value},
};
use frame_support::{ensure};
- use pallet_evm::{ExitError, ExitReason, ExitRevert, ExitSucceed, PrecompileOutput};
+ use pallet_evm::{
+ ExitError, ExitReason, ExitRevert, ExitSucceed, PrecompileOutput, GasWeightMapping,
+ };
+ use frame_system::ensure_signed;
pub use frame_support::dispatch::DispatchResult;
use pallet_ethereum::EthereumTransactionSender;
use sp_std::cell::RefCell;
@@ -25,6 +30,7 @@
use sp_core::{H160, H256};
use ethereum::Log;
use frame_support::{pallet_prelude::*, traits::PalletInfo};
+ use frame_system::pallet_prelude::*;
/// DispatchError is opaque, but we need to somehow extract correct error in case of OutOfGas failure
/// So we have this pallet, which defines OutOfGas error, and knews its own id to check if DispatchError
@@ -40,25 +46,24 @@
#[pallet::config]
pub trait Config: frame_system::Config {
type EthereumTransactionSender: pallet_ethereum::EthereumTransactionSender;
+ type GasWeightMapping: pallet_evm::GasWeightMapping;
}
#[pallet::pallet]
pub struct Pallet<T>(_);
- // FIXME: those items are defined as private in evm_gasometer::consts, and we can't directly use it
- pub const G_LOG: u64 = 375;
- pub const G_LOGDATA: u64 = 8;
- pub const G_LOGTOPIC: u64 = 375;
+ #[pallet::call]
+ impl<T: Config> Pallet<T> {
+ #[pallet::weight(0)]
+ pub fn empty_call(origin: OriginFor<T>) -> DispatchResult {
+ let _sender = ensure_signed(origin)?;
+ Ok(())
+ }
+ }
// From instabul hardfork configuration: https://github.com/rust-blockchain/evm/blob/fd4fd6acc0ca3208d6770fdb3ba407c94cdf97c6/runtime/src/lib.rs#L284
pub const G_SLOAD_WORD: u64 = 800;
pub const G_SSTORE_WORD: u64 = 20000;
-
- fn log_price(data: usize, topics: usize) -> u64 {
- G_LOG
- .saturating_add((data as u64).saturating_mul(G_LOGDATA))
- .saturating_add((topics as u64).saturating_mul(G_LOGTOPIC))
- }
pub fn generate_transaction() -> ethereum::TransactionV0 {
use ethereum::{TransactionV0, TransactionAction, TransactionSignature};
@@ -98,16 +103,10 @@
pub fn is_empty(&self) -> bool {
self.logs.borrow().is_empty()
}
- pub fn log_sub(&self, log: impl ToLog) -> DispatchResult {
- self.log_raw_sub(log.to_log(self.contract))
- }
- pub fn log_raw_sub(&self, log: Log) -> DispatchResult {
- self.consume_gas_sub(log_price(log.data.len(), log.topics.len()))?;
- self.logs.borrow_mut().push(log);
- Ok(())
- }
+ // TODO: Replace with real storage in pallet-ethereum,
+ // same way as it is done with frame_system's Events
/// Doesn't consumes any gas, should be used after consume_log_sub
- pub fn log_infallible(&self, log: impl ToLog) {
+ pub fn log(&self, log: impl ToLog) {
self.logs.borrow_mut().push(log.to_log(self.contract));
}
pub fn retrieve_logs(self) -> Vec<Log> {
@@ -125,9 +124,6 @@
}
pub fn consume_sstore_sub(&self) -> DispatchResult {
self.consume_gas_sub(G_SSTORE_WORD)
- }
- pub fn consume_log_sub(&self, topics: usize, data: usize) -> DispatchResult {
- self.consume_gas_sub(log_price(data, topics))
}
pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {
ensure!(gas != u64::MAX, Error::<T>::OutOfGas);
@@ -154,6 +150,10 @@
*gas_limit -= gas;
Ok(())
}
+ pub fn return_gas(&self, gas: u64) {
+ let mut gas_limit = self.gas_limit.borrow_mut();
+ *gas_limit += gas;
+ }
pub fn evm_to_precompile_output(
self,
@@ -181,12 +181,16 @@
})
}
- pub fn submit_logs(self) -> DispatchResult {
+ pub fn submit_logs(self) {
let logs = self.retrieve_logs();
if logs.is_empty() {
- return Ok(());
+ return;
}
- T::EthereumTransactionSender::submit_logs_transaction(generate_transaction(), logs)
+ T::EthereumTransactionSender::submit_logs_transaction(
+ Default::default(),
+ generate_transaction(),
+ logs,
+ )
}
}
@@ -215,7 +219,31 @@
}
}
- pub fn call_internal<C: evm_coder::Call, E: evm_coder::Callable<C>>(
+ pub trait WithRecorder<T: Config> {
+ fn recorder(&self) -> &SubstrateRecorder<T>;
+ fn into_recorder(self) -> SubstrateRecorder<T>;
+ }
+
+ /// Helper to simplify implementing bridge between evm-coder definitions and pallet-evm
+ pub fn call<
+ T: Config,
+ C: evm_coder::Call + evm_coder::Weighted,
+ E: evm_coder::Callable<C> + WithRecorder<T>,
+ >(
+ caller: H160,
+ mut e: E,
+ value: value,
+ input: &[u8],
+ ) -> Option<PrecompileOutput> {
+ let result = call_internal(caller, &mut e, value, input);
+ e.into_recorder().evm_to_precompile_output(result)
+ }
+
+ fn call_internal<
+ T: Config,
+ C: evm_coder::Call + evm_coder::Weighted,
+ E: evm_coder::Callable<C> + WithRecorder<T>,
+ >(
caller: H160,
e: &mut E,
value: value,
@@ -227,11 +255,28 @@
return Ok(None);
}
let call = call.unwrap();
- e.call(Msg {
+
+ let dispatch_info = call.weight();
+ e.recorder()
+ .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;
+
+ match e.call(Msg {
call,
caller,
value,
- })
- .map(Some)
+ }) {
+ Ok(v) => {
+ let unspent = v.post_info.calc_unspent(&dispatch_info);
+ e.recorder()
+ .return_gas(T::GasWeightMapping::weight_to_gas(unspent));
+ Ok(Some(v.data))
+ }
+ Err(v) => {
+ let unspent = v.post_info.calc_unspent(&dispatch_info);
+ e.recorder()
+ .return_gas(T::GasWeightMapping::weight_to_gas(unspent));
+ Err(v.data)
+ }
+ }
}
}
pallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-contract-helpers/Cargo.toml
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -4,7 +4,9 @@
edition = "2018"
[dependencies]
-scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
@@ -12,7 +14,7 @@
sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
-pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
up-sponsorship = { default-features = false, path = '../../primitives/sponsorship' }
log = "0.4.14"
pallets/evm-contract-helpers/exp.rsdiffbeforeafterboth1#![feature(prelude_import)]2#[prelude_import]3use std::prelude::rust_2018::*;4#[macro_use]5extern crate std;6pub use pallet::*;7pub use eth::*;8pub mod eth {9 use core::marker::PhantomData;10 use evm_coder::{abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*};11 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};12 use pallet_evm::{ExitReason, ExitRevert, OnCreate, OnMethodCall, PrecompileOutput};13 use sp_core::H160;14 use crate::{15 AllowlistEnabled, Config, Owner, Pallet, SelfSponsoring, SponsorBasket, SponsoringRateLimit,16 };17 use frame_support::traits::Get;18 use up_sponsorship::SponsorshipHandler;19 use sp_std::{convert::TryInto, vec::Vec};20 struct ContractHelpers<T: Config>(SubstrateRecorder<T>);21 impl<T: Config> WithRecorder<T> for ContractHelpers<T> {22 fn recorder(&self) -> &SubstrateRecorder<T> {23 &self.024 }25 fn into_recorder(self) -> SubstrateRecorder<T> {26 self.027 }28 }29 impl<T: Config> ContractHelpers<T> {30 fn contract_owner(&self, contract_address: address) -> Result<address> {31 Ok(<Owner<T>>::get(contract_address))32 }33 fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {34 Ok(<SelfSponsoring<T>>::get(contract_address))35 }36 fn toggle_sponsoring(37 &mut self,38 caller: caller,39 contract_address: address,40 enabled: bool,41 ) -> Result<void> {42 <Pallet<T>>::ensure_owner(contract_address, caller)?;43 <Pallet<T>>::toggle_sponsoring(contract_address, enabled);44 Ok(())45 }46 fn set_sponsoring_rate_limit(47 &mut self,48 caller: caller,49 contract_address: address,50 rate_limit: uint32,51 ) -> Result<void> {52 <Pallet<T>>::ensure_owner(contract_address, caller)?;53 <Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());54 Ok(())55 }56 fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {57 Ok(<SponsoringRateLimit<T>>::get(contract_address)58 .try_into()59 .map_err(|_| "rate limit > u32::MAX")?)60 }61 fn allowed(&self, contract_address: address, user: address) -> Result<bool> {62 Ok(<Pallet<T>>::allowed(contract_address, user, true))63 }64 fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {65 Ok(<AllowlistEnabled<T>>::get(contract_address))66 }67 fn toggle_allowlist(68 &mut self,69 caller: caller,70 contract_address: address,71 enabled: bool,72 ) -> Result<void> {73 <Pallet<T>>::ensure_owner(contract_address, caller)?;74 <Pallet<T>>::toggle_allowlist(contract_address, enabled);75 Ok(())76 }77 fn toggle_allowed(78 &mut self,79 caller: caller,80 contract_address: address,81 user: address,82 allowed: bool,83 ) -> Result<void> {84 <Pallet<T>>::ensure_owner(contract_address, caller)?;85 <Pallet<T>>::toggle_allowed(contract_address, user, allowed);86 Ok(())87 }88 }89 pub enum ContractHelpersCall<T: Config> {90 ERC165Call(::evm_coder::ERC165Call, PhantomData<(T)>),91 ContractOwner {92 contract_address: address,93 },94 SponsoringEnabled {95 contract_address: address,96 },97 ToggleSponsoring {98 contract_address: address,99 enabled: bool,100 },101 SetSponsoringRateLimit {102 contract_address: address,103 rate_limit: uint32,104 },105 GetSponsoringRateLimit {106 contract_address: address,107 },108 Allowed {109 contract_address: address,110 user: address,111 },112 AllowlistEnabled {113 contract_address: address,114 },115 ToggleAllowlist {116 contract_address: address,117 enabled: bool,118 },119 ToggleAllowed {120 contract_address: address,121 user: address,122 allowed: bool,123 },124 }125 #[automatically_derived]126 #[allow(unused_qualifications)]127 impl<T: ::core::fmt::Debug + Config> ::core::fmt::Debug for ContractHelpersCall<T> {128 fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {129 match (&*self,) {130 (&ContractHelpersCall::ERC165Call(ref __self_0, ref __self_1),) => {131 let debug_trait_builder =132 &mut ::core::fmt::Formatter::debug_tuple(f, "ERC165Call");133 let _ = ::core::fmt::DebugTuple::field(debug_trait_builder, &&(*__self_0));134 let _ = ::core::fmt::DebugTuple::field(debug_trait_builder, &&(*__self_1));135 ::core::fmt::DebugTuple::finish(debug_trait_builder)136 }137 (&ContractHelpersCall::ContractOwner {138 contract_address: ref __self_0,139 },) => {140 let debug_trait_builder =141 &mut ::core::fmt::Formatter::debug_struct(f, "ContractOwner");142 let _ = ::core::fmt::DebugStruct::field(143 debug_trait_builder,144 "contract_address",145 &&(*__self_0),146 );147 ::core::fmt::DebugStruct::finish(debug_trait_builder)148 }149 (&ContractHelpersCall::SponsoringEnabled {150 contract_address: ref __self_0,151 },) => {152 let debug_trait_builder =153 &mut ::core::fmt::Formatter::debug_struct(f, "SponsoringEnabled");154 let _ = ::core::fmt::DebugStruct::field(155 debug_trait_builder,156 "contract_address",157 &&(*__self_0),158 );159 ::core::fmt::DebugStruct::finish(debug_trait_builder)160 }161 (&ContractHelpersCall::ToggleSponsoring {162 contract_address: ref __self_0,163 enabled: ref __self_1,164 },) => {165 let debug_trait_builder =166 &mut ::core::fmt::Formatter::debug_struct(f, "ToggleSponsoring");167 let _ = ::core::fmt::DebugStruct::field(168 debug_trait_builder,169 "contract_address",170 &&(*__self_0),171 );172 let _ = ::core::fmt::DebugStruct::field(173 debug_trait_builder,174 "enabled",175 &&(*__self_1),176 );177 ::core::fmt::DebugStruct::finish(debug_trait_builder)178 }179 (&ContractHelpersCall::SetSponsoringRateLimit {180 contract_address: ref __self_0,181 rate_limit: ref __self_1,182 },) => {183 let debug_trait_builder =184 &mut ::core::fmt::Formatter::debug_struct(f, "SetSponsoringRateLimit");185 let _ = ::core::fmt::DebugStruct::field(186 debug_trait_builder,187 "contract_address",188 &&(*__self_0),189 );190 let _ = ::core::fmt::DebugStruct::field(191 debug_trait_builder,192 "rate_limit",193 &&(*__self_1),194 );195 ::core::fmt::DebugStruct::finish(debug_trait_builder)196 }197 (&ContractHelpersCall::GetSponsoringRateLimit {198 contract_address: ref __self_0,199 },) => {200 let debug_trait_builder =201 &mut ::core::fmt::Formatter::debug_struct(f, "GetSponsoringRateLimit");202 let _ = ::core::fmt::DebugStruct::field(203 debug_trait_builder,204 "contract_address",205 &&(*__self_0),206 );207 ::core::fmt::DebugStruct::finish(debug_trait_builder)208 }209 (&ContractHelpersCall::Allowed {210 contract_address: ref __self_0,211 user: ref __self_1,212 },) => {213 let debug_trait_builder =214 &mut ::core::fmt::Formatter::debug_struct(f, "Allowed");215 let _ = ::core::fmt::DebugStruct::field(216 debug_trait_builder,217 "contract_address",218 &&(*__self_0),219 );220 let _ =221 ::core::fmt::DebugStruct::field(debug_trait_builder, "user", &&(*__self_1));222 ::core::fmt::DebugStruct::finish(debug_trait_builder)223 }224 (&ContractHelpersCall::AllowlistEnabled {225 contract_address: ref __self_0,226 },) => {227 let debug_trait_builder =228 &mut ::core::fmt::Formatter::debug_struct(f, "AllowlistEnabled");229 let _ = ::core::fmt::DebugStruct::field(230 debug_trait_builder,231 "contract_address",232 &&(*__self_0),233 );234 ::core::fmt::DebugStruct::finish(debug_trait_builder)235 }236 (&ContractHelpersCall::ToggleAllowlist {237 contract_address: ref __self_0,238 enabled: ref __self_1,239 },) => {240 let debug_trait_builder =241 &mut ::core::fmt::Formatter::debug_struct(f, "ToggleAllowlist");242 let _ = ::core::fmt::DebugStruct::field(243 debug_trait_builder,244 "contract_address",245 &&(*__self_0),246 );247 let _ = ::core::fmt::DebugStruct::field(248 debug_trait_builder,249 "enabled",250 &&(*__self_1),251 );252 ::core::fmt::DebugStruct::finish(debug_trait_builder)253 }254 (&ContractHelpersCall::ToggleAllowed {255 contract_address: ref __self_0,256 user: ref __self_1,257 allowed: ref __self_2,258 },) => {259 let debug_trait_builder =260 &mut ::core::fmt::Formatter::debug_struct(f, "ToggleAllowed");261 let _ = ::core::fmt::DebugStruct::field(262 debug_trait_builder,263 "contract_address",264 &&(*__self_0),265 );266 let _ =267 ::core::fmt::DebugStruct::field(debug_trait_builder, "user", &&(*__self_1));268 let _ = ::core::fmt::DebugStruct::field(269 debug_trait_builder,270 "allowed",271 &&(*__self_2),272 );273 ::core::fmt::DebugStruct::finish(debug_trait_builder)274 }275 }276 }277 }278 impl<T: Config> ContractHelpersCall<T> {279 #[doc = "contractOwner(address)"]280 const CONTRACT_OWNER: u32 = 1364373836u32;281 #[doc = "sponsoringEnabled(address)"]282 const SPONSORING_ENABLED: u32 = 1613225057u32;283 #[doc = "toggleSponsoring(address,bool)"]284 const TOGGLE_SPONSORING: u32 = 4239158662u32;285 #[doc = "setSponsoringRateLimit(address,uint32)"]286 const SET_SPONSORING_RATE_LIMIT: u32 = 2008467720u32;287 #[doc = "getSponsoringRateLimit(address)"]288 const GET_SPONSORING_RATE_LIMIT: u32 = 1628240573u32;289 #[doc = "allowed(address,address)"]290 const ALLOWED: u32 = 1550156133u32;291 #[doc = "allowlistEnabled(address)"]292 const ALLOWLIST_ENABLED: u32 = 3346198380u32;293 #[doc = "toggleAllowlist(address,bool)"]294 const TOGGLE_ALLOWLIST: u32 = 920527093u32;295 #[doc = "toggleAllowed(address,address,bool)"]296 const TOGGLE_ALLOWED: u32 = 1191627804u32;297 pub const fn interface_id() -> u32 {298 let mut interface_id = 0;299 interface_id ^= Self::CONTRACT_OWNER;300 interface_id ^= Self::SPONSORING_ENABLED;301 interface_id ^= Self::TOGGLE_SPONSORING;302 interface_id ^= Self::SET_SPONSORING_RATE_LIMIT;303 interface_id ^= Self::GET_SPONSORING_RATE_LIMIT;304 interface_id ^= Self::ALLOWED;305 interface_id ^= Self::ALLOWLIST_ENABLED;306 interface_id ^= Self::TOGGLE_ALLOWLIST;307 interface_id ^= Self::TOGGLE_ALLOWED;308 interface_id309 }310 pub fn supports_interface(interface_id: u32) -> bool {311 interface_id != 0xffffff312 && (interface_id == ::evm_coder::ERC165Call::INTERFACE_ID313 || interface_id == Self::interface_id())314 }315 pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {316 use evm_coder::solidity::*;317 use core::fmt::Write;318 let interface = SolidityInterface {319 name: "ContractHelpers",320 selector: Self::interface_id(),321 is: &["Dummy", "ERC165"],322 functions: (323 SolidityFunction {324 docs: &[],325 selector: "contractOwner(address) 5152b14c",326 name: "contractOwner",327 mutability: SolidityMutability::View,328 args: (<NamedArgument<address>>::new("contractAddress"),),329 result: <UnnamedArgument<address>>::default(),330 },331 SolidityFunction {332 docs: &[],333 selector: "sponsoringEnabled(address) 6027dc61",334 name: "sponsoringEnabled",335 mutability: SolidityMutability::View,336 args: (<NamedArgument<address>>::new("contractAddress"),),337 result: <UnnamedArgument<bool>>::default(),338 },339 SolidityFunction {340 docs: &[],341 selector: "toggleSponsoring(address,bool) fcac6d86",342 name: "toggleSponsoring",343 mutability: SolidityMutability::Mutable,344 args: (345 <NamedArgument<address>>::new("contractAddress"),346 <NamedArgument<bool>>::new("enabled"),347 ),348 result: <UnnamedArgument<void>>::default(),349 },350 SolidityFunction {351 docs: &[],352 selector: "setSponsoringRateLimit(address,uint32) 77b6c908",353 name: "setSponsoringRateLimit",354 mutability: SolidityMutability::Mutable,355 args: (356 <NamedArgument<address>>::new("contractAddress"),357 <NamedArgument<uint32>>::new("rateLimit"),358 ),359 result: <UnnamedArgument<void>>::default(),360 },361 SolidityFunction {362 docs: &[],363 selector: "getSponsoringRateLimit(address) 610cfabd",364 name: "getSponsoringRateLimit",365 mutability: SolidityMutability::View,366 args: (<NamedArgument<address>>::new("contractAddress"),),367 result: <UnnamedArgument<uint32>>::default(),368 },369 SolidityFunction {370 docs: &[],371 selector: "allowed(address,address) 5c658165",372 name: "allowed",373 mutability: SolidityMutability::View,374 args: (375 <NamedArgument<address>>::new("contractAddress"),376 <NamedArgument<address>>::new("user"),377 ),378 result: <UnnamedArgument<bool>>::default(),379 },380 SolidityFunction {381 docs: &[],382 selector: "allowlistEnabled(address) c772ef6c",383 name: "allowlistEnabled",384 mutability: SolidityMutability::View,385 args: (<NamedArgument<address>>::new("contractAddress"),),386 result: <UnnamedArgument<bool>>::default(),387 },388 SolidityFunction {389 docs: &[],390 selector: "toggleAllowlist(address,bool) 36de20f5",391 name: "toggleAllowlist",392 mutability: SolidityMutability::Mutable,393 args: (394 <NamedArgument<address>>::new("contractAddress"),395 <NamedArgument<bool>>::new("enabled"),396 ),397 result: <UnnamedArgument<void>>::default(),398 },399 SolidityFunction {400 docs: &[],401 selector: "toggleAllowed(address,address,bool) 4706cc1c",402 name: "toggleAllowed",403 mutability: SolidityMutability::Mutable,404 args: (405 <NamedArgument<address>>::new("contractAddress"),406 <NamedArgument<address>>::new("user"),407 <NamedArgument<bool>>::new("allowed"),408 ),409 result: <UnnamedArgument<void>>::default(),410 },411 ),412 };413 if is_impl {414 tc . collect ("// 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 ()) ;415 } else {416 tc . collect ("// Common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n" . into ()) ;417 }418 let mut out = string::new();419 if "ContractHelpers".starts_with("Inline") {420 out.push_str("// Inline\n");421 }422 let _ = interface.format(is_impl, &mut out, tc);423 tc.collect(out);424 }425 }426 impl<T: Config> ::evm_coder::Call for ContractHelpersCall<T> {427 fn parse(428 method_id: u32,429 reader: &mut ::evm_coder::abi::AbiReader,430 ) -> ::evm_coder::execution::Result<Option<Self>> {431 use ::evm_coder::abi::AbiRead;432 match method_id {433 ::evm_coder::ERC165Call::INTERFACE_ID => {434 return Ok(435 ::evm_coder::ERC165Call::parse(method_id, reader)?.map(Self::ERC165Call)436 )437 }438 Self::CONTRACT_OWNER => {439 return Ok(Some(Self::ContractOwner {440 contract_address: reader.abi_read()?,441 }))442 }443 Self::SPONSORING_ENABLED => {444 return Ok(Some(Self::SponsoringEnabled {445 contract_address: reader.abi_read()?,446 }))447 }448 Self::TOGGLE_SPONSORING => {449 return Ok(Some(Self::ToggleSponsoring {450 contract_address: reader.abi_read()?,451 enabled: reader.abi_read()?,452 }))453 }454 Self::SET_SPONSORING_RATE_LIMIT => {455 return Ok(Some(Self::SetSponsoringRateLimit {456 contract_address: reader.abi_read()?,457 rate_limit: reader.abi_read()?,458 }))459 }460 Self::GET_SPONSORING_RATE_LIMIT => {461 return Ok(Some(Self::GetSponsoringRateLimit {462 contract_address: reader.abi_read()?,463 }))464 }465 Self::ALLOWED => {466 return Ok(Some(Self::Allowed {467 contract_address: reader.abi_read()?,468 user: reader.abi_read()?,469 }))470 }471 Self::ALLOWLIST_ENABLED => {472 return Ok(Some(Self::AllowlistEnabled {473 contract_address: reader.abi_read()?,474 }))475 }476 Self::TOGGLE_ALLOWLIST => {477 return Ok(Some(Self::ToggleAllowlist {478 contract_address: reader.abi_read()?,479 enabled: reader.abi_read()?,480 }))481 }482 Self::TOGGLE_ALLOWED => {483 return Ok(Some(Self::ToggleAllowed {484 contract_address: reader.abi_read()?,485 user: reader.abi_read()?,486 allowed: reader.abi_read()?,487 }))488 }489 _ => {}490 }491 return Ok(None);492 }493 }494 impl<T: Config> ::evm_coder::Weighted for ContractHelpersCall<T> {495 fn weight(&self) -> ::evm_coder::execution::DispatchInfo {496 type InternalCall = ContractHelpersCall;497 match self {498 InternalCall::ERC165Call(::evm_coder::ERC165Call::SupportsInterface { .. }) => {499 100u64.into()500 }501 InternalCall::ContractOwner { .. } => ().into(),502 InternalCall::SponsoringEnabled { .. } => ().into(),503 InternalCall::ToggleSponsoring { .. } => ().into(),504 InternalCall::SetSponsoringRateLimit { .. } => ().into(),505 InternalCall::GetSponsoringRateLimit { .. } => ().into(),506 InternalCall::Allowed { .. } => ().into(),507 InternalCall::AllowlistEnabled { .. } => ().into(),508 InternalCall::ToggleAllowlist { .. } => ().into(),509 InternalCall::ToggleAllowed { .. } => ().into(),510 }511 }512 }513 impl<T: Config> ::evm_coder::Callable<ContractHelpersCall<T>> for ContractHelpers<T> {514 #[allow(unreachable_code)]515 fn call(516 &mut self,517 c: Msg<ContractHelpersCall>,518 ) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {519 use ::evm_coder::abi::AbiWrite;520 type InternalCall = ContractHelpersCall;521 match c.call {522 InternalCall::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {523 interface_id,524 }) => {525 let mut writer = ::evm_coder::abi::AbiWriter::default();526 writer.bool(&InternalCall::supports_interface(interface_id));527 return Ok(writer.into());528 }529 _ => {}530 }531 let mut writer = ::evm_coder::abi::AbiWriter::default();532 match c.call {533 InternalCall::ContractOwner { contract_address } => {534 let result = self.contract_owner(contract_address)?;535 (&result).into_result()536 }537 InternalCall::SponsoringEnabled { contract_address } => {538 let result = self.sponsoring_enabled(contract_address)?;539 (&result).into_result()540 }541 InternalCall::ToggleSponsoring {542 contract_address,543 enabled,544 } => {545 let result =546 self.toggle_sponsoring(c.caller.clone(), contract_address, enabled)?;547 (&result).into_result()548 }549 InternalCall::SetSponsoringRateLimit {550 contract_address,551 rate_limit,552 } => {553 let result = self.set_sponsoring_rate_limit(554 c.caller.clone(),555 contract_address,556 rate_limit,557 )?;558 (&result).into_result()559 }560 InternalCall::GetSponsoringRateLimit { contract_address } => {561 let result = self.get_sponsoring_rate_limit(contract_address)?;562 (&result).into_result()563 }564 InternalCall::Allowed {565 contract_address,566 user,567 } => {568 let result = self.allowed(contract_address, user)?;569 (&result).into_result()570 }571 InternalCall::AllowlistEnabled { contract_address } => {572 let result = self.allowlist_enabled(contract_address)?;573 (&result).into_result()574 }575 InternalCall::ToggleAllowlist {576 contract_address,577 enabled,578 } => {579 let result =580 self.toggle_allowlist(c.caller.clone(), contract_address, enabled)?;581 (&result).into_result()582 }583 InternalCall::ToggleAllowed {584 contract_address,585 user,586 allowed,587 } => {588 let result =589 self.toggle_allowed(c.caller.clone(), contract_address, user, allowed)?;590 (&result).into_result()591 }592 _ => ::core::panicking::panic("internal error: entered unreachable code"),593 }594 }595 }596 pub struct HelpersOnMethodCall<T: Config>(PhantomData<*const T>);597 impl<T: Config> OnMethodCall<T> for HelpersOnMethodCall<T> {598 fn is_reserved(contract: &sp_core::H160) -> bool {599 contract == &T::ContractAddress::get()600 }601 fn is_used(contract: &sp_core::H160) -> bool {602 contract == &T::ContractAddress::get()603 }604 fn call(605 source: &sp_core::H160,606 target: &sp_core::H160,607 gas_left: u64,608 input: &[u8],609 value: sp_core::U256,610 ) -> Option<PrecompileOutput> {611 if !<Pallet<T>>::allowed(*target, *source, true) {612 return Some(PrecompileOutput {613 exit_status: ExitReason::Revert(ExitRevert::Reverted),614 cost: 0,615 output: {616 let mut writer = AbiWriter::new_call(147028384u32);617 writer.string("Target contract is allowlisted");618 writer.finish()619 },620 logs: ::alloc::vec::Vec::new(),621 });622 }623 if target != &T::ContractAddress::get() {624 return None;625 }626 let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(*target, gas_left));627 pallet_evm_coder_substrate::call(*source, helpers, value, input)628 }629 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {630 (contract == & T :: ContractAddress :: get ()) . then (| | b"`\xe0`@R`&`\x80\x81\x81R\x90a\x04\xf4`\xa09\x80Qa\x00&\x91`\x01\x91` \x90\x91\x01\x90a\x009V[P4\x80\x15a\x003W`\x00\x80\xfd[Pa\x01\rV[\x82\x80Ta\x00E\x90a\x00\xd2V[\x90`\x00R` `\x00 \x90`\x1f\x01` \x90\x04\x81\x01\x92\x82a\x00gW`\x00\x85Ua\x00\xadV[\x82`\x1f\x10a\x00\x80W\x80Q`\xff\x19\x16\x83\x80\x01\x17\x85Ua\x00\xadV[\x82\x80\x01`\x01\x01\x85U\x82\x15a\x00\xadW\x91\x82\x01[\x82\x81\x11\x15a\x00\xadW\x82Q\x82U\x91` \x01\x91\x90`\x01\x01\x90a\x00\x92V[Pa\x00\xb9\x92\x91Pa\x00\xbdV[P\x90V[[\x80\x82\x11\x15a\x00\xb9W`\x00\x81U`\x01\x01a\x00\xbeV[`\x01\x81\x81\x1c\x90\x82\x16\x80a\x00\xe6W`\x7f\x82\x16\x91P[` \x82\x10\x81\x14\x15a\x01\x07WcNH{q`\xe0\x1b`\x00R`\"`\x04R`$`\x00\xfd[P\x91\x90PV[a\x03\xd8\x80a\x01\x1c`\x009`\x00\xf3\xfe`\x80`@R4\x80\x15a\x00\x10W`\x00\x80\xfd[P`\x046\x10a\x00\x9eW`\x005`\xe0\x1c\x80c`\'\xdca\x11a\x00fW\x80c`\'\xdca\x14a\x01\"W\x80ca\x0c\xfa\xbd\x14a\x010W\x80cw\xb6\xc9\x08\x14a\x01SW\x80c\xc7r\xefl\x14a\x01\"W\x80c\xfc\xacm\x86\x14a\x00\xcbW`\x00\x80\xfd[\x80c\x01\xff\xc9\xa7\x14a\x00\xa3W\x80c6\xde \xf5\x14a\x00\xcbW\x80cG\x06\xcc\x1c\x14a\x00\xe0W\x80cQR\xb1L\x14a\x00\xeeW\x80c\\e\x81e\x14a\x01\x14W[`\x00\x80\xfd[a\x00\xb6a\x00\xb16`\x04a\x01\xa2V[a\x01aV[`@Q\x90\x15\x15\x81R` \x01[`@Q\x80\x91\x03\x90\xf3[a\x00\xdea\x00\xd96`\x04a\x01\xffV[a\x01\x87V[\x00[a\x00\xdea\x00\xd96`\x04a\x022V[a\x00\xfca\x00\xb16`\x04a\x02uV[`@Q`\x01`\x01`\xa0\x1b\x03\x90\x91\x16\x81R` \x01a\x00\xc2V[a\x00\xb6a\x00\xb16`\x04a\x02\x90V[a\x00\xb6a\x00\xb16`\x04a\x02uV[a\x01>a\x00\xb16`\x04a\x02uV[`@Qc\xff\xff\xff\xff\x90\x91\x16\x81R` \x01a\x00\xc2V[a\x00\xdea\x00\xd96`\x04a\x02\xbaV[`\x00`\x01`@QbF\x1b\xcd`\xe5\x1b\x81R`\x04\x01a\x01~\x91\x90a\x02\xfaV[`@Q\x80\x91\x03\x90\xfd[`\x01`@QbF\x1b\xcd`\xe5\x1b\x81R`\x04\x01a\x01~\x91\x90a\x02\xfaV[`\x00` \x82\x84\x03\x12\x15a\x01\xb4W`\x00\x80\xfd[\x815`\x01`\x01`\xe0\x1b\x03\x19\x81\x16\x81\x14a\x01\xccW`\x00\x80\xfd[\x93\x92PPPV[\x805`\x01`\x01`\xa0\x1b\x03\x81\x16\x81\x14a\x01\xeaW`\x00\x80\xfd[\x91\x90PV[\x805\x80\x15\x15\x81\x14a\x01\xeaW`\x00\x80\xfd[`\x00\x80`@\x83\x85\x03\x12\x15a\x02\x12W`\x00\x80\xfd[a\x02\x1b\x83a\x01\xd3V[\x91Pa\x02)` \x84\x01a\x01\xefV[\x90P\x92P\x92\x90PV[`\x00\x80`\x00``\x84\x86\x03\x12\x15a\x02GW`\x00\x80\xfd[a\x02P\x84a\x01\xd3V[\x92Pa\x02^` \x85\x01a\x01\xd3V[\x91Pa\x02l`@\x85\x01a\x01\xefV[\x90P\x92P\x92P\x92V[`\x00` \x82\x84\x03\x12\x15a\x02\x87W`\x00\x80\xfd[a\x01\xcc\x82a\x01\xd3V[`\x00\x80`@\x83\x85\x03\x12\x15a\x02\xa3W`\x00\x80\xfd[a\x02\xac\x83a\x01\xd3V[\x91Pa\x02)` \x84\x01a\x01\xd3V[`\x00\x80`@\x83\x85\x03\x12\x15a\x02\xcdW`\x00\x80\xfd[a\x02\xd6\x83a\x01\xd3V[\x91P` \x83\x015c\xff\xff\xff\xff\x81\x16\x81\x14a\x02\xefW`\x00\x80\xfd[\x80\x91PP\x92P\x92\x90PV[`\x00` \x80\x83R`\x00\x84T\x81`\x01\x82\x81\x1c\x91P\x80\x83\x16\x80a\x03\x1cW`\x7f\x83\x16\x92P[\x85\x83\x10\x81\x14\x15a\x03:WcNH{q`\xe0\x1b\x85R`\"`\x04R`$\x85\xfd[\x87\x86\x01\x83\x81R` \x01\x81\x80\x15a\x03WW`\x01\x81\x14a\x03hWa\x03\x93V[`\xff\x19\x86\x16\x82R\x87\x82\x01\x96Pa\x03\x93V[`\x00\x8b\x81R` \x90 `\x00[\x86\x81\x10\x15a\x03\x8dW\x81T\x84\x82\x01R\x90\x85\x01\x90\x89\x01a\x03tV[\x83\x01\x97PP[P\x94\x99\x98PPPPPPPPPV\xfe\xa2dipfsX\"\x12 \xde\xe1\xb0gnP\xa0\xbb\xa7\xaf\xbek+\xe6S6\n\xcd?\x0c+\x81\xebEq\x8c\xe3\xab\xaaC6UdsolcC\x00\x08\t\x003this contract is implemented in native" . to_vec ())631 }632 }633 pub struct HelpersOnCreate<T: Config>(PhantomData<*const T>);634 impl<T: Config> OnCreate<T> for HelpersOnCreate<T> {635 fn on_create(owner: H160, contract: H160) {636 <Owner<T>>::insert(contract, owner);637 }638 }639 pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);640 impl<T: Config> SponsorshipHandler<H160, (H160, Vec<u8>)> for HelpersContractSponsoring<T> {641 fn get_sponsor(who: &H160, call: &(H160, Vec<u8>)) -> Option<H160> {642 if <SelfSponsoring<T>>::get(&call.0) && <Pallet<T>>::allowed(call.0, *who, false) {643 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;644 if let Some(last_tx_block) = <SponsorBasket<T>>::get(&call.0, who) {645 let rate_limit = <SponsoringRateLimit<T>>::get(&call.0);646 let limit_time = last_tx_block + rate_limit;647 if block_number > limit_time {648 <SponsorBasket<T>>::insert(&call.0, who, block_number);649 return Some(call.0);650 }651 } else {652 <SponsorBasket<T>>::insert(&call.0, who, block_number);653 return Some(call.0);654 }655 }656 None657 }658 }659}660#[doc = r"661 The module that hosts all the662 [FRAME](https://docs.substrate.io/v3/runtime/frame)663 types needed to add this pallet to a664 runtime.665 "]666pub mod pallet {667 use evm_coder::execution::Result;668 use frame_support::pallet_prelude::*;669 use sp_core::H160;670 #[doc = r"671 Configuration trait of this pallet.672673 Implement this type for a runtime in order to customize this pallet.674 "]675 pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config {676 type ContractAddress: Get<H160>;677 type DefaultSponsoringRateLimit: Get<Self::BlockNumber>;678 }679 #[scale_info(skip_type_params(T), capture_docs = "always")]680 #[doc = r"681 Custom [dispatch errors](https://docs.substrate.io/v3/runtime/events-and-errors)682 of this pallet.683 "]684 pub enum Error<T> {685 #[doc(hidden)]686 #[codec(skip)]687 __Ignore(688 frame_support::sp_std::marker::PhantomData<(T)>,689 frame_support::Never,690 ),691 #[doc = " This method is only executable by owner"]692 NoPermission,693 }694 #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]695 const _: () = {696 impl<T> ::scale_info::TypeInfo for Error<T>697 where698 frame_support::sp_std::marker::PhantomData<(T)>: ::scale_info::TypeInfo + 'static,699 T: 'static,700 {701 type Identity = Self;702 fn type_info() -> ::scale_info::Type {703 :: scale_info :: Type :: builder () . path (:: scale_info :: Path :: new ("Error" , "pallet_evm_contract_helpers::pallet")) . type_params (< [_] > :: into_vec (box [:: scale_info :: TypeParameter :: new ("T" , :: core :: option :: Option :: None)])) . docs_always (& ["\n\t\t\tCustom [dispatch errors](https://docs.substrate.io/v3/runtime/events-and-errors)\n\t\t\tof this pallet.\n\t\t\t"]) . variant (:: scale_info :: build :: Variants :: new () . variant ("NoPermission" , | v | v . index (0usize as :: core :: primitive :: u8) . docs_always (& ["This method is only executable by owner"])))704 }705 };706 };707 #[doc = r"708 The [pallet](https://docs.substrate.io/v3/runtime/frame#pallets) implementing709 the on-chain logic.710 "]711 pub struct Pallet<T>(frame_support::sp_std::marker::PhantomData<(T)>);712 const _: () = {713 impl<T> core::clone::Clone for Pallet<T> {714 fn clone(&self) -> Self {715 Self(core::clone::Clone::clone(&self.0))716 }717 }718 };719 const _: () = {720 impl<T> core::cmp::Eq for Pallet<T> {}721 };722 const _: () = {723 impl<T> core::cmp::PartialEq for Pallet<T> {724 fn eq(&self, other: &Self) -> bool {725 true && self.0 == other.0726 }727 }728 };729 const _: () = {730 impl<T> core::fmt::Debug for Pallet<T> {731 fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {732 fmt.debug_tuple("Pallet").field(&self.0).finish()733 }734 }735 };736 #[allow(type_alias_bounds)]737 pub(super) type Owner<T: Config> = StorageMap<738 _GeneratedPrefixForStorageOwner<T>,739 Twox128,740 H160,741 H160,742 ValueQuery,743 frame_support::traits::GetDefault,744 frame_support::traits::GetDefault,745 >;746 #[allow(type_alias_bounds)]747 pub(super) type SelfSponsoring<T: Config> = StorageMap<748 _GeneratedPrefixForStorageSelfSponsoring<T>,749 Twox128,750 H160,751 bool,752 ValueQuery,753 frame_support::traits::GetDefault,754 frame_support::traits::GetDefault,755 >;756 #[allow(type_alias_bounds)]757 pub(super) type SponsoringRateLimit<T: Config> = StorageMap<758 _GeneratedPrefixForStorageSponsoringRateLimit<T>,759 Twox128,760 H160,761 T::BlockNumber,762 ValueQuery,763 T::DefaultSponsoringRateLimit,764 frame_support::traits::GetDefault,765 >;766 #[allow(type_alias_bounds)]767 pub(super) type SponsorBasket<T: Config> = StorageDoubleMap<768 _GeneratedPrefixForStorageSponsorBasket<T>,769 Twox128,770 H160,771 Twox128,772 H160,773 T::BlockNumber,774 OptionQuery,775 frame_support::traits::GetDefault,776 frame_support::traits::GetDefault,777 >;778 #[allow(type_alias_bounds)]779 pub(super) type AllowlistEnabled<T: Config> = StorageMap<780 _GeneratedPrefixForStorageAllowlistEnabled<T>,781 Twox128,782 H160,783 bool,784 ValueQuery,785 frame_support::traits::GetDefault,786 frame_support::traits::GetDefault,787 >;788 #[allow(type_alias_bounds)]789 pub(super) type Allowlist<T: Config> = StorageDoubleMap<790 _GeneratedPrefixForStorageAllowlist<T>,791 Twox128,792 H160,793 Twox128,794 H160,795 bool,796 ValueQuery,797 frame_support::traits::GetDefault,798 frame_support::traits::GetDefault,799 >;800 impl<T: Config> Pallet<T> {801 pub fn toggle_sponsoring(contract: H160, enabled: bool) {802 <SelfSponsoring<T>>::insert(contract, enabled);803 }804 pub fn set_sponsoring_rate_limit(contract: H160, rate_limit: T::BlockNumber) {805 <SponsoringRateLimit<T>>::insert(contract, rate_limit);806 }807 #[doc = " Default is returned if allowlist is disabled"]808 pub fn allowed(contract: H160, user: H160, default: bool) -> bool {809 if !<AllowlistEnabled<T>>::get(contract) {810 return default;811 }812 <Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user813 }814 pub fn toggle_allowlist(contract: H160, enabled: bool) {815 <AllowlistEnabled<T>>::insert(contract, enabled)816 }817 pub fn toggle_allowed(contract: H160, user: H160, allowed: bool) {818 <Allowlist<T>>::insert(contract, user, allowed);819 }820 pub fn ensure_owner(contract: H160, user: H160) -> Result<()> {821 {822 if !(<Owner<T>>::get(&contract) == user) {823 {824 return Err("no permission".into());825 };826 }827 };828 Ok(())829 }830 }831 impl<T: Config> Pallet<T> {832 #[doc(hidden)]833 pub fn pallet_constants_metadata(834 ) -> frame_support::sp_std::vec::Vec<frame_support::metadata::PalletConstantMetadata>835 {836 ::alloc::vec::Vec::new()837 }838 }839 impl<T: Config> Pallet<T> {840 pub fn error_metadata() -> Option<frame_support::metadata::PalletErrorMetadata> {841 Some(frame_support::metadata::PalletErrorMetadata {842 ty: frame_support::scale_info::meta_type::<Error<T>>(),843 })844 }845 }846 #[doc = r" Type alias to `Pallet`, to be used by `construct_runtime`."]847 #[doc = r""]848 #[doc = r" Generated by `pallet` attribute macro."]849 #[deprecated(note = "use `Pallet` instead")]850 #[allow(dead_code)]851 pub type Module<T> = Pallet<T>;852 impl<T: Config> frame_support::traits::GetStorageVersion for Pallet<T> {853 fn current_storage_version() -> frame_support::traits::StorageVersion {854 frame_support::traits::StorageVersion::default()855 }856 fn on_chain_storage_version() -> frame_support::traits::StorageVersion {857 frame_support::traits::StorageVersion::get::<Self>()858 }859 }860 impl<T: Config> frame_support::traits::OnGenesis for Pallet<T> {861 fn on_genesis() {862 let storage_version = frame_support::traits::StorageVersion::default();863 storage_version.put::<Self>();864 }865 }866 impl<T: Config> frame_support::traits::PalletInfoAccess for Pallet<T> {867 fn index() -> usize {868 <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::index::<869 Self,870 >()871 .expect(872 "Pallet is part of the runtime because pallet `Config` trait is \873 implemented by the runtime",874 )875 }876 fn name() -> &'static str {877 <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<878 Self,879 >()880 .expect(881 "Pallet is part of the runtime because pallet `Config` trait is \882 implemented by the runtime",883 )884 }885 fn module_name() -> &'static str {886 < < T as frame_system :: Config > :: PalletInfo as frame_support :: traits :: PalletInfo > :: module_name :: < Self > () . expect ("Pallet is part of the runtime because pallet `Config` trait is \887 implemented by the runtime")888 }889 fn crate_version() -> frame_support::traits::CrateVersion {890 frame_support::traits::CrateVersion {891 major: 0u16,892 minor: 1u8,893 patch: 0u8,894 }895 }896 }897 impl<T: Config> frame_support::traits::StorageInfoTrait for Pallet<T> {898 fn storage_info() -> frame_support::sp_std::vec::Vec<frame_support::traits::StorageInfo> {899 #[allow(unused_mut)]900 let mut res = ::alloc::vec::Vec::new();901 {902 let mut storage_info = < Owner < T > as frame_support :: traits :: PartialStorageInfoTrait > :: partial_storage_info () ;903 res.append(&mut storage_info);904 }905 {906 let mut storage_info = < SelfSponsoring < T > as frame_support :: traits :: PartialStorageInfoTrait > :: partial_storage_info () ;907 res.append(&mut storage_info);908 }909 {910 let mut storage_info = < SponsoringRateLimit < T > as frame_support :: traits :: PartialStorageInfoTrait > :: partial_storage_info () ;911 res.append(&mut storage_info);912 }913 {914 let mut storage_info = < SponsorBasket < T > as frame_support :: traits :: PartialStorageInfoTrait > :: partial_storage_info () ;915 res.append(&mut storage_info);916 }917 {918 let mut storage_info = < AllowlistEnabled < T > as frame_support :: traits :: PartialStorageInfoTrait > :: partial_storage_info () ;919 res.append(&mut storage_info);920 }921 {922 let mut storage_info = < Allowlist < T > as frame_support :: traits :: PartialStorageInfoTrait > :: partial_storage_info () ;923 res.append(&mut storage_info);924 }925 res926 }927 }928 #[doc(hidden)]929 pub mod __substrate_call_check {930 #[doc(hidden)]931 pub use __is_call_part_defined_0 as is_call_part_defined;932 }933 #[doc = r"Contains one variant per dispatchable that can be called by an extrinsic."]934 #[codec(encode_bound())]935 #[codec(decode_bound())]936 #[scale_info(skip_type_params(T), capture_docs = "always")]937 #[allow(non_camel_case_types)]938 pub enum Call<T: Config> {939 #[doc(hidden)]940 #[codec(skip)]941 __Ignore(942 frame_support::sp_std::marker::PhantomData<(T,)>,943 frame_support::Never,944 ),945 }946 const _: () = {947 impl<T: Config> core::fmt::Debug for Call<T> {948 fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {949 match *self {950 Self::__Ignore(ref _0, ref _1) => fmt951 .debug_tuple("Call::__Ignore")952 .field(&_0)953 .field(&_1)954 .finish(),955 }956 }957 }958 };959 const _: () = {960 impl<T: Config> core::clone::Clone for Call<T> {961 fn clone(&self) -> Self {962 match self {963 Self::__Ignore(ref _0, ref _1) => {964 Self::__Ignore(core::clone::Clone::clone(_0), core::clone::Clone::clone(_1))965 }966 }967 }968 }969 };970 const _: () = {971 impl<T: Config> core::cmp::Eq for Call<T> {}972 };973 const _: () = {974 impl<T: Config> core::cmp::PartialEq for Call<T> {975 fn eq(&self, other: &Self) -> bool {976 match (self, other) {977 (Self::__Ignore(_0, _1), Self::__Ignore(_0_other, _1_other)) => {978 true && _0 == _0_other && _1 == _1_other979 }980 }981 }982 }983 };984 const _: () = {985 #[allow(non_camel_case_types)]986 impl<T: Config> ::codec::Encode for Call<T> {}987 impl<T: Config> ::codec::EncodeLike for Call<T> {}988 };989 const _: () = {990 #[allow(non_camel_case_types)]991 impl<T: Config> ::codec::Decode for Call<T> {992 fn decode<__CodecInputEdqy: ::codec::Input>(993 __codec_input_edqy: &mut __CodecInputEdqy,994 ) -> ::core::result::Result<Self, ::codec::Error> {995 match __codec_input_edqy996 .read_byte()997 .map_err(|e| e.chain("Could not decode `Call`, failed to read variant byte"))?998 {999 _ => ::core::result::Result::Err(<_ as ::core::convert::Into<_>>::into(1000 "Could not decode `Call`, variant doesn\'t exist",1001 )),1002 }1003 }1004 }1005 };1006 #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]1007 const _: () = {1008 impl<T: Config> ::scale_info::TypeInfo for Call<T>1009 where1010 frame_support::sp_std::marker::PhantomData<(T,)>: ::scale_info::TypeInfo + 'static,1011 T: Config + 'static,1012 {1013 type Identity = Self;1014 fn type_info() -> ::scale_info::Type {1015 ::scale_info::Type::builder()1016 .path(::scale_info::Path::new(1017 "Call",1018 "pallet_evm_contract_helpers::pallet",1019 ))1020 .type_params(<[_]>::into_vec(box [::scale_info::TypeParameter::new(1021 "T",1022 ::core::option::Option::None,1023 )]))1024 .docs_always(&[1025 "Contains one variant per dispatchable that can be called by an extrinsic.",1026 ])1027 .variant(::scale_info::build::Variants::new())1028 }1029 };1030 };1031 impl<T: Config> Call<T> {}1032 impl<T: Config> frame_support::dispatch::GetDispatchInfo for Call<T> {1033 fn get_dispatch_info(&self) -> frame_support::dispatch::DispatchInfo {1034 match *self {1035 Self::__Ignore(_, _) => {1036 ::core::panicking::panic_fmt(::core::fmt::Arguments::new_v1(1037 &["internal error: entered unreachable code: "],1038 &match (&"__Ignore cannot be used",) {1039 (arg0,) => [::core::fmt::ArgumentV1::new(1040 arg0,1041 ::core::fmt::Display::fmt,1042 )],1043 },1044 ))1045 }1046 }1047 }1048 }1049 impl<T: Config> frame_support::dispatch::GetCallName for Call<T> {1050 fn get_call_name(&self) -> &'static str {1051 match *self {1052 Self::__Ignore(_, _) => {1053 ::core::panicking::panic_fmt(::core::fmt::Arguments::new_v1(1054 &["internal error: entered unreachable code: "],1055 &match (&"__PhantomItem cannot be used.",) {1056 (arg0,) => [::core::fmt::ArgumentV1::new(1057 arg0,1058 ::core::fmt::Display::fmt,1059 )],1060 },1061 ))1062 }1063 }1064 }1065 fn get_call_names() -> &'static [&'static str] {1066 &[]1067 }1068 }1069 impl<T: Config> frame_support::traits::UnfilteredDispatchable for Call<T> {1070 type Origin = frame_system::pallet_prelude::OriginFor<T>;1071 fn dispatch_bypass_filter(1072 self,1073 origin: Self::Origin,1074 ) -> frame_support::dispatch::DispatchResultWithPostInfo {1075 match self {1076 Self::__Ignore(_, _) => {1077 let _ = origin;1078 {1079 {1080 ::core::panicking::panic_fmt(::core::fmt::Arguments::new_v1(1081 &["internal error: entered unreachable code: "],1082 &match (&"__PhantomItem cannot be used.",) {1083 (arg0,) => [::core::fmt::ArgumentV1::new(1084 arg0,1085 ::core::fmt::Display::fmt,1086 )],1087 },1088 ))1089 }1090 };1091 }1092 }1093 }1094 }1095 impl<T: Config> frame_support::dispatch::Callable<T> for Pallet<T> {1096 type Call = Call<T>;1097 }1098 impl<T: Config> Pallet<T> {1099 #[doc(hidden)]1100 pub fn call_functions() -> frame_support::metadata::PalletCallMetadata {1101 frame_support::scale_info::meta_type::<Call<T>>().into()1102 }1103 }1104 impl<T: Config> frame_support::sp_std::fmt::Debug for Error<T> {1105 fn fmt(1106 &self,1107 f: &mut frame_support::sp_std::fmt::Formatter<'_>,1108 ) -> frame_support::sp_std::fmt::Result {1109 f.write_str(self.as_str())1110 }1111 }1112 impl<T: Config> Error<T> {1113 pub fn as_u8(&self) -> u8 {1114 match &self {1115 Self::__Ignore(_, _) => {1116 ::core::panicking::panic_fmt(::core::fmt::Arguments::new_v1(1117 &["internal error: entered unreachable code: "],1118 &match (&"`__Ignore` can never be constructed",) {1119 (arg0,) => [::core::fmt::ArgumentV1::new(1120 arg0,1121 ::core::fmt::Display::fmt,1122 )],1123 },1124 ))1125 }1126 Self::NoPermission => 0usize as u8,1127 }1128 }1129 pub fn as_str(&self) -> &'static str {1130 match &self {1131 Self::__Ignore(_, _) => {1132 ::core::panicking::panic_fmt(::core::fmt::Arguments::new_v1(1133 &["internal error: entered unreachable code: "],1134 &match (&"`__Ignore` can never be constructed",) {1135 (arg0,) => [::core::fmt::ArgumentV1::new(1136 arg0,1137 ::core::fmt::Display::fmt,1138 )],1139 },1140 ))1141 }1142 Self::NoPermission => "NoPermission",1143 }1144 }1145 }1146 impl<T: Config> From<Error<T>> for &'static str {1147 fn from(err: Error<T>) -> &'static str {1148 err.as_str()1149 }1150 }1151 impl<T: Config> From<Error<T>> for frame_support::sp_runtime::DispatchError {1152 fn from(err: Error<T>) -> Self {1153 let index = < < T as frame_system :: Config > :: PalletInfo as frame_support :: traits :: PalletInfo > :: index :: < Pallet < T > > () . expect ("Every active module has an index in the runtime; qed") as u8 ;1154 frame_support::sp_runtime::DispatchError::Module {1155 index,1156 error: err.as_u8(),1157 message: Some(err.as_str()),1158 }1159 }1160 }1161 #[doc(hidden)]1162 pub mod __substrate_event_check {1163 #[doc(hidden)]1164 pub use __is_event_part_defined_1 as is_event_part_defined;1165 }1166 impl<T: Config> Pallet<T> {1167 #[doc(hidden)]1168 pub fn storage_metadata() -> frame_support::metadata::PalletStorageMetadata {1169 frame_support :: metadata :: PalletStorageMetadata { prefix : < < T as frame_system :: Config > :: PalletInfo as frame_support :: traits :: PalletInfo > :: name :: < Pallet < T > > () . expect ("Every active pallet has a name in the runtime; qed") , entries : { # [allow (unused_mut)] let mut entries = :: alloc :: vec :: Vec :: new () ; { < Owner < T > as frame_support :: storage :: StorageEntryMetadataBuilder > :: build_metadata (:: alloc :: vec :: Vec :: new () , & mut entries) ; } { < SelfSponsoring < T > as frame_support :: storage :: StorageEntryMetadataBuilder > :: build_metadata (:: alloc :: vec :: Vec :: new () , & mut entries) ; } { < SponsoringRateLimit < T > as frame_support :: storage :: StorageEntryMetadataBuilder > :: build_metadata (:: alloc :: vec :: Vec :: new () , & mut entries) ; } { < SponsorBasket < T > as frame_support :: storage :: StorageEntryMetadataBuilder > :: build_metadata (:: alloc :: vec :: Vec :: new () , & mut entries) ; } { < AllowlistEnabled < T > as frame_support :: storage :: StorageEntryMetadataBuilder > :: build_metadata (:: alloc :: vec :: Vec :: new () , & mut entries) ; } { < Allowlist < T > as frame_support :: storage :: StorageEntryMetadataBuilder > :: build_metadata (:: alloc :: vec :: Vec :: new () , & mut entries) ; } entries } , }1170 }1171 }1172 pub(super) struct _GeneratedPrefixForStorageOwner<T>(core::marker::PhantomData<(T,)>);1173 impl<T: Config> frame_support::traits::StorageInstance for _GeneratedPrefixForStorageOwner<T> {1174 fn pallet_prefix() -> &'static str {1175 <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<1176 Pallet<T>,1177 >()1178 .expect("Every active pallet has a name in the runtime; qed")1179 }1180 const STORAGE_PREFIX: &'static str = "Owner";1181 }1182 pub(super) struct _GeneratedPrefixForStorageSelfSponsoring<T>(core::marker::PhantomData<(T,)>);1183 impl<T: Config> frame_support::traits::StorageInstance1184 for _GeneratedPrefixForStorageSelfSponsoring<T>1185 {1186 fn pallet_prefix() -> &'static str {1187 <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<1188 Pallet<T>,1189 >()1190 .expect("Every active pallet has a name in the runtime; qed")1191 }1192 const STORAGE_PREFIX: &'static str = "SelfSponsoring";1193 }1194 pub(super) struct _GeneratedPrefixForStorageSponsoringRateLimit<T>(1195 core::marker::PhantomData<(T,)>,1196 );1197 impl<T: Config> frame_support::traits::StorageInstance1198 for _GeneratedPrefixForStorageSponsoringRateLimit<T>1199 {1200 fn pallet_prefix() -> &'static str {1201 <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<1202 Pallet<T>,1203 >()1204 .expect("Every active pallet has a name in the runtime; qed")1205 }1206 const STORAGE_PREFIX: &'static str = "SponsoringRateLimit";1207 }1208 pub(super) struct _GeneratedPrefixForStorageSponsorBasket<T>(core::marker::PhantomData<(T,)>);1209 impl<T: Config> frame_support::traits::StorageInstance1210 for _GeneratedPrefixForStorageSponsorBasket<T>1211 {1212 fn pallet_prefix() -> &'static str {1213 <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<1214 Pallet<T>,1215 >()1216 .expect("Every active pallet has a name in the runtime; qed")1217 }1218 const STORAGE_PREFIX: &'static str = "SponsorBasket";1219 }1220 pub(super) struct _GeneratedPrefixForStorageAllowlistEnabled<T>(1221 core::marker::PhantomData<(T,)>,1222 );1223 impl<T: Config> frame_support::traits::StorageInstance1224 for _GeneratedPrefixForStorageAllowlistEnabled<T>1225 {1226 fn pallet_prefix() -> &'static str {1227 <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<1228 Pallet<T>,1229 >()1230 .expect("Every active pallet has a name in the runtime; qed")1231 }1232 const STORAGE_PREFIX: &'static str = "AllowlistEnabled";1233 }1234 pub(super) struct _GeneratedPrefixForStorageAllowlist<T>(core::marker::PhantomData<(T,)>);1235 impl<T: Config> frame_support::traits::StorageInstance for _GeneratedPrefixForStorageAllowlist<T> {1236 fn pallet_prefix() -> &'static str {1237 <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<1238 Pallet<T>,1239 >()1240 .expect("Every active pallet has a name in the runtime; qed")1241 }1242 const STORAGE_PREFIX: &'static str = "Allowlist";1243 }1244 #[doc(hidden)]1245 pub mod __substrate_inherent_check {1246 #[doc(hidden)]1247 pub use __is_inherent_part_defined_2 as is_inherent_part_defined;1248 }1249 #[doc = r" Hidden instance generated to be internally used when module is used without"]1250 #[doc = r" instance."]1251 #[doc(hidden)]1252 pub type __InherentHiddenInstance = ();1253 pub(super) trait Store {1254 type Owner;1255 type SelfSponsoring;1256 type SponsoringRateLimit;1257 type SponsorBasket;1258 type AllowlistEnabled;1259 type Allowlist;1260 }1261 impl<T: Config> Store for Pallet<T> {1262 type Owner = Owner<T>;1263 type SelfSponsoring = SelfSponsoring<T>;1264 type SponsoringRateLimit = SponsoringRateLimit<T>;1265 type SponsorBasket = SponsorBasket<T>;1266 type AllowlistEnabled = AllowlistEnabled<T>;1267 type Allowlist = Allowlist<T>;1268 }1269 impl<T: Config> frame_support::traits::Hooks<<T as frame_system::Config>::BlockNumber>1270 for Pallet<T>1271 {1272 }1273 impl<T: Config> frame_support::traits::OnFinalize<<T as frame_system::Config>::BlockNumber>1274 for Pallet<T>1275 {1276 fn on_finalize(n: <T as frame_system::Config>::BlockNumber) {1277 let __within_span__ = {1278 use ::tracing::__macro_support::Callsite as _;1279 static CALLSITE: ::tracing::__macro_support::MacroCallsite = {1280 use ::tracing::__macro_support::MacroCallsite;1281 static META: ::tracing::Metadata<'static> = {1282 ::tracing_core::metadata::Metadata::new(1283 "on_finalize",1284 "pallet_evm_contract_helpers::pallet",1285 ::tracing::Level::TRACE,1286 Some("pallets/evm-contract-helpers/src/lib.rs"),1287 Some(7u32),1288 Some("pallet_evm_contract_helpers::pallet"),1289 ::tracing_core::field::FieldSet::new(1290 &[],1291 ::tracing_core::callsite::Identifier(&CALLSITE),1292 ),1293 ::tracing::metadata::Kind::SPAN,1294 )1295 };1296 MacroCallsite::new(&META)1297 };1298 let mut interest = ::tracing::subscriber::Interest::never();1299 if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL1300 && ::tracing::Level::TRACE <= ::tracing::level_filters::LevelFilter::current()1301 && {1302 interest = CALLSITE.interest();1303 !interest.is_never()1304 }1305 && CALLSITE.is_enabled(interest)1306 {1307 let meta = CALLSITE.metadata();1308 ::tracing::Span::new(meta, &{ meta.fields().value_set(&[]) })1309 } else {1310 let span = CALLSITE.disabled_span();1311 {};1312 span1313 }1314 };1315 let __tracing_guard__ = __within_span__.enter();1316 < Self as frame_support :: traits :: Hooks < < T as frame_system :: Config > :: BlockNumber > > :: on_finalize (n)1317 }1318 }1319 impl<T: Config> frame_support::traits::OnIdle<<T as frame_system::Config>::BlockNumber>1320 for Pallet<T>1321 {1322 fn on_idle(1323 n: <T as frame_system::Config>::BlockNumber,1324 remaining_weight: frame_support::weights::Weight,1325 ) -> frame_support::weights::Weight {1326 < Self as frame_support :: traits :: Hooks < < T as frame_system :: Config > :: BlockNumber > > :: on_idle (n , remaining_weight)1327 }1328 }1329 impl<T: Config> frame_support::traits::OnInitialize<<T as frame_system::Config>::BlockNumber>1330 for Pallet<T>1331 {1332 fn on_initialize(1333 n: <T as frame_system::Config>::BlockNumber,1334 ) -> frame_support::weights::Weight {1335 let __within_span__ = {1336 use ::tracing::__macro_support::Callsite as _;1337 static CALLSITE: ::tracing::__macro_support::MacroCallsite = {1338 use ::tracing::__macro_support::MacroCallsite;1339 static META: ::tracing::Metadata<'static> = {1340 ::tracing_core::metadata::Metadata::new(1341 "on_initialize",1342 "pallet_evm_contract_helpers::pallet",1343 ::tracing::Level::TRACE,1344 Some("pallets/evm-contract-helpers/src/lib.rs"),1345 Some(7u32),1346 Some("pallet_evm_contract_helpers::pallet"),1347 ::tracing_core::field::FieldSet::new(1348 &[],1349 ::tracing_core::callsite::Identifier(&CALLSITE),1350 ),1351 ::tracing::metadata::Kind::SPAN,1352 )1353 };1354 MacroCallsite::new(&META)1355 };1356 let mut interest = ::tracing::subscriber::Interest::never();1357 if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL1358 && ::tracing::Level::TRACE <= ::tracing::level_filters::LevelFilter::current()1359 && {1360 interest = CALLSITE.interest();1361 !interest.is_never()1362 }1363 && CALLSITE.is_enabled(interest)1364 {1365 let meta = CALLSITE.metadata();1366 ::tracing::Span::new(meta, &{ meta.fields().value_set(&[]) })1367 } else {1368 let span = CALLSITE.disabled_span();1369 {};1370 span1371 }1372 };1373 let __tracing_guard__ = __within_span__.enter();1374 < Self as frame_support :: traits :: Hooks < < T as frame_system :: Config > :: BlockNumber > > :: on_initialize (n)1375 }1376 }1377 impl<T: Config> frame_support::traits::OnRuntimeUpgrade for Pallet<T> {1378 fn on_runtime_upgrade() -> frame_support::weights::Weight {1379 let __within_span__ = {1380 use ::tracing::__macro_support::Callsite as _;1381 static CALLSITE: ::tracing::__macro_support::MacroCallsite = {1382 use ::tracing::__macro_support::MacroCallsite;1383 static META: ::tracing::Metadata<'static> = {1384 ::tracing_core::metadata::Metadata::new(1385 "on_runtime_update",1386 "pallet_evm_contract_helpers::pallet",1387 ::tracing::Level::TRACE,1388 Some("pallets/evm-contract-helpers/src/lib.rs"),1389 Some(7u32),1390 Some("pallet_evm_contract_helpers::pallet"),1391 ::tracing_core::field::FieldSet::new(1392 &[],1393 ::tracing_core::callsite::Identifier(&CALLSITE),1394 ),1395 ::tracing::metadata::Kind::SPAN,1396 )1397 };1398 MacroCallsite::new(&META)1399 };1400 let mut interest = ::tracing::subscriber::Interest::never();1401 if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL1402 && ::tracing::Level::TRACE <= ::tracing::level_filters::LevelFilter::current()1403 && {1404 interest = CALLSITE.interest();1405 !interest.is_never()1406 }1407 && CALLSITE.is_enabled(interest)1408 {1409 let meta = CALLSITE.metadata();1410 ::tracing::Span::new(meta, &{ meta.fields().value_set(&[]) })1411 } else {1412 let span = CALLSITE.disabled_span();1413 {};1414 span1415 }1416 };1417 let __tracing_guard__ = __within_span__.enter();1418 let pallet_name = < < T as frame_system :: Config > :: PalletInfo as frame_support :: traits :: PalletInfo > :: name :: < Self > () . unwrap_or ("<unknown pallet name>") ;1419 {1420 let lvl = ::log::Level::Info;1421 if lvl <= ::log::STATIC_MAX_LEVEL && lvl <= ::log::max_level() {1422 ::log::__private_api_log(1423 ::core::fmt::Arguments::new_v1(1424 &["\u{2705} no migration for "],1425 &match (&pallet_name,) {1426 (arg0,) => [::core::fmt::ArgumentV1::new(1427 arg0,1428 ::core::fmt::Display::fmt,1429 )],1430 },1431 ),1432 lvl,1433 &(1434 frame_support::LOG_TARGET,1435 "pallet_evm_contract_helpers::pallet",1436 "pallets/evm-contract-helpers/src/lib.rs",1437 7u32,1438 ),1439 );1440 }1441 };1442 < Self as frame_support :: traits :: Hooks < < T as frame_system :: Config > :: BlockNumber > > :: on_runtime_upgrade ()1443 }1444 }1445 impl<T: Config> frame_support::traits::OffchainWorker<<T as frame_system::Config>::BlockNumber>1446 for Pallet<T>1447 {1448 fn offchain_worker(n: <T as frame_system::Config>::BlockNumber) {1449 < Self as frame_support :: traits :: Hooks < < T as frame_system :: Config > :: BlockNumber > > :: offchain_worker (n)1450 }1451 }1452 impl<T: Config> frame_support::traits::IntegrityTest for Pallet<T> {1453 fn integrity_test() {1454 < Self as frame_support :: traits :: Hooks < < T as frame_system :: Config > :: BlockNumber > > :: integrity_test ()1455 }1456 }1457 #[doc(hidden)]1458 pub mod __substrate_genesis_config_check {1459 #[doc(hidden)]1460 pub use __is_genesis_config_defined_3 as is_genesis_config_defined;1461 #[doc(hidden)]1462 pub use __is_std_enabled_for_genesis_3 as is_std_enabled_for_genesis;1463 }1464 #[doc(hidden)]1465 pub mod __substrate_origin_check {1466 #[doc(hidden)]1467 pub use __is_origin_part_defined_4 as is_origin_part_defined;1468 }1469 #[doc(hidden)]1470 pub mod __substrate_validate_unsigned_check {1471 #[doc(hidden)]1472 pub use __is_validate_unsigned_part_defined_5 as is_validate_unsigned_part_defined;1473 }1474}pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -1,6 +1,6 @@
use core::marker::PhantomData;
use evm_coder::{abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*};
-use pallet_evm_coder_substrate::SubstrateRecorder;
+use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use pallet_evm::{ExitReason, ExitRevert, OnCreate, OnMethodCall, PrecompileOutput};
use sp_core::H160;
use crate::{
@@ -11,16 +11,23 @@
use sp_std::{convert::TryInto, vec::Vec};
struct ContractHelpers<T: Config>(SubstrateRecorder<T>);
+impl<T: Config> WithRecorder<T> for ContractHelpers<T> {
+ fn recorder(&self) -> &SubstrateRecorder<T> {
+ &self.0
+ }
+ fn into_recorder(self) -> SubstrateRecorder<T> {
+ self.0
+ }
+}
+
#[solidity_interface(name = "ContractHelpers")]
impl<T: Config> ContractHelpers<T> {
fn contract_owner(&self, contract_address: address) -> Result<address> {
- self.0.consume_sload()?;
Ok(<Owner<T>>::get(contract_address))
}
fn sponsoring_enabled(&self, contract_address: address) -> Result<bool> {
- self.0.consume_sload()?;
Ok(<SelfSponsoring<T>>::get(contract_address))
}
@@ -30,9 +37,7 @@
contract_address: address,
enabled: bool,
) -> Result<void> {
- self.0.consume_sload()?;
<Pallet<T>>::ensure_owner(contract_address, caller)?;
- self.0.consume_sstore()?;
<Pallet<T>>::toggle_sponsoring(contract_address, enabled);
Ok(())
}
@@ -43,27 +48,22 @@
contract_address: address,
rate_limit: uint32,
) -> Result<void> {
- self.0.consume_sload()?;
<Pallet<T>>::ensure_owner(contract_address, caller)?;
- self.0.consume_sstore()?;
<Pallet<T>>::set_sponsoring_rate_limit(contract_address, rate_limit.into());
Ok(())
}
fn get_sponsoring_rate_limit(&self, contract_address: address) -> Result<uint32> {
- self.0.consume_sload()?;
Ok(<SponsoringRateLimit<T>>::get(contract_address)
.try_into()
.map_err(|_| "rate limit > u32::MAX")?)
}
fn allowed(&self, contract_address: address, user: address) -> Result<bool> {
- self.0.consume_sload()?;
Ok(<Pallet<T>>::allowed(contract_address, user, true))
}
fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {
- self.0.consume_sload()?;
Ok(<AllowlistEnabled<T>>::get(contract_address))
}
@@ -73,9 +73,7 @@
contract_address: address,
enabled: bool,
) -> Result<void> {
- self.0.consume_sload()?;
<Pallet<T>>::ensure_owner(contract_address, caller)?;
- self.0.consume_sstore()?;
<Pallet<T>>::toggle_allowlist(contract_address, enabled);
Ok(())
}
@@ -87,9 +85,7 @@
user: address,
allowed: bool,
) -> Result<void> {
- self.0.consume_sload()?;
<Pallet<T>>::ensure_owner(contract_address, caller)?;
- self.0.consume_sstore()?;
<Pallet<T>>::toggle_allowed(contract_address, user, allowed);
Ok(())
}
@@ -130,9 +126,8 @@
return None;
}
- let mut helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(*target, gas_left));
- let result = pallet_evm_coder_substrate::call_internal(*source, &mut helpers, value, input);
- helpers.0.evm_to_precompile_output(result)
+ let helpers = ContractHelpers::<T>(SubstrateRecorder::<T>::new(*target, gas_left));
+ pallet_evm_coder_substrate::call(*source, helpers, value, input)
}
fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {
@@ -170,5 +165,5 @@
}
}
-generate_stubgen!(contract_helpers_impl, ContractHelpersCall, true);
-generate_stubgen!(contract_helpers_iface, ContractHelpersCall, false);
+generate_stubgen!(contract_helpers_impl, ContractHelpersCall<()>, true);
+generate_stubgen!(contract_helpers_iface, ContractHelpersCall<()>, false);
pallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -21,6 +21,7 @@
}
}
+// Selector: 31acb1fe
contract ContractHelpers is Dummy, ERC165 {
// Selector: contractOwner(address) 5152b14c
function contractOwner(address contractAddress)
pallets/evm-migration/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-migration/Cargo.toml
+++ b/pallets/evm-migration/Cargo.toml
@@ -4,7 +4,9 @@
edition = "2018"
[dependencies]
-scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
@@ -12,8 +14,8 @@
sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
[dependencies.codec]
default-features = false
pallets/evm-transaction-payment/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-transaction-payment/Cargo.toml
+++ b/pallets/evm-transaction-payment/Cargo.toml
@@ -4,16 +4,18 @@
edition = "2018"
[dependencies]
-scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
up-sponsorship = { default-features = false, path = '../../primitives/sponsorship' }
[dependencies.codec]
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -1,15 +1,18 @@
use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
use core::convert::TryInto;
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
use nft_data_structs::CollectionMode;
use pallet_common::erc::CommonEvmHandler;
use sp_core::{H160, U256};
use sp_std::vec::Vec;
use pallet_common::account::CrossAccountId;
use pallet_common::erc::PrecompileOutput;
-use pallet_evm_coder_substrate::{call_internal, dispatch_to_evm};
+use pallet_evm_coder_substrate::{call, dispatch_to_evm};
-use crate::{Allowance, Balance, Config, FungibleHandle, Pallet, TotalSupply};
+use crate::{
+ Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,
+ weights::WeightInfo,
+};
#[derive(ToLog)]
pub enum ERC20Events {
@@ -40,6 +43,7 @@
Ok(string::from_utf8_lossy(&self.token_prefix).into())
}
fn total_supply(&self) -> Result<uint256> {
+ self.consume_store_reads(1)?;
Ok(<TotalSupply<T>>::get(self.id).into())
}
@@ -51,10 +55,12 @@
})
}
fn balance_of(&self, owner: address) -> Result<uint256> {
+ self.consume_store_reads(1)?;
let owner = T::CrossAccountId::from_eth(owner);
let balance = <Balance<T>>::get((self.id, owner));
Ok(balance.into())
}
+ #[weight(<SelfWeightOf<T>>::transfer())]
fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
@@ -63,6 +69,7 @@
<Pallet<T>>::transfer(self, &caller, &to, amount).map_err(|_| "transfer error")?;
Ok(true)
}
+ #[weight(<SelfWeightOf<T>>::transfer_from())]
fn transfer_from(
&mut self,
caller: caller,
@@ -79,6 +86,7 @@
.map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
+ #[weight(<SelfWeightOf<T>>::approve())]
fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let spender = T::CrossAccountId::from_eth(spender);
@@ -89,6 +97,7 @@
Ok(true)
}
fn allowance(&self, owner: address, spender: address) -> Result<uint256> {
+ self.consume_store_reads(1)?;
let owner = T::CrossAccountId::from_eth(owner);
let spender = T::CrossAccountId::from_eth(spender);
@@ -98,6 +107,7 @@
#[solidity_interface(name = "ERC20UniqueExtensions")]
impl<T: Config> FungibleHandle<T> {
+ #[weight(<SelfWeightOf<T>>::burn_from())]
fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let from = T::CrossAccountId::from_eth(from);
@@ -111,14 +121,13 @@
#[solidity_interface(name = "UniqueFungible", is(ERC20))]
impl<T: Config> FungibleHandle<T> {}
-generate_stubgen!(gen_impl, UniqueFungibleCall, true);
-generate_stubgen!(gen_iface, UniqueFungibleCall, false);
+generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);
+generate_stubgen!(gen_iface, UniqueFungibleCall<()>, false);
impl<T: Config> CommonEvmHandler for FungibleHandle<T> {
const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");
- fn call(mut self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileOutput> {
- let result = call_internal::<UniqueFungibleCall, _>(*source, &mut self, value, input);
- self.0.recorder.evm_to_precompile_output(result)
+ fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileOutput> {
+ call::<T, UniqueFungibleCall<T>, _>(*source, self, value, input)
}
}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -6,6 +6,7 @@
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
};
+use pallet_evm_coder_substrate::WithRecorder;
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
@@ -82,6 +83,14 @@
self.0
}
}
+impl<T: Config> WithRecorder<T> for FungibleHandle<T> {
+ fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
+ self.0.recorder()
+ }
+ fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {
+ self.0.into_recorder()
+ }
+}
impl<T: Config> Deref for FungibleHandle<T> {
type Target = pallet_common::CollectionHandle<T>;
@@ -136,7 +145,7 @@
}
<TotalSupply<T>>::insert(collection.id, total_supply);
- collection.log_infallible(ERC20Events::Transfer {
+ collection.log(ERC20Events::Transfer {
from: *owner.as_eth(),
to: H160::default(),
value: amount.into(),
@@ -179,11 +188,6 @@
} else {
None
};
-
- collection.consume_sstore()?;
- collection.consume_sstore()?;
- collection.consume_log(2, 32)?;
- collection.consume_sstore()?;
// =========
@@ -197,7 +201,7 @@
<Balance<T>>::insert((collection.id, to), balance_to);
}
- collection.log_infallible(ERC20Events::Transfer {
+ collection.log(ERC20Events::Transfer {
from: *from.as_eth(),
to: *to.as_eth(),
value: amount.into(),
@@ -217,8 +221,7 @@
sender: &T::CrossAccountId,
data: Vec<CreateItemData<T>>,
) -> DispatchResult {
- let unrestricted_minting = collection.is_owner_or_admin(sender)?;
- if !unrestricted_minting {
+ if !collection.is_owner_or_admin(sender) {
ensure!(
collection.mint_mode,
<CommonError<T>>::PublicMintingNotAllowed
@@ -241,20 +244,12 @@
.ok_or(ArithmeticError::Overflow)?;
for (user, amount) in data.into_iter() {
- collection.consume_sload()?;
let balance = balances
.entry(user.clone())
.or_insert_with(|| <Balance<T>>::get((collection.id, user)));
*balance = (*balance)
.checked_add(amount)
.ok_or(ArithmeticError::Overflow)?;
- }
-
- collection.consume_sstore()?;
- for _ in &balances {
- collection.consume_sstore()?;
- collection.consume_log(2, 32)?;
- collection.consume_sstore()?;
}
// =========
@@ -263,7 +258,7 @@
for (user, amount) in balances {
<Balance<T>>::insert((collection.id, &user), amount);
- collection.log_infallible(ERC20Events::Transfer {
+ collection.log(ERC20Events::Transfer {
from: H160::default(),
to: *user.as_eth(),
value: amount.into(),
@@ -287,7 +282,7 @@
) {
<Allowance<T>>::insert((collection.id, owner, spender), amount);
- collection.log_infallible(ERC20Events::Approval {
+ collection.log(ERC20Events::Approval {
owner: *owner.as_eth(),
spender: *spender.as_eth(),
value: amount.into(),
@@ -314,7 +309,7 @@
if <Balance<T>>::get((collection.id, owner)) < amount {
ensure!(
- collection.ignores_owned_amount(owner)?,
+ collection.ignores_owned_amount(owner),
<CommonError<T>>::CantApproveMoreThanOwned
);
}
@@ -343,7 +338,7 @@
let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
- collection.ignores_allowance(spender)?,
+ collection.ignores_allowance(spender),
<CommonError<T>>::TokenValueNotEnough
);
}
@@ -374,7 +369,7 @@
let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
- collection.ignores_allowance(spender)?,
+ collection.ignores_allowance(spender),
<CommonError<T>>::TokenValueNotEnough
);
}
pallets/nft/Cargo.tomldiffbeforeafterboth--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -146,9 +146,9 @@
"serde_no_std",
] }
-pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
hex-literal = "0.3.3"
pallet-common = { default-features = false, path = "../common" }
pallets/nft/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nft/src/benchmarking.rs
+++ b/pallets/nft/src/benchmarking.rs
@@ -155,12 +155,13 @@
let cl = CollectionLimits {
account_token_ownership_limit: Some(0),
- sponsored_data_size: 0,
- token_limit: 1,
- sponsor_transfer_timeout: 0,
- owner_can_destroy: true,
- owner_can_transfer: true,
+ sponsored_data_size: Some(0),
+ token_limit: Some(1),
+ sponsor_transfer_timeout: Some(0),
+ owner_can_destroy: Some(true),
+ owner_can_transfer: Some(true),
sponsored_data_rate_limit: None,
+ transfers_enabled: Some(true),
};
}: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)
pallets/nft/src/dispatch.rsdiffbeforeafterboth--- a/pallets/nft/src/dispatch.rs
+++ b/pallets/nft/src/dispatch.rs
@@ -83,10 +83,6 @@
_ => {}
}
- // TODO: Make submit_logs infallible, but it shouldn't fail here anyway
- dispatched
- .into_inner()
- .submit_logs()
- .expect("should succeed");
+ dispatched.into_inner().submit_logs();
result
}
pallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -31,7 +31,7 @@
let (method_id, mut reader) = AbiReader::new_call(call).map_err(|_| AnyError)?;
match &collection.mode {
crate::CollectionMode::NFT => {
- let call: UniqueNFTCall = UniqueNFTCall::parse(method_id, &mut reader)
+ let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader)
.map_err(|_| AnyError)?
.ok_or(AnyError)?;
match call {
@@ -63,7 +63,7 @@
}
}
crate::CollectionMode::Fungible(_) => {
- let call: UniqueFungibleCall = UniqueFungibleCall::parse(method_id, &mut reader)
+ let call = <UniqueFungibleCall<T>>::parse(method_id, &mut reader)
.map_err(|_| AnyError)?
.ok_or(AnyError)?;
#[allow(clippy::single_match)]
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -2,18 +2,19 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use frame_support::BoundedVec;
use nft_data_structs::TokenId;
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
use sp_std::{vec::Vec, vec};
use pallet_common::{account::CrossAccountId, erc::CommonEvmHandler};
-use pallet_evm_coder_substrate::call_internal;
+use pallet_evm_coder_substrate::call;
use pallet_common::erc::PrecompileOutput;
use crate::{
AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
+ SelfWeightOf, weights::WeightInfo,
};
#[derive(ToLog)]
@@ -64,6 +65,7 @@
/// Returns token's const_metadata
#[solidity(rename_selector = "tokenURI")]
fn token_uri(&self, token_id: uint256) -> Result<string> {
+ self.consume_store_reads(1)?;
let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
Ok(string::from_utf8_lossy(
&<TokenData<T>>::get((self.id, token_id))
@@ -87,6 +89,7 @@
}
fn total_supply(&self) -> Result<uint256> {
+ self.consume_store_reads(1)?;
Ok(<Pallet<T>>::total_supply(self).into())
}
}
@@ -94,11 +97,13 @@
#[solidity_interface(name = "ERC721", events(ERC721Events))]
impl<T: Config> NonfungibleHandle<T> {
fn balance_of(&self, owner: address) -> Result<uint256> {
+ self.consume_store_reads(1)?;
let owner = T::CrossAccountId::from_eth(owner);
let balance = <AccountBalance<T>>::get((self.id, owner));
Ok(balance.into())
}
fn owner_of(&self, token_id: uint256) -> Result<address> {
+ self.consume_store_reads(1)?;
let token: TokenId = token_id.try_into()?;
Ok(*<TokenData<T>>::get((self.id, token))
.ok_or("token not found")?
@@ -129,6 +134,7 @@
Err("not implemented".into())
}
+ #[weight(<SelfWeightOf<T>>::transfer_from())]
fn transfer_from(
&mut self,
caller: caller,
@@ -147,6 +153,7 @@
Ok(())
}
+ #[weight(<SelfWeightOf<T>>::approve())]
fn approve(
&mut self,
caller: caller,
@@ -189,6 +196,7 @@
#[solidity_interface(name = "ERC721Burnable")]
impl<T: Config> NonfungibleHandle<T> {
+ #[weight(<SelfWeightOf<T>>::burn_item())]
fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
let token = token_id.try_into()?;
@@ -206,6 +214,7 @@
/// `token_id` should be obtained with `next_token_id` method,
/// unlike standard, you can't specify it manually
+ #[weight(<SelfWeightOf<T>>::create_item())]
fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
@@ -235,6 +244,7 @@
/// `token_id` should be obtained with `next_token_id` method,
/// unlike standard, you can't specify it manually
#[solidity(rename_selector = "mintWithTokenURI")]
+ #[weight(<SelfWeightOf<T>>::create_item())]
fn mint_with_token_uri(
&mut self,
caller: caller,
@@ -276,6 +286,7 @@
#[solidity_interface(name = "ERC721UniqueExtensions")]
impl<T: Config> NonfungibleHandle<T> {
+ #[weight(<SelfWeightOf<T>>::transfer())]
fn transfer(
&mut self,
caller: caller,
@@ -291,6 +302,7 @@
Ok(())
}
+ #[weight(<SelfWeightOf<T>>::burn_from())]
fn burn_from(
&mut self,
caller: caller,
@@ -307,12 +319,14 @@
}
fn next_token_id(&self) -> Result<uint256> {
+ self.consume_store_reads(1)?;
Ok(<TokensMinted<T>>::get(self.id)
.checked_add(1)
.ok_or("item id overflow")?
.into())
}
+ #[weight(<SelfWeightOf<T>>::set_variable_metadata(data.len() as u32))]
fn set_variable_metadata(
&mut self,
caller: caller,
@@ -328,6 +342,7 @@
}
fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {
+ self.consume_store_reads(1)?;
let token: TokenId = token_id.try_into()?;
Ok(<TokenData<T>>::get((self.id, token))
@@ -335,6 +350,7 @@
.variable_data)
}
+ #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]
fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
@@ -363,6 +379,7 @@
}
#[solidity(rename_selector = "mintBulkWithTokenURI")]
+ #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]
fn mint_bulk_with_token_uri(
&mut self,
caller: caller,
@@ -411,16 +428,13 @@
impl<T: Config> NonfungibleHandle<T> {}
// Not a tests, but code generators
-generate_stubgen!(gen_impl, UniqueNFTCall, true);
-generate_stubgen!(gen_iface, UniqueNFTCall, false);
-
-pub const CODE: &[u8] = include_bytes!("./stubs/UniqueNFT.raw");
+generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);
+generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);
impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {
const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");
- fn call(mut self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileOutput> {
- let result = call_internal::<UniqueNFTCall, _>(*source, &mut self, value, input);
- self.0.recorder.evm_to_precompile_output(result)
+ fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileOutput> {
+ call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)
}
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -8,6 +8,7 @@
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
};
+use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
use sp_std::{vec::Vec, vec};
@@ -114,6 +115,14 @@
self.0
}
}
+impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {
+ fn recorder(&self) -> &SubstrateRecorder<T> {
+ self.0.recorder()
+ }
+ fn into_recorder(self) -> SubstrateRecorder<T> {
+ self.0.into_recorder()
+ }
+}
impl<T: Config> Deref for NonfungibleHandle<T> {
type Target = pallet_common::CollectionHandle<T>;
@@ -164,8 +173,7 @@
.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;
ensure!(
&token_data.owner == sender
- || (collection.limits.owner_can_transfer()
- && collection.is_owner_or_admin(sender)?),
+ || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),
<CommonError<T>>::NoPermission
);
@@ -194,7 +202,7 @@
));
}
- collection.log_infallible(ERC721Events::Transfer {
+ collection.log(ERC721Events::Transfer {
from: *token_data.owner.as_eth(),
to: H160::default(),
token_id: token.into(),
@@ -223,8 +231,7 @@
.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;
ensure!(
&token_data.owner == from
- || (collection.limits.owner_can_transfer()
- && collection.is_owner_or_admin(from)?),
+ || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),
<CommonError<T>>::NoPermission
);
@@ -251,9 +258,6 @@
} else {
None
};
-
- collection.consume_sstores(4)?;
- collection.consume_log(3, 0)?;
// =========
@@ -278,7 +282,7 @@
}
Self::set_allowance_unchecked(collection, from, token, None, true);
- collection.log_infallible(ERC721Events::Transfer {
+ collection.log(ERC721Events::Transfer {
from: *from.as_eth(),
to: *to.as_eth(),
token_id: token.into(),
@@ -298,8 +302,7 @@
sender: &T::CrossAccountId,
data: Vec<CreateItemData<T>>,
) -> DispatchResult {
- let unrestricted_minting = collection.is_owner_or_admin(sender)?;
- if !unrestricted_minting {
+ if !collection.is_owner_or_admin(sender) {
ensure!(
collection.mint_mode,
<CommonError<T>>::PublicMintingNotAllowed
@@ -313,14 +316,6 @@
for data in data.iter() {
<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;
- if !data.const_data.is_empty() {
- collection.consume_sstore()?;
- }
- if !data.variable_data.is_empty() {
- collection.consume_sstore()?;
- }
- collection.consume_sstore()?;
- collection.consume_log(3, 0)?;
}
let first_token = <TokensMinted<T>>::get(collection.id);
@@ -331,7 +326,6 @@
tokens_minted < collection.limits.token_limit(),
<CommonError<T>>::CollectionTokenLimitExceeded
);
- collection.consume_sstore()?;
let mut balances = BTreeMap::new();
for data in &data {
@@ -345,7 +339,6 @@
<CommonError<T>>::AccountTokenLimitExceeded,
);
}
- collection.consume_sstores(balances.len())?;
// =========
@@ -366,7 +359,7 @@
);
<Owned<T>>::insert((collection.id, &data.owner, token), true);
- collection.log_infallible(ERC721Events::Transfer {
+ collection.log(ERC721Events::Transfer {
from: H160::default(),
to: *data.owner.as_eth(),
token_id: token.into(),
@@ -393,7 +386,7 @@
<Allowance<T>>::insert((collection.id, token), spender);
// In ERC721 there is only one possible approved user of token, so we set
// approved user to spender
- collection.log_infallible(ERC721Events::Approval {
+ collection.log(ERC721Events::Approval {
owner: *sender.as_eth(),
approved: *spender.as_eth(),
token_id: token.into(),
@@ -423,7 +416,7 @@
if !assume_implicit_eth {
// In ERC721 there is only one possible approved user of token, so we set
// approved user to zero address
- collection.log_infallible(ERC721Events::Approval {
+ collection.log(ERC721Events::Approval {
owner: *sender.as_eth(),
approved: H160::default(),
token_id: token.into(),
@@ -463,7 +456,7 @@
<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
if &token_data.owner != sender {
ensure!(
- collection.ignores_owned_amount(sender)?,
+ collection.ignores_owned_amount(sender),
<CommonError<T>>::CantApproveMoreThanOwned
);
}
@@ -491,7 +484,7 @@
if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {
ensure!(
- collection.ignores_allowance(spender)?,
+ collection.ignores_allowance(spender),
<CommonError<T>>::TokenValueNotEnough
);
}
@@ -519,7 +512,7 @@
if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {
ensure!(
- collection.ignores_allowance(spender)?,
+ collection.ignores_allowance(spender),
<CommonError<T>>::TokenValueNotEnough
);
}
@@ -542,8 +535,6 @@
let token_data =
<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
collection.check_can_update_meta(sender, &token_data.owner)?;
-
- collection.consume_sstore()?;
// =========
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -58,7 +58,7 @@
}
fn burn_from() -> Weight {
- 0
+ <SelfWeightOf<T>>::burn_from()
}
fn set_variable_metadata(bytes: u32) -> Weight {
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -359,8 +359,7 @@
sender: &T::CrossAccountId,
data: Vec<CreateItemData<T>>,
) -> DispatchResult {
- let unrestricted_minting = collection.is_owner_or_admin(sender)?;
- if !unrestricted_minting {
+ if !collection.is_owner_or_admin(sender) {
ensure!(
collection.mint_mode,
<CommonError<T>>::PublicMintingNotAllowed
@@ -492,7 +491,7 @@
if <Balance<T>>::get((collection.id, token, sender)) < amount {
ensure!(
- collection.ignores_owned_amount(sender)? && Self::token_exists(collection, token),
+ collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),
<CommonError<T>>::CantApproveMoreThanOwned
);
}
@@ -523,7 +522,7 @@
<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
- collection.ignores_allowance(spender)?,
+ collection.ignores_allowance(spender),
<CommonError<T>>::TokenValueNotEnough
);
}
@@ -556,7 +555,7 @@
<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
- collection.ignores_allowance(spender)?,
+ collection.ignores_allowance(spender),
<CommonError<T>>::TokenValueNotEnough
);
}
@@ -585,7 +584,6 @@
&T::CrossAccountId::from_sub(collection.owner.clone()),
)?;
- collection.consume_sstore()?;
let token_data = <TokenData<T>>::get((collection.id, token));
// =========
runtime/Cargo.tomldiffbeforeafterboth--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -387,10 +387,10 @@
pallet-evm-transaction-payment = { path = '../pallets/evm-transaction-payment', default-features = false }
pallet-evm-coder-substrate = { default-features = false, path = "../pallets/evm-coder-substrate" }
-pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
-fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fp-rpc = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
+fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12-weights" }
################################################################################
# Build Dependencies
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -66,7 +66,7 @@
};
use smallvec::smallvec;
use codec::{Encode, Decode};
-use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};
+use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};
use fp_rpc::TransactionStatus;
use sp_core::crypto::Public;
use sp_runtime::{
@@ -247,10 +247,37 @@
}
}
+// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case
+// (contract, which only writes a lot of data),
+// approximating on top of our real store write weight
+parameter_types! {
+ pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;
+ pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;
+ pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();
+}
+
+/// Limiting EVM execution to 50% of block for substrate users and management tasks
+/// EVM transaction consumes more weight than substrate's, so we can't rely on them being
+/// scheduled fairly
+const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);
+parameter_types! {
+ pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());
+}
+
+pub enum FixedGasWeightMapping {}
+impl GasWeightMapping for FixedGasWeightMapping {
+ fn gas_to_weight(gas: u64) -> Weight {
+ gas.saturating_mul(WeightPerGas::get())
+ }
+ fn weight_to_gas(weight: Weight) -> u64 {
+ weight / WeightPerGas::get()
+ }
+}
+
impl pallet_evm::Config for Runtime {
type BlockGasLimit = BlockGasLimit;
type FeeCalculator = FixedFee;
- type GasWeightMapping = ();
+ type GasWeightMapping = FixedGasWeightMapping;
type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
type CallOrigin = EnsureAddressTruncated;
type WithdrawOrigin = EnsureAddressTruncated;
@@ -289,14 +316,9 @@
}
}
-parameter_types! {
- pub BlockGasLimit: U256 = U256::from(u32::max_value());
-}
-
impl pallet_ethereum::Config for Runtime {
type Event = Event;
type StateRoot = pallet_ethereum::IntermediateStateRoot;
- type EvmSubmitLog = pallet_evm::Pallet<Self>;
}
impl pallet_randomness_collective_flip::Config for Runtime {}
@@ -671,6 +693,7 @@
impl pallet_evm_coder_substrate::Config for Runtime {
type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;
+ type GasWeightMapping = FixedGasWeightMapping;
}
impl pallet_xcm::Config for Runtime {