difftreelog
refactor unify function and type signature handling
in: master
12 files changed
crates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -24,8 +24,8 @@
use quote::{quote, format_ident};
use inflector::cases;
use syn::{
- Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
- MetaNameValue, PatType, PathArguments, ReturnType, Type,
+ Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,
+ PatType, ReturnType, Type,
spanned::Spanned,
parse::{Parse, ParseStream},
parenthesized, Token, LitInt, LitStr,
@@ -601,12 +601,12 @@
let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);
let custom_signature = self.expand_custom_signature();
quote! {
- const #screaming_name_signature: ::evm_coder::custom_signature::FunctionSignature = #custom_signature;
+ const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;
const #screaming_name: ::evm_coder::types::bytes4 = {
let mut sum = ::evm_coder::sha3_const::Keccak256::new();
let mut pos = 0;
- while pos < Self::#screaming_name_signature.unit.len {
- sum = sum.update(&[Self::#screaming_name_signature.unit.data[pos]; 1]);
+ while pos < Self::#screaming_name_signature.len {
+ sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);
pos += 1;
}
let a = sum.finalize();
@@ -710,192 +710,28 @@
};
quote! {
Self::#pascal_name #matcher => ().into()
- }
- }
- }
-
- fn expand_type(ty: &Type, token_stream: &mut proc_macro2::TokenStream, read_signature: bool) {
- match ty {
- Type::Path(tp) => {
- if let Some(qself) = &tp.qself {
- panic!("no receiver expected {:?}", qself.ty.span());
- }
- let path = &tp.path;
- if path.segments.len() != 1 {
- panic!("expected path to have only one segment {:?}", path.span());
- }
- let last_segment = path.segments.last().unwrap();
-
- if last_segment.ident == "Vec" {
- let args = match &last_segment.arguments {
- PathArguments::AngleBracketed(e) => e,
- _ => {
- panic!("missing Vec generic {:?}", last_segment.arguments.span());
- }
- };
- let args = &args.args;
- if args.len() != 1 {
- panic!("expected only one generic for vec {:?}", args.span());
- }
- let arg = args.first().expect("first arg");
-
- let ty = match arg {
- GenericArgument::Type(ty) => ty,
- _ => {
- panic!("expected first generic to be type {:?}", arg.span());
- }
- };
-
- let mut vec_token = proc_macro2::TokenStream::new();
- Self::expand_type(ty, &mut vec_token, false);
- vec_token = if read_signature {
- quote! { (<Vec<#vec_token>>::SIGNATURE) }
- } else {
- quote! { <Vec<#vec_token>> }
- };
- token_stream.extend(vec_token);
- } else {
- if !last_segment.arguments.is_empty() {
- panic!(
- "unexpected generic arguments for non-vec type {:?}",
- last_segment.arguments.span()
- );
- }
-
- let ident = &last_segment.ident;
- let plain_token = if read_signature {
- quote! {
- (<#ident>::SIGNATURE)
- }
- } else {
- quote! {
- #ident
- }
- };
-
- token_stream.extend(plain_token);
- }
- }
-
- Type::Tuple(tt) => {
- // for ty in tt.elems.iter() {
- // out.push(AbiType::try_from(ty)?)
- // }
-
- let mut tuple_types = proc_macro2::TokenStream::new();
- let mut is_first = true;
-
- for ty in tt.elems.iter() {
- if is_first {
- is_first = false
- } else {
- tuple_types.extend(quote!(,));
- }
- Self::expand_type(ty, &mut tuple_types, false);
- }
- tuple_types = if read_signature {
- quote! { (<(#tuple_types)>::SIGNATURE) }
- } else {
- quote! { (#tuple_types) }
- };
- token_stream.extend(tuple_types);
}
-
- // Type::Array(arr) => {
- // let wrapped = AbiType::try_from(&arr.elem)?;
- // match &arr.len {
- // Expr::Lit(l) => match &l.lit {
- // Lit::Int(i) => {
- // let num = i.base10_parse::<usize>()?;
- // Ok(AbiType::Array(Box::new(wrapped), num as usize))
- // }
- // _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),
- // },
- // _ => Err(syn::Error::new(arr.len.span(), "should be literal")),
- // }
- // }
- _ => panic!("Unexpected type {ty:?}"),
}
- // match ty {
- // AbiType::Plain(ref ident) => {
- // let plain_token = if read_signature {
- // quote! {
- // (<#ident>::SIGNATURE)
- // }
- // } else {
- // quote! {
- // #ident
- // }
- // };
-
- // token_stream.extend(plain_token);
- // }
-
- // AbiType::Tuple(ref tuple_type) => {
- // let mut tuple_types = proc_macro2::TokenStream::new();
- // let mut is_first = true;
-
- // for ty in tuple_type {
- // if is_first {
- // is_first = false
- // } else {
- // tuple_types.extend(quote!(,));
- // }
- // Self::expand_type(ty, &mut tuple_types, false);
- // }
- // tuple_types = if read_signature {
- // quote! { (<(#tuple_types)>::SIGNATURE) }
- // } else {
- // quote! { (#tuple_types) }
- // };
- // token_stream.extend(tuple_types);
- // }
-
- // AbiType::Vec(ref vec_type) => {
- // let mut vec_token = proc_macro2::TokenStream::new();
- // Self::expand_type(vec_type.as_ref(), &mut vec_token, false);
- // vec_token = if read_signature {
- // quote! { (<Vec<#vec_token>>::SIGNATURE) }
- // } else {
- // quote! { <Vec<#vec_token>> }
- // };
- // token_stream.extend(vec_token);
- // }
-
- // AbiType::Array(_, _) => todo!("Array eth signature"),
- // };
}
fn expand_custom_signature(&self) -> proc_macro2::TokenStream {
- let mut token_stream = TokenStream::new();
+ let mut args = TokenStream::new();
let mut is_first = true;
- for arg in &self.args {
- if arg.is_special() {
- continue;
- }
-
- if is_first {
- is_first = false;
- } else {
- token_stream.extend(quote!(,));
- }
- Self::expand_type(&arg.ty, &mut token_stream, true);
+ for arg in self.args.iter().filter(|a| !a.is_special()) {
+ is_first = false;
+ let ty = &arg.ty;
+ args.extend(quote! {nameof(#ty)});
+ args.extend(quote! {fixed(",")})
}
+ // Remove trailing comma
if !is_first {
- token_stream.extend(quote!(,));
+ args.extend(quote! {shift_left(1)})
}
let func_name = self.camel_name.clone();
- let func_name = quote!(SignaturePreferences {
- open_name: Some(SignatureUnit::new(#func_name)),
- open_delimiter: Some(SignatureUnit::new("(")),
- param_delimiter: Some(SignatureUnit::new(",")),
- close_delimiter: Some(SignatureUnit::new(")")),
- close_name: None,
- });
- quote!({ ::evm_coder::make_signature!(new fn(#func_name), #token_stream) })
+ quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }
}
fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
@@ -916,12 +752,6 @@
let screaming_name = &self.screaming_name;
let hide = self.hide;
let custom_signature = self.expand_custom_signature();
- let custom_signature = quote!(
- {
- const cs: FunctionSignature = #custom_signature;
- cs
- }
- );
let is_payable = self.has_value_args;
quote! {
crates/evm-coder/src/abi.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi.rs
+++ b/crates/evm-coder/src/abi.rs
@@ -27,7 +27,7 @@
execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},
types::*,
make_signature,
- custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT},
+ custom_signature::{SignatureUnit},
};
use crate::execution::Result;
@@ -428,7 +428,7 @@
}
impl<R: Signature> Signature for Vec<R> {
- make_signature!(new nameof(R) fixed("[]"));
+ const SIGNATURE: SignatureUnit = make_signature!(new nameof(R) fixed("[]"));
}
impl sealed::CanBePlacedInVec for EthCrossAccount {}
@@ -522,7 +522,7 @@
where
$($ident: Signature,)+
{
- make_signature!(
+ const SIGNATURE: SignatureUnit = make_signature!(
new fixed("(")
$(nameof($ident) fixed(","))+
shift_left(1)
@@ -758,13 +758,13 @@
1ACF2D55
0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
-
+
0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
000000000000000000000000000000000000000000000000000000000000000A // uint256
-
+
000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
0000000000000000000000000000000000000000000000000000000000000014 // uint256
-
+
0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
000000000000000000000000000000000000000000000000000000000000001E // uint256
"
crates/evm-coder/src/custom_signature.rsdiffbeforeafterboth--- a/crates/evm-coder/src/custom_signature.rs
+++ b/crates/evm-coder/src/custom_signature.rs
@@ -74,132 +74,11 @@
//! impl<T: SoliditySignature> SoliditySignature for Vec<T> {
//! make_signature!(new nameof(T) fixed("[]"));
//! }
-//!
-//! // Function signature settings
-//! const SIGNATURE_PREFERENCES: SignaturePreferences = SignaturePreferences {
-//! open_name: Some(SignatureUnit::new("some_funk")),
-//! open_delimiter: Some(SignatureUnit::new("(")),
-//! param_delimiter: Some(SignatureUnit::new(",")),
-//! close_delimiter: Some(SignatureUnit::new(")")),
-//! close_name: None,
-//! };
-//!
-//! // Create functions signatures
-//! fn make_func_without_args() {
-//! const SIG: FunctionSignature = make_signature!(
-//! new fn(SIGNATURE_PREFERENCES),
-//! );
-//! let name = SIG.as_str();
-//! similar_asserts::assert_eq!(name, "some_funk()");
-//! }
-//!
-//! fn make_func_with_3_args() {
-//! const SIG: FunctionSignature = make_signature!(
-//! new fn(SIGNATURE_PREFERENCES),
-//! (<u8>::SIGNATURE),
-//! (<u8>::SIGNATURE),
-//! (<Vec<u8>>::SIGNATURE),
-//! );
-//! let name = SIG.as_str();
-//! similar_asserts::assert_eq!(name, "some_funk(uint8,uint8,uint8[])");
-//! }
//! ```
-use core::str::from_utf8;
/// The maximum length of the signature.
pub const SIGNATURE_SIZE_LIMIT: usize = 256;
-
-/// Function signature formatting preferences.
-#[derive(Debug)]
-pub struct SignaturePreferences {
- /// The name of the function before the list of parameters: `*some*(param1,param2)func`
- pub open_name: Option<SignatureUnit>,
- /// Opening separator: `some*(*param1,param2)func`
- pub open_delimiter: Option<SignatureUnit>,
- /// Parameters separator: `some(param1*,*param2)func`
- pub param_delimiter: Option<SignatureUnit>,
- /// Closinging separator: `some(param1,param2*)*func`
- pub close_delimiter: Option<SignatureUnit>,
- /// The name of the function after the list of parameters: `some(param1,param2)*func*`
- pub close_name: Option<SignatureUnit>,
-}
-
-/// Constructs and stores the signature of the function.
-#[derive(Debug)]
-pub struct FunctionSignature {
- /// Storage for function signature.
- pub unit: SignatureUnit,
- preferences: SignaturePreferences,
-}
-impl FunctionSignature {
- /// Start constructing the signature. It is written to the storage
- /// [`SignaturePreferences::open_name`] and [`SignaturePreferences::open_delimiter`].
- pub const fn new(preferences: SignaturePreferences) -> FunctionSignature {
- let mut dst = [0_u8; SIGNATURE_SIZE_LIMIT];
- let mut dst_offset = 0;
- if let Some(ref name) = preferences.open_name {
- crate::make_signature!(@copy(name.data, dst, name.len, dst_offset));
- }
- if let Some(ref delimiter) = preferences.open_delimiter {
- crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
- }
- FunctionSignature {
- unit: SignatureUnit {
- data: dst,
- len: dst_offset,
- },
- preferences,
- }
- }
-
- /// Add a function parameter to the signature. It is written to the storage
- /// `param` [`SignatureUnit`] and [`SignaturePreferences::param_delimiter`].
- pub const fn add_param(
- signature: FunctionSignature,
- param: SignatureUnit,
- ) -> FunctionSignature {
- let mut dst = signature.unit.data;
- let mut dst_offset = signature.unit.len;
- crate::make_signature!(@copy(param.data, dst, param.len, dst_offset));
- if let Some(ref delimiter) = signature.preferences.param_delimiter {
- crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
- }
- FunctionSignature {
- unit: SignatureUnit {
- data: dst,
- len: dst_offset,
- },
- ..signature
- }
- }
-
- /// Complete signature construction. It is written to the storage
- /// [`SignaturePreferences::close_delimiter`] and [`SignaturePreferences::close_name`].
- pub const fn done(signature: FunctionSignature, owerride: bool) -> FunctionSignature {
- let mut dst = signature.unit.data;
- let mut dst_offset = signature.unit.len - if owerride { 1 } else { 0 };
- if let Some(ref delimiter) = signature.preferences.close_delimiter {
- crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
- }
- if let Some(ref name) = signature.preferences.close_name {
- crate::make_signature!(@copy(name.data, dst, name.len, dst_offset));
- }
- FunctionSignature {
- unit: SignatureUnit {
- data: dst,
- len: dst_offset,
- },
- ..signature
- }
- }
-
- /// Represent the signature as `&str'.
- pub fn as_str(&self) -> &str {
- from_utf8(&self.unit.data[..self.unit.len]).expect("bad utf-8")
- }
-}
-
/// Storage for the signature or its elements.
#[derive(Debug)]
pub struct SignatureUnit {
@@ -222,6 +101,10 @@
len: name_len,
}
}
+ /// String conversion
+ pub fn as_str(&self) -> Option<&str> {
+ core::str::from_utf8(&self.data[0..self.len]).ok()
+ }
}
/// ### Macro to create signatures of types and functions.
@@ -231,85 +114,52 @@
/// make_signature!(new fixed("uint8")); // Simple type
/// make_signature!(new fixed("(") nameof(u8) fixed(",") nameof(u8) fixed(")")); // Composite type
/// ```
-/// Format for creating a function of the function:
-/// ```ignore
-/// const SIG: FunctionSignature = make_signature!(
-/// new fn(SIGNATURE_PREFERENCES),
-/// (u8::SIGNATURE),
-/// (<(u8,u8)>::SIGNATURE),
-/// );
-/// ```
#[macro_export]
macro_rules! make_signature {
- (new fn($func:expr)$(,)*) => {
- {
- let fs = FunctionSignature::new($func);
- let fs = FunctionSignature::done(fs, false);
- fs
- }
- };
- (new fn($func:expr), $($tt:tt,)*) => {
- {
- let fs = FunctionSignature::new($func);
- let fs = make_signature!(@param; fs, $($tt),*);
- fs
- }
+ (new $($tt:tt)*) => {
+ ($crate::custom_signature::SignatureUnit {
+ data: {
+ let mut out = [0u8; $crate::custom_signature::SIGNATURE_SIZE_LIMIT];
+ let mut dst_offset = 0;
+ $crate::make_signature!(@data(out, dst_offset); $($tt)*);
+ out
+ },
+ len: {0 + $crate::make_signature!(@size; $($tt)*)},
+ })
};
- (@param; $func:expr) => {
- FunctionSignature::done($func, true)
+ (@size;) => {
+ 0
};
- (@param; $func:expr, $param:expr) => {
- make_signature!(@param; FunctionSignature::add_param($func, $param))
+ (@size; fixed($expr:expr) $($tt:tt)*) => {
+ $expr.len() + $crate::make_signature!(@size; $($tt)*)
};
- (@param; $func:expr, $param:expr, $($tt:tt),*) => {
- make_signature!(@param; FunctionSignature::add_param($func, $param), $($tt),*)
+ (@size; nameof($expr:ty) $($tt:tt)*) => {
+ <$expr>::SIGNATURE.len + $crate::make_signature!(@size; $($tt)*)
};
-
- (new $($tt:tt)*) => {
- const SIGNATURE: SignatureUnit = SignatureUnit {
- data: {
- let mut out = [0u8; SIGNATURE_SIZE_LIMIT];
- let mut dst_offset = 0;
- make_signature!(@data(out, dst_offset); $($tt)*);
- out
- },
- len: {0 + make_signature!(@size; $($tt)*)},
- };
- };
-
- (@size;) => {
- 0
- };
- (@size; fixed($expr:expr) $($tt:tt)*) => {
- $expr.len() + make_signature!(@size; $($tt)*)
- };
- (@size; nameof($expr:ty) $($tt:tt)*) => {
- <$expr>::SIGNATURE.len + make_signature!(@size; $($tt)*)
- };
(@size; shift_left($expr:expr) $($tt:tt)*) => {
- make_signature!(@size; $($tt)*) - $expr
+ $crate::make_signature!(@size; $($tt)*) - $expr
};
- (@data($dst:ident, $dst_offset:ident);) => {};
- (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
- {
- let data = $expr.as_bytes();
+ (@data($dst:ident, $dst_offset:ident);) => {};
+ (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
+ {
+ let data = $expr.as_bytes();
let data_len = data.len();
- make_signature!(@copy(data, $dst, data_len, $dst_offset));
- }
- make_signature!(@data($dst, $dst_offset); $($tt)*)
- };
- (@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {
- {
- make_signature!(@copy(&<$expr>::SIGNATURE.data, $dst, <$expr>::SIGNATURE.len, $dst_offset));
- }
- make_signature!(@data($dst, $dst_offset); $($tt)*)
- };
+ $crate::make_signature!(@copy(data, $dst, data_len, $dst_offset));
+ }
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+ (@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {
+ {
+ $crate::make_signature!(@copy(&<$expr>::SIGNATURE.data, $dst, <$expr>::SIGNATURE.len, $dst_offset));
+ }
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
(@data($dst:ident, $dst_offset:ident); shift_left($expr:expr) $($tt:tt)*) => {
- $dst_offset -= $expr;
- make_signature!(@data($dst, $dst_offset); $($tt)*)
- };
+ $dst_offset -= $expr;
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
(@copy($src:expr, $dst:expr, $src_len:expr, $dst_offset:ident)) => {
{
@@ -328,7 +178,7 @@
mod test {
use core::str::from_utf8;
- use super::{SIGNATURE_SIZE_LIMIT, SignatureUnit, FunctionSignature, SignaturePreferences};
+ use super::{SIGNATURE_SIZE_LIMIT, SignatureUnit};
trait Name {
const SIGNATURE: SignatureUnit;
@@ -339,19 +189,21 @@
}
impl Name for u8 {
- make_signature!(new fixed("uint8"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint8"));
}
impl Name for u32 {
- make_signature!(new fixed("uint32"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint32"));
}
impl<T: Name> Name for Vec<T> {
- make_signature!(new nameof(T) fixed("[]"));
+ const SIGNATURE: SignatureUnit = make_signature!(new nameof(T) fixed("[]"));
}
impl<A: Name, B: Name> Name for (A, B) {
- make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
+ const SIGNATURE: SignatureUnit =
+ make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
}
impl<A: Name> Name for (A,) {
- make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));
+ const SIGNATURE: SignatureUnit =
+ make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));
}
struct MaxSize();
@@ -361,14 +213,6 @@
len: SIGNATURE_SIZE_LIMIT,
};
}
-
- const SIGNATURE_PREFERENCES: SignaturePreferences = SignaturePreferences {
- open_name: Some(SignatureUnit::new("some_funk")),
- open_delimiter: Some(SignatureUnit::new("(")),
- param_delimiter: Some(SignatureUnit::new(",")),
- close_delimiter: Some(SignatureUnit::new(")")),
- close_name: None,
- };
#[test]
fn simple() {
@@ -421,68 +265,6 @@
#[test]
fn max_size() {
assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));
- }
-
- #[test]
- fn make_func_without_args() {
- const SIG: FunctionSignature = make_signature!(
- new fn(SIGNATURE_PREFERENCES)
- );
- let name = SIG.as_str();
- similar_asserts::assert_eq!(name, "some_funk()");
- }
-
- #[test]
- fn make_func_with_1_args() {
- const SIG: FunctionSignature = make_signature!(
- new fn(SIGNATURE_PREFERENCES),
- (<u8>::SIGNATURE),
- );
- let name = SIG.as_str();
- similar_asserts::assert_eq!(name, "some_funk(uint8)");
- }
-
- #[test]
- fn make_func_with_2_args() {
- const SIG: FunctionSignature = make_signature!(
- new fn(SIGNATURE_PREFERENCES),
- (u8::SIGNATURE),
- (<Vec<u32>>::SIGNATURE),
- );
- let name = SIG.as_str();
- similar_asserts::assert_eq!(name, "some_funk(uint8,uint32[])");
- }
-
- #[test]
- fn make_func_with_3_args() {
- const SIG: FunctionSignature = make_signature!(
- new fn(SIGNATURE_PREFERENCES),
- (<u8>::SIGNATURE),
- (<u32>::SIGNATURE),
- (<Vec<u32>>::SIGNATURE),
- );
- let name = SIG.as_str();
- similar_asserts::assert_eq!(name, "some_funk(uint8,uint32,uint32[])");
- }
-
- #[test]
- fn make_slice_from_signature() {
- const SIG: FunctionSignature = make_signature!(
- new fn(SIGNATURE_PREFERENCES),
- (<u8>::SIGNATURE),
- (<u32>::SIGNATURE),
- (<Vec<u32>>::SIGNATURE),
- );
- const NAME: [u8; SIG.unit.len] = {
- let mut name: [u8; SIG.unit.len] = [0; SIG.unit.len];
- let mut i = 0;
- while i < SIG.unit.len {
- name[i] = SIG.unit.data[i];
- i += 1;
- }
- name
- };
- similar_asserts::assert_eq!(&NAME, b"some_funk(uint8,uint32,uint32[])");
}
#[test]
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -122,7 +122,7 @@
use primitive_types::{U256, H160, H256};
use core::str::from_utf8;
- use crate::custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT};
+ use crate::custom_signature::SignatureUnit;
pub trait Signature {
const SIGNATURE: SignatureUnit;
@@ -133,14 +133,14 @@
}
impl Signature for bool {
- make_signature!(new fixed("bool"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bool"));
}
macro_rules! define_simple_type {
(type $ident:ident = $ty:ty) => {
pub type $ident = $ty;
impl Signature for $ty {
- make_signature!(new fixed(stringify!($ident)));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ident)));
}
};
}
@@ -165,7 +165,7 @@
#[derive(Default, Debug)]
pub struct bytes(pub Vec<u8>);
impl Signature for bytes {
- make_signature!(new fixed("bytes"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));
}
/// Solidity doesn't have `void` type, however we have special implementation
@@ -259,7 +259,7 @@
}
impl Signature for EthCrossAccount {
- make_signature!(new fixed("(address,uint256)"));
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("(address,uint256)"));
}
/// Convert `CrossAccountId` to `uint256`.
crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -32,7 +32,7 @@
cmp::Reverse,
};
use impl_trait_for_tuples::impl_for_tuples;
-use crate::{types::*, custom_signature::FunctionSignature};
+use crate::{types::*, custom_signature::SignatureUnit};
#[derive(Default)]
pub struct TypeCollector {
@@ -486,7 +486,7 @@
pub docs: &'static [&'static str],
pub selector: u32,
pub hide: bool,
- pub custom_signature: FunctionSignature,
+ pub custom_signature: SignatureUnit,
pub name: &'static str,
pub args: A,
pub result: R,
@@ -512,7 +512,7 @@
writeln!(
writer,
"\t{hide_comment}/// or in textual repr: {}",
- self.custom_signature.as_str()
+ self.custom_signature.as_str().expect("bad utf-8")
)?;
write!(writer, "\t{hide_comment}function {}(", self.name)?;
self.args.solidity_name(writer, tc)?;
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -21,8 +21,6 @@
types::*,
execution::{Result, Error},
weight,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
};
pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};
use pallet_evm_coder_substrate::dispatch_to_evm;
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -19,13 +19,7 @@
extern crate alloc;
use core::marker::PhantomData;
use evm_coder::{
- abi::AbiWriter,
- execution::Result,
- generate_stubgen, solidity_interface,
- types::*,
- ToLog,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
+ abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
};
use pallet_evm::{
ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -19,15 +19,7 @@
extern crate alloc;
use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
use core::convert::TryInto;
-use evm_coder::{
- ToLog,
- execution::*,
- generate_stubgen, solidity_interface,
- types::*,
- weight,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
use up_data_structs::CollectionMode;
use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
use sp_std::vec::Vec;
pallets/nonfungible/src/erc.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{28 ToLog,29 execution::*,30 generate_stubgen, solidity, solidity_interface,31 types::*,32 weight,33 custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},34 make_signature,35};36use frame_support::BoundedVec;37use up_data_structs::{38 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,39 CollectionPropertiesVec,40};41use pallet_evm_coder_substrate::dispatch_to_evm;42use sp_std::vec::Vec;43use pallet_common::{44 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},45 CollectionHandle, CollectionPropertyPermissions,46};47use pallet_evm::{account::CrossAccountId, PrecompileHandle};48use pallet_evm_coder_substrate::call;49use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};5051use crate::{52 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,53 SelfWeightOf, weights::WeightInfo, TokenProperties,54};5556/// @title A contract that allows to set and delete token properties and change token property permissions.57#[solidity_interface(name = TokenProperties)]58impl<T: Config> NonfungibleHandle<T> {59 /// @notice Set permissions for token property.60 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.61 /// @param key Property key.62 /// @param isMutable Permission to mutate property.63 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.64 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.65 fn set_token_property_permission(66 &mut self,67 caller: caller,68 key: string,69 is_mutable: bool,70 collection_admin: bool,71 token_owner: bool,72 ) -> Result<()> {73 let caller = T::CrossAccountId::from_eth(caller);74 <Pallet<T>>::set_property_permission(75 self,76 &caller,77 PropertyKeyPermission {78 key: <Vec<u8>>::from(key)79 .try_into()80 .map_err(|_| "too long key")?,81 permission: PropertyPermission {82 mutable: is_mutable,83 collection_admin,84 token_owner,85 },86 },87 )88 .map_err(dispatch_to_evm::<T>)89 }9091 /// @notice Set token property value.92 /// @dev Throws error if `msg.sender` has no permission to edit the property.93 /// @param tokenId ID of the token.94 /// @param key Property key.95 /// @param value Property value.96 fn set_property(97 &mut self,98 caller: caller,99 token_id: uint256,100 key: string,101 value: bytes,102 ) -> Result<()> {103 let caller = T::CrossAccountId::from_eth(caller);104 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;105 let key = <Vec<u8>>::from(key)106 .try_into()107 .map_err(|_| "key too long")?;108 let value = value.0.try_into().map_err(|_| "value too long")?;109110 let nesting_budget = self111 .recorder112 .weight_calls_budget(<StructureWeight<T>>::find_parent());113114 <Pallet<T>>::set_token_property(115 self,116 &caller,117 TokenId(token_id),118 Property { key, value },119 &nesting_budget,120 )121 .map_err(dispatch_to_evm::<T>)122 }123124 /// @notice Set token properties value.125 /// @dev Throws error if `msg.sender` has no permission to edit the property.126 /// @param tokenId ID of the token.127 /// @param properties settable properties128 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]129 fn set_properties(130 &mut self,131 caller: caller,132 token_id: uint256,133 properties: Vec<(string, bytes)>,134 ) -> Result<()> {135 let caller = T::CrossAccountId::from_eth(caller);136 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;137138 let nesting_budget = self139 .recorder140 .weight_calls_budget(<StructureWeight<T>>::find_parent());141142 let properties = properties143 .into_iter()144 .map(|(key, value)| {145 let key = <Vec<u8>>::from(key)146 .try_into()147 .map_err(|_| "key too large")?;148149 let value = value.0.try_into().map_err(|_| "value too large")?;150151 Ok(Property { key, value })152 })153 .collect::<Result<Vec<_>>>()?;154155 <Pallet<T>>::set_token_properties(156 self,157 &caller,158 TokenId(token_id),159 properties.into_iter(),160 <Pallet<T>>::token_exists(&self, TokenId(token_id)),161 &nesting_budget,162 )163 .map_err(dispatch_to_evm::<T>)164 }165166 /// @notice Delete token property value.167 /// @dev Throws error if `msg.sender` has no permission to edit the property.168 /// @param tokenId ID of the token.169 /// @param key Property key.170 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {171 let caller = T::CrossAccountId::from_eth(caller);172 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;173 let key = <Vec<u8>>::from(key)174 .try_into()175 .map_err(|_| "key too long")?;176177 let nesting_budget = self178 .recorder179 .weight_calls_budget(<StructureWeight<T>>::find_parent());180181 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)182 .map_err(dispatch_to_evm::<T>)183 }184185 /// @notice Get token property value.186 /// @dev Throws error if key not found187 /// @param tokenId ID of the token.188 /// @param key Property key.189 /// @return Property value bytes190 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {191 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;192 let key = <Vec<u8>>::from(key)193 .try_into()194 .map_err(|_| "key too long")?;195196 let props = <TokenProperties<T>>::get((self.id, token_id));197 let prop = props.get(&key).ok_or("key not found")?;198199 Ok(prop.to_vec().into())200 }201}202203#[derive(ToLog)]204pub enum ERC721Events {205 /// @dev This emits when ownership of any NFT changes by any mechanism.206 /// This event emits when NFTs are created (`from` == 0) and destroyed207 /// (`to` == 0). Exception: during contract creation, any number of NFTs208 /// may be created and assigned without emitting Transfer. At the time of209 /// any transfer, the approved address for that NFT (if any) is reset to none.210 Transfer {211 #[indexed]212 from: address,213 #[indexed]214 to: address,215 #[indexed]216 token_id: uint256,217 },218 /// @dev This emits when the approved address for an NFT is changed or219 /// reaffirmed. The zero address indicates there is no approved address.220 /// When a Transfer event emits, this also indicates that the approved221 /// address for that NFT (if any) is reset to none.222 Approval {223 #[indexed]224 owner: address,225 #[indexed]226 approved: address,227 #[indexed]228 token_id: uint256,229 },230 /// @dev This emits when an operator is enabled or disabled for an owner.231 /// The operator can manage all NFTs of the owner.232 #[allow(dead_code)]233 ApprovalForAll {234 #[indexed]235 owner: address,236 #[indexed]237 operator: address,238 approved: bool,239 },240}241242#[derive(ToLog)]243pub enum ERC721UniqueMintableEvents {244 #[allow(dead_code)]245 MintingFinished {},246}247248/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension249/// @dev See https://eips.ethereum.org/EIPS/eip-721250#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]251impl<T: Config> NonfungibleHandle<T>252where253 T::AccountId: From<[u8; 32]>,254{255 /// @notice A descriptive name for a collection of NFTs in this contract256 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`257 #[solidity(hide, rename_selector = "name")]258 fn name_proxy(&self) -> Result<string> {259 self.name()260 }261262 /// @notice An abbreviated name for NFTs in this contract263 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`264 #[solidity(hide, rename_selector = "symbol")]265 fn symbol_proxy(&self) -> Result<string> {266 self.symbol()267 }268269 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.270 ///271 /// @dev If the token has a `url` property and it is not empty, it is returned.272 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.273 /// If the collection property `baseURI` is empty or absent, return "" (empty string)274 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix275 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).276 ///277 /// @return token's const_metadata278 #[solidity(rename_selector = "tokenURI")]279 fn token_uri(&self, token_id: uint256) -> Result<string> {280 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;281282 match get_token_property(self, token_id_u32, &key::url()).as_deref() {283 Err(_) | Ok("") => (),284 Ok(url) => {285 return Ok(url.into());286 }287 };288289 let base_uri =290 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())291 .map(BoundedVec::into_inner)292 .map(string::from_utf8)293 .transpose()294 .map_err(|e| {295 Error::Revert(alloc::format!(296 "Can not convert value \"baseURI\" to string with error \"{}\"",297 e298 ))299 })?;300301 let base_uri = match base_uri.as_deref() {302 None | Some("") => {303 return Ok("".into());304 }305 Some(base_uri) => base_uri.into(),306 };307308 Ok(309 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {310 Err(_) | Ok("") => base_uri,311 Ok(suffix) => base_uri + suffix,312 },313 )314 }315}316317/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension318/// @dev See https://eips.ethereum.org/EIPS/eip-721319#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]320impl<T: Config> NonfungibleHandle<T> {321 /// @notice Enumerate valid NFTs322 /// @param index A counter less than `totalSupply()`323 /// @return The token identifier for the `index`th NFT,324 /// (sort order not specified)325 fn token_by_index(&self, index: uint256) -> Result<uint256> {326 Ok(index)327 }328329 /// @dev Not implemented330 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {331 // TODO: Not implemetable332 Err("not implemented".into())333 }334335 /// @notice Count NFTs tracked by this contract336 /// @return A count of valid NFTs tracked by this contract, where each one of337 /// them has an assigned and queryable owner not equal to the zero address338 fn total_supply(&self) -> Result<uint256> {339 self.consume_store_reads(1)?;340 Ok(<Pallet<T>>::total_supply(self).into())341 }342}343344/// @title ERC-721 Non-Fungible Token Standard345/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md346#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]347impl<T: Config> NonfungibleHandle<T> {348 /// @notice Count all NFTs assigned to an owner349 /// @dev NFTs assigned to the zero address are considered invalid, and this350 /// function throws for queries about the zero address.351 /// @param owner An address for whom to query the balance352 /// @return The number of NFTs owned by `owner`, possibly zero353 fn balance_of(&self, owner: address) -> Result<uint256> {354 self.consume_store_reads(1)?;355 let owner = T::CrossAccountId::from_eth(owner);356 let balance = <AccountBalance<T>>::get((self.id, owner));357 Ok(balance.into())358 }359 /// @notice Find the owner of an NFT360 /// @dev NFTs assigned to zero address are considered invalid, and queries361 /// about them do throw.362 /// @param tokenId The identifier for an NFT363 /// @return The address of the owner of the NFT364 fn owner_of(&self, token_id: uint256) -> Result<address> {365 self.consume_store_reads(1)?;366 let token: TokenId = token_id.try_into()?;367 Ok(*<TokenData<T>>::get((self.id, token))368 .ok_or("token not found")?369 .owner370 .as_eth())371 }372 /// @dev Not implemented373 #[solidity(rename_selector = "safeTransferFrom")]374 fn safe_transfer_from_with_data(375 &mut self,376 _from: address,377 _to: address,378 _token_id: uint256,379 _data: bytes,380 ) -> Result<void> {381 // TODO: Not implemetable382 Err("not implemented".into())383 }384 /// @dev Not implemented385 fn safe_transfer_from(386 &mut self,387 _from: address,388 _to: address,389 _token_id: uint256,390 ) -> Result<void> {391 // TODO: Not implemetable392 Err("not implemented".into())393 }394395 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE396 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE397 /// THEY MAY BE PERMANENTLY LOST398 /// @dev Throws unless `msg.sender` is the current owner or an authorized399 /// operator for this NFT. Throws if `from` is not the current owner. Throws400 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.401 /// @param from The current owner of the NFT402 /// @param to The new owner403 /// @param tokenId The NFT to transfer404 #[weight(<SelfWeightOf<T>>::transfer_from())]405 fn transfer_from(406 &mut self,407 caller: caller,408 from: address,409 to: address,410 token_id: uint256,411 ) -> Result<void> {412 let caller = T::CrossAccountId::from_eth(caller);413 let from = T::CrossAccountId::from_eth(from);414 let to = T::CrossAccountId::from_eth(to);415 let token = token_id.try_into()?;416 let budget = self417 .recorder418 .weight_calls_budget(<StructureWeight<T>>::find_parent());419420 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)421 .map_err(dispatch_to_evm::<T>)?;422 Ok(())423 }424425 /// @notice Set or reaffirm the approved address for an NFT426 /// @dev The zero address indicates there is no approved address.427 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized428 /// operator of the current owner.429 /// @param approved The new approved NFT controller430 /// @param tokenId The NFT to approve431 #[weight(<SelfWeightOf<T>>::approve())]432 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {433 let caller = T::CrossAccountId::from_eth(caller);434 let approved = T::CrossAccountId::from_eth(approved);435 let token = token_id.try_into()?;436437 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))438 .map_err(dispatch_to_evm::<T>)?;439 Ok(())440 }441442 /// @dev Not implemented443 fn set_approval_for_all(444 &mut self,445 _caller: caller,446 _operator: address,447 _approved: bool,448 ) -> Result<void> {449 // TODO: Not implemetable450 Err("not implemented".into())451 }452453 /// @dev Not implemented454 fn get_approved(&self, _token_id: uint256) -> Result<address> {455 // TODO: Not implemetable456 Err("not implemented".into())457 }458459 /// @dev Not implemented460 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {461 // TODO: Not implemetable462 Err("not implemented".into())463 }464}465466/// @title ERC721 Token that can be irreversibly burned (destroyed).467#[solidity_interface(name = ERC721Burnable)]468impl<T: Config> NonfungibleHandle<T> {469 /// @notice Burns a specific ERC721 token.470 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized471 /// operator of the current owner.472 /// @param tokenId The NFT to approve473 #[weight(<SelfWeightOf<T>>::burn_item())]474 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {475 let caller = T::CrossAccountId::from_eth(caller);476 let token = token_id.try_into()?;477478 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;479 Ok(())480 }481}482483/// @title ERC721 minting logic.484#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]485impl<T: Config> NonfungibleHandle<T> {486 fn minting_finished(&self) -> Result<bool> {487 Ok(false)488 }489490 /// @notice Function to mint token.491 /// @param to The new owner492 /// @return uint256 The id of the newly minted token493 #[weight(<SelfWeightOf<T>>::create_item())]494 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {495 let token_id: uint256 = <TokensMinted<T>>::get(self.id)496 .checked_add(1)497 .ok_or("item id overflow")?498 .into();499 self.mint_check_id(caller, to, token_id)?;500 Ok(token_id)501 }502503 /// @notice Function to mint token.504 /// @dev `tokenId` should be obtained with `nextTokenId` method,505 /// unlike standard, you can't specify it manually506 /// @param to The new owner507 /// @param tokenId ID of the minted NFT508 #[solidity(hide, rename_selector = "mint")]509 #[weight(<SelfWeightOf<T>>::create_item())]510 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {511 let caller = T::CrossAccountId::from_eth(caller);512 let to = T::CrossAccountId::from_eth(to);513 let token_id: u32 = token_id.try_into()?;514 let budget = self515 .recorder516 .weight_calls_budget(<StructureWeight<T>>::find_parent());517518 if <TokensMinted<T>>::get(self.id)519 .checked_add(1)520 .ok_or("item id overflow")?521 != token_id522 {523 return Err("item id should be next".into());524 }525526 <Pallet<T>>::create_item(527 self,528 &caller,529 CreateItemData::<T> {530 properties: BoundedVec::default(),531 owner: to,532 },533 &budget,534 )535 .map_err(dispatch_to_evm::<T>)?;536537 Ok(true)538 }539540 /// @notice Function to mint token with the given tokenUri.541 /// @param to The new owner542 /// @param tokenUri Token URI that would be stored in the NFT properties543 /// @return uint256 The id of the newly minted token544 #[solidity(rename_selector = "mintWithTokenURI")]545 #[weight(<SelfWeightOf<T>>::create_item())]546 fn mint_with_token_uri(547 &mut self,548 caller: caller,549 to: address,550 token_uri: string,551 ) -> Result<uint256> {552 let token_id: uint256 = <TokensMinted<T>>::get(self.id)553 .checked_add(1)554 .ok_or("item id overflow")?555 .into();556 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;557 Ok(token_id)558 }559560 /// @notice Function to mint token with the given tokenUri.561 /// @dev `tokenId` should be obtained with `nextTokenId` method,562 /// unlike standard, you can't specify it manually563 /// @param to The new owner564 /// @param tokenId ID of the minted NFT565 /// @param tokenUri Token URI that would be stored in the NFT properties566 #[solidity(hide, rename_selector = "mintWithTokenURI")]567 #[weight(<SelfWeightOf<T>>::create_item())]568 fn mint_with_token_uri_check_id(569 &mut self,570 caller: caller,571 to: address,572 token_id: uint256,573 token_uri: string,574 ) -> Result<bool> {575 let key = key::url();576 let permission = get_token_permission::<T>(self.id, &key)?;577 if !permission.collection_admin {578 return Err("Operation is not allowed".into());579 }580581 let caller = T::CrossAccountId::from_eth(caller);582 let to = T::CrossAccountId::from_eth(to);583 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;584 let budget = self585 .recorder586 .weight_calls_budget(<StructureWeight<T>>::find_parent());587588 if <TokensMinted<T>>::get(self.id)589 .checked_add(1)590 .ok_or("item id overflow")?591 != token_id592 {593 return Err("item id should be next".into());594 }595596 let mut properties = CollectionPropertiesVec::default();597 properties598 .try_push(Property {599 key,600 value: token_uri601 .into_bytes()602 .try_into()603 .map_err(|_| "token uri is too long")?,604 })605 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;606607 <Pallet<T>>::create_item(608 self,609 &caller,610 CreateItemData::<T> {611 properties,612 owner: to,613 },614 &budget,615 )616 .map_err(dispatch_to_evm::<T>)?;617 Ok(true)618 }619620 /// @dev Not implemented621 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {622 Err("not implementable".into())623 }624}625626fn get_token_property<T: Config>(627 collection: &CollectionHandle<T>,628 token_id: u32,629 key: &up_data_structs::PropertyKey,630) -> Result<string> {631 collection.consume_store_reads(1)?;632 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))633 .map_err(|_| Error::Revert("Token properties not found".into()))?;634 if let Some(property) = properties.get(key) {635 return Ok(string::from_utf8_lossy(property).into());636 }637638 Err("Property tokenURI not found".into())639}640641fn get_token_permission<T: Config>(642 collection_id: CollectionId,643 key: &PropertyKey,644) -> Result<PropertyPermission> {645 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)646 .map_err(|_| Error::Revert("No permissions for collection".into()))?;647 let a = token_property_permissions648 .get(key)649 .map(Clone::clone)650 .ok_or_else(|| {651 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();652 Error::Revert(alloc::format!("No permission for key {}", key))653 })?;654 Ok(a)655}656657/// @title Unique extensions for ERC721.658#[solidity_interface(name = ERC721UniqueExtensions)]659impl<T: Config> NonfungibleHandle<T>660where661 T::AccountId: From<[u8; 32]>,662{663 /// @notice A descriptive name for a collection of NFTs in this contract664 fn name(&self) -> Result<string> {665 Ok(decode_utf16(self.name.iter().copied())666 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))667 .collect::<string>())668 }669670 /// @notice An abbreviated name for NFTs in this contract671 fn symbol(&self) -> Result<string> {672 Ok(string::from_utf8_lossy(&self.token_prefix).into())673 }674675 /// @notice Set or reaffirm the approved address for an NFT676 /// @dev The zero address indicates there is no approved address.677 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized678 /// operator of the current owner.679 /// @param approved The new substrate address approved NFT controller680 /// @param tokenId The NFT to approve681 #[weight(<SelfWeightOf<T>>::approve())]682 fn approve_cross(683 &mut self,684 caller: caller,685 approved: EthCrossAccount,686 token_id: uint256,687 ) -> Result<void> {688 let caller = T::CrossAccountId::from_eth(caller);689 let approved = approved.into_sub_cross_account::<T>()?;690 let token = token_id.try_into()?;691692 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))693 .map_err(dispatch_to_evm::<T>)?;694 Ok(())695 }696697 /// @notice Transfer ownership of an NFT698 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`699 /// is the zero address. Throws if `tokenId` is not a valid NFT.700 /// @param to The new owner701 /// @param tokenId The NFT to transfer702 #[weight(<SelfWeightOf<T>>::transfer())]703 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {704 let caller = T::CrossAccountId::from_eth(caller);705 let to = T::CrossAccountId::from_eth(to);706 let token = token_id.try_into()?;707 let budget = self708 .recorder709 .weight_calls_budget(<StructureWeight<T>>::find_parent());710711 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;712 Ok(())713 }714715 /// @notice Transfer ownership of an NFT from cross account address to cross account address716 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`717 /// is the zero address. Throws if `tokenId` is not a valid NFT.718 /// @param from Cross acccount address of current owner719 /// @param to Cross acccount address of new owner720 /// @param tokenId The NFT to transfer721 #[weight(<SelfWeightOf<T>>::transfer())]722 fn transfer_from_cross(723 &mut self,724 caller: caller,725 from: EthCrossAccount,726 to: EthCrossAccount,727 token_id: uint256,728 ) -> Result<void> {729 let caller = T::CrossAccountId::from_eth(caller);730 let from = from.into_sub_cross_account::<T>()?;731 let to = to.into_sub_cross_account::<T>()?;732 let token_id = token_id.try_into()?;733 let budget = self734 .recorder735 .weight_calls_budget(<StructureWeight<T>>::find_parent());736 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)737 .map_err(dispatch_to_evm::<T>)?;738 Ok(())739 }740741 /// @notice Burns a specific ERC721 token.742 /// @dev Throws unless `msg.sender` is the current owner or an authorized743 /// operator for this NFT. Throws if `from` is not the current owner. Throws744 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.745 /// @param from The current owner of the NFT746 /// @param tokenId The NFT to transfer747 #[weight(<SelfWeightOf<T>>::burn_from())]748 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {749 let caller = T::CrossAccountId::from_eth(caller);750 let from = T::CrossAccountId::from_eth(from);751 let token = token_id.try_into()?;752 let budget = self753 .recorder754 .weight_calls_budget(<StructureWeight<T>>::find_parent());755756 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)757 .map_err(dispatch_to_evm::<T>)?;758 Ok(())759 }760761 /// @notice Burns a specific ERC721 token.762 /// @dev Throws unless `msg.sender` is the current owner or an authorized763 /// operator for this NFT. Throws if `from` is not the current owner. Throws764 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.765 /// @param from The current owner of the NFT766 /// @param tokenId The NFT to transfer767 #[weight(<SelfWeightOf<T>>::burn_from())]768 fn burn_from_cross(769 &mut self,770 caller: caller,771 from: EthCrossAccount,772 token_id: uint256,773 ) -> Result<void> {774 let caller = T::CrossAccountId::from_eth(caller);775 let from = from.into_sub_cross_account::<T>()?;776 let token = token_id.try_into()?;777 let budget = self778 .recorder779 .weight_calls_budget(<StructureWeight<T>>::find_parent());780781 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)782 .map_err(dispatch_to_evm::<T>)?;783 Ok(())784 }785786 /// @notice Returns next free NFT ID.787 fn next_token_id(&self) -> Result<uint256> {788 self.consume_store_reads(1)?;789 Ok(<TokensMinted<T>>::get(self.id)790 .checked_add(1)791 .ok_or("item id overflow")?792 .into())793 }794795 /// @notice Function to mint multiple tokens.796 /// @dev `tokenIds` should be an array of consecutive numbers and first number797 /// should be obtained with `nextTokenId` method798 /// @param to The new owner799 /// @param tokenIds IDs of the minted NFTs800 #[solidity(hide)]801 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]802 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {803 let caller = T::CrossAccountId::from_eth(caller);804 let to = T::CrossAccountId::from_eth(to);805 let mut expected_index = <TokensMinted<T>>::get(self.id)806 .checked_add(1)807 .ok_or("item id overflow")?;808 let budget = self809 .recorder810 .weight_calls_budget(<StructureWeight<T>>::find_parent());811812 let total_tokens = token_ids.len();813 for id in token_ids.into_iter() {814 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;815 if id != expected_index {816 return Err("item id should be next".into());817 }818 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;819 }820 let data = (0..total_tokens)821 .map(|_| CreateItemData::<T> {822 properties: BoundedVec::default(),823 owner: to.clone(),824 })825 .collect();826827 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)828 .map_err(dispatch_to_evm::<T>)?;829 Ok(true)830 }831832 /// @notice Function to mint multiple tokens with the given tokenUris.833 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive834 /// numbers and first number should be obtained with `nextTokenId` method835 /// @param to The new owner836 /// @param tokens array of pairs of token ID and token URI for minted tokens837 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]838 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]839 fn mint_bulk_with_token_uri(840 &mut self,841 caller: caller,842 to: address,843 tokens: Vec<(uint256, string)>,844 ) -> Result<bool> {845 let key = key::url();846 let caller = T::CrossAccountId::from_eth(caller);847 let to = T::CrossAccountId::from_eth(to);848 let mut expected_index = <TokensMinted<T>>::get(self.id)849 .checked_add(1)850 .ok_or("item id overflow")?;851 let budget = self852 .recorder853 .weight_calls_budget(<StructureWeight<T>>::find_parent());854855 let mut data = Vec::with_capacity(tokens.len());856 for (id, token_uri) in tokens {857 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;858 if id != expected_index {859 return Err("item id should be next".into());860 }861 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;862863 let mut properties = CollectionPropertiesVec::default();864 properties865 .try_push(Property {866 key: key.clone(),867 value: token_uri868 .into_bytes()869 .try_into()870 .map_err(|_| "token uri is too long")?,871 })872 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;873874 data.push(CreateItemData::<T> {875 properties,876 owner: to.clone(),877 });878 }879880 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)881 .map_err(dispatch_to_evm::<T>)?;882 Ok(true)883 }884}885886#[solidity_interface(887 name = UniqueNFT,888 is(889 ERC721,890 ERC721Enumerable,891 ERC721UniqueExtensions,892 ERC721UniqueMintable,893 ERC721Burnable,894 ERC721Metadata(if(this.flags.erc721metadata)),895 Collection(via(common_mut returns CollectionHandle<T>)),896 TokenProperties,897 )898)]899impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}900901// Not a tests, but code generators902generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);903generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);904905impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>906where907 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,908{909 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");910911 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {912 call::<T, UniqueNFTCall<T>, _, _>(handle, self)913 }914}pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -25,15 +25,7 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{
- ToLog,
- execution::*,
- generate_stubgen, solidity, solidity_interface,
- types::*,
- weight,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use frame_support::{BoundedBTreeMap, BoundedVec};
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions,
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -29,15 +29,7 @@
convert::TryInto,
ops::Deref,
};
-use evm_coder::{
- ToLog,
- execution::*,
- generate_stubgen, solidity_interface,
- types::*,
- weight,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -18,13 +18,7 @@
use core::marker::PhantomData;
use ethereum as _;
-use evm_coder::{
- execution::*,
- generate_stubgen, solidity, solidity_interface,
- types::*,
- custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
- make_signature, weight,
-};
+use evm_coder::{execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use frame_support::traits::Get;
use crate::Pallet;