difftreelog
feat Add custum signature with unlimited nesting.
in: master
17 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
@@ -21,7 +21,7 @@
// https://doc.rust-lang.org/reference/procedural-macros.html
use proc_macro2::{TokenStream, Group};
-use quote::{quote, ToTokens};
+use quote::{quote, ToTokens, format_ident};
use inflector::cases;
use std::fmt::Write;
use syn::{
@@ -725,25 +725,20 @@
}
}
- fn expand_selector(&self) -> proc_macro2::TokenStream {
- let custom_signature = self.expand_custom_signature();
- quote! {
- {
- let a = ::evm_coder::sha3_const::Keccak256::new()
- .update(#custom_signature.as_bytes())
- .finalize();
- [a[0], a[1], a[2], a[3]]
- }
- }
- }
-
fn expand_const(&self) -> proc_macro2::TokenStream {
let screaming_name = &self.screaming_name;
+ let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);
let selector_str = &self.selector_str;
- let selector = &self.expand_selector();
+ let custom_signature = self.expand_custom_signature();
quote! {
+ const #screaming_name_signature: ::evm_coder::custom_signature::FunctionSignature = #custom_signature;
#[doc = #selector_str]
- const #screaming_name: ::evm_coder::types::bytes4 = #selector;
+ const #screaming_name: ::evm_coder::types::bytes4 = {
+ let a = ::evm_coder::sha3_const::Keccak256::new()
+ .update_with_size(&Self::#screaming_name_signature.signature, Self::#screaming_name_signature.signature_len)
+ .finalize();
+ [a[0], a[1], a[2], a[3]]
+ };
}
}
@@ -847,9 +842,8 @@
}
fn expand_custom_signature(&self) -> proc_macro2::TokenStream {
- let mut first_comma = true;
let mut custom_signature = TokenStream::new();
- let mut template = self.camel_name.clone() + "(";
+
self.args
.iter()
.filter_map(|a| {
@@ -863,39 +857,18 @@
}
})
.for_each(|ident| {
- if !first_comma {
- custom_signature.extend(quote!(,));
- template.push(',');
- } else {
- first_comma = false;
- };
- template.push_str("{}");
- let ident_str = ident.to_string();
- match ident_str.as_str() {
- "address" | "uint8" | "uint16" | "uint32" | "uint64" | "uint128"
- | "uint256" | "bytes4" | "topic" | "string" | "bytes" | "void" | "caller"
- | "bool" | "" => {
- custom_signature.extend(quote!(#ident_str));
- }
- _ => {
- custom_signature.extend(quote! {
- #ident::SIGNATURE_STRING
- });
- }
- }
+ custom_signature.extend(quote! {
+ (<#ident>::SIGNATURE, <#ident>::SIGNATURE_LEN)
+ });
});
- template.push(')');
- let mut template = quote!(#template);
- template.extend(quote!(,));
- template.extend(custom_signature);
- let custom_signature_group = Group::new(proc_macro2::Delimiter::Parenthesis, template);
- let mut custom_signature = quote! {
- ::evm_coder::const_format::formatcp!
- };
- custom_signature.extend(custom_signature_group.to_token_stream());
+ let func_name = self.camel_name.clone();
+ let func_name = quote!(FunctionName::new(#func_name));
+ custom_signature =
+ quote!({ ::evm_coder::make_signature!(new fn(& #func_name),#custom_signature) });
+
+ // println!("!!!!! {}", custom_signature);
- println!("!!!!! {}", custom_signature);
custom_signature
}
@@ -915,16 +888,23 @@
.map(MethodArg::expand_solidity_argument);
let docs = &self.docs;
let selector_str = &self.selector_str;
- let selector = &self.expand_selector();
+ 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
+ }
+ );
+ // println!("!!!!! {}", custom_signature);
let is_payable = self.has_value_args;
- quote! {
+ let out = quote! {
SolidityFunction {
docs: &[#(#docs),*],
selector_str: #selector_str,
hide: #hide,
- selector: u32::from_be_bytes(#selector),
+ selector: u32::from_be_bytes(Self::#screaming_name),
custom_signature: #custom_signature,
name: #camel_name,
mutability: #mutability,
@@ -936,7 +916,9 @@
),
result: <UnnamedArgument<#result>>::default(),
}
- }
+ };
+ // println!("@@@ {}", out);
+ out
}
}
crates/evm-coder/src/custom_signature.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/custom_signature.rs
@@ -0,0 +1,336 @@
+use core::str::from_utf8;
+
+pub const SIGNATURE_SIZE_LIMIT: usize = 256;
+
+pub trait Name {
+ const SIGNATURE: [u8; SIGNATURE_SIZE_LIMIT];
+ const SIGNATURE_LEN: usize;
+
+ fn name() -> &'static str {
+ from_utf8(&Self::SIGNATURE[..Self::SIGNATURE_LEN]).expect("bad utf-8")
+ }
+}
+
+#[derive(Debug)]
+pub struct FunctionSignature {
+ pub signature: [u8; SIGNATURE_SIZE_LIMIT],
+ pub signature_len: usize,
+}
+
+impl FunctionSignature {
+ pub const fn new(name: &'static FunctionName) -> FunctionSignature {
+ let mut signature = [0_u8; SIGNATURE_SIZE_LIMIT];
+ let name_len = name.signature_len;
+ let name = name.signature;
+ let mut dst_offset = 0;
+ let bracket_open = {
+ let mut b = [0_u8; SIGNATURE_SIZE_LIMIT];
+ b[0] = b"("[0];
+ b
+ };
+ crate::make_signature!(@copy(name, signature, name_len, dst_offset));
+ crate::make_signature!(@copy(bracket_open, signature, 1, dst_offset));
+ FunctionSignature {
+ signature,
+ signature_len: dst_offset,
+ }
+ }
+
+ pub const fn add_param(
+ signature: FunctionSignature,
+ param: ([u8; SIGNATURE_SIZE_LIMIT], usize),
+ ) -> FunctionSignature {
+ let mut dst = signature.signature;
+ let mut dst_offset = signature.signature_len;
+ let (param_name, param_len) = param;
+ let comma = {
+ let mut b = [0_u8; SIGNATURE_SIZE_LIMIT];
+ b[0] = b","[0];
+ b
+ };
+ FunctionSignature {
+ signature: {
+ crate::make_signature!(@copy(param_name, dst, param_len, dst_offset));
+ crate::make_signature!(@copy(comma, dst, 1, dst_offset));
+ dst
+ },
+ signature_len: dst_offset,
+ }
+ }
+
+ pub const fn done(signature: FunctionSignature, owerride: bool) -> FunctionSignature {
+ let mut dst = signature.signature;
+ let mut dst_offset = signature.signature_len - if owerride { 1 } else { 0 };
+ let bracket_close = {
+ let mut b = [0_u8; SIGNATURE_SIZE_LIMIT];
+ b[0] = b")"[0];
+ b
+ };
+ FunctionSignature {
+ signature: {
+ crate::make_signature!(@copy(bracket_close, dst, 1, dst_offset));
+ dst
+ },
+ signature_len: dst_offset,
+ }
+ }
+
+ // fn as_str(&self) -> &'static str {
+ // from_utf8(&self.signature[..self.signature_len]).expect("bad utf-8")
+ // }
+}
+
+#[derive(Debug)]
+pub struct FunctionName {
+ signature: [u8; SIGNATURE_SIZE_LIMIT],
+ signature_len: usize,
+}
+
+impl FunctionName {
+ pub const fn new(name: &'static str) -> FunctionName {
+ let mut signature = [0_u8; SIGNATURE_SIZE_LIMIT];
+ let name = name.as_bytes();
+ let name_len = name.len();
+ let mut dst_offset = 0;
+ crate::make_signature!(@copy(name, signature, name_len, dst_offset));
+ FunctionName {
+ signature,
+ signature_len: name_len,
+ }
+ }
+}
+
+#[macro_export]
+#[allow(missing_docs)]
+macro_rules! make_signature { // May be "define_signature"?
+ (new fn($func:expr)$(,)+) => {
+ {
+ let fs = FunctionSignature::new(& $func);
+ let fs = FunctionSignature::done(fs, false);
+ fs
+ }
+ };
+ (new fn($func:expr), $($tt:tt)*) => {
+ {
+ let fs = FunctionSignature::new(& $func);
+ let fs = make_signature!(@param; fs, $($tt),*);
+ fs
+ }
+ };
+
+ (@param; $func:expr) => {
+ FunctionSignature::done($func, true)
+ };
+ (@param; $func:expr, $param:expr) => {
+ make_signature!(@param; FunctionSignature::add_param($func, $param))
+ };
+ (@param; $func:expr, $param:expr, $($tt:tt),*) => {
+ make_signature!(@param; FunctionSignature::add_param($func, $param), $($tt),*)
+ };
+
+ (new $($tt:tt)*) => {
+ const SIGNATURE: [u8; SIGNATURE_SIZE_LIMIT] = {
+ let mut out = [0u8; SIGNATURE_SIZE_LIMIT];
+ let mut dst_offset = 0;
+ make_signature!(@data(out, dst_offset); $($tt)*);
+ out
+ };
+ const SIGNATURE_LEN: usize = 0 + make_signature!(@size; $($tt)*);
+ };
+
+ // (@bytes)
+
+ (@size;) => {
+ 0
+ };
+ (@size; fixed($expr:expr) $($tt:tt)*) => {
+ $expr.len() + make_signature!(@size; $($tt)*)
+ };
+ (@size; nameof($expr:ty) $($tt:tt)*) => {
+ <$expr>::SIGNATURE_LEN + make_signature!(@size; $($tt)*)
+ };
+
+ (@data($dst:ident, $dst_offset:ident);) => {};
+ (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
+ {
+ let data = $expr.as_bytes();
+ let data_len = data.len();
+ make_signature!(@copy(data, $dst, data_len, $dst_offset));
+ }
+ make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+ (@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {
+ {
+ let data = &<$expr>::SIGNATURE;
+ let data_len = <$expr>::SIGNATURE_LEN;
+ make_signature!(@copy(data, $dst, data_len, $dst_offset));
+ }
+ make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+
+ (@copy($src:ident, $dst:ident, $src_len:expr, $dst_offset:ident)) => {
+ {
+ let mut src_offset = 0;
+ let src_len: usize = $src_len;
+ while src_offset < src_len {
+ $dst[$dst_offset] = $src[src_offset];
+ $dst_offset += 1;
+ src_offset += 1;
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use core::str::from_utf8;
+
+ use frame_support::sp_runtime::app_crypto::sp_core::hexdisplay::AsBytesRef;
+
+ use super::{Name, SIGNATURE_SIZE_LIMIT, FunctionName, FunctionSignature};
+
+ impl Name for u8 {
+ make_signature!(new fixed("uint8"));
+ }
+ impl Name for u32 {
+ make_signature!(new fixed("uint32"));
+ }
+ impl<T: Name> Name for Vec<T> {
+ make_signature!(new nameof(T) fixed("[]"));
+ }
+ impl<A: Name, B: Name> Name for (A, B) {
+ make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
+ }
+
+ struct MaxSize();
+ impl Name for MaxSize {
+ const SIGNATURE: [u8; SIGNATURE_SIZE_LIMIT] = [b'!'; SIGNATURE_SIZE_LIMIT];
+ const SIGNATURE_LEN: usize = SIGNATURE_SIZE_LIMIT;
+ }
+
+ #[test]
+ fn simple() {
+ assert_eq!(u8::name(), "uint8");
+ assert_eq!(u32::name(), "uint32");
+ }
+
+ #[test]
+ fn vector_of_simple() {
+ assert_eq!(<Vec<u8>>::name(), "uint8[]");
+ assert_eq!(<Vec<u32>>::name(), "uint32[]");
+ }
+
+ #[test]
+ fn vector_of_vector() {
+ assert_eq!(<Vec<Vec<u8>>>::name(), "uint8[][]");
+ }
+
+ #[test]
+ fn tuple_of_simple() {
+ assert_eq!(<(u32, u8)>::name(), "(uint32,uint8)");
+ }
+
+ #[test]
+ fn tuple_of_tuple() {
+ assert_eq!(
+ <((u32, u8), (u8, u32))>::name(),
+ "((uint32,uint8),(uint8,uint32))"
+ );
+ }
+
+ #[test]
+ fn vector_of_tuple() {
+ assert_eq!(<Vec<(u32, u8)>>::name(), "(uint32,uint8)[]");
+ }
+
+ #[test]
+ fn tuple_of_vector() {
+ assert_eq!(<(Vec<u32>, u8)>::name(), "(uint32[],uint8)");
+ }
+
+ #[test]
+ fn complex() {
+ assert_eq!(
+ <(Vec<u32>, (u32, Vec<u8>))>::name(),
+ "(uint32[],(uint32,uint8[]))"
+ );
+ }
+
+ #[test]
+ fn max_size() {
+ assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));
+ }
+
+ // This test must NOT compile!
+ // #[test]
+ // fn over_max_size() {
+ // assert_eq!(<Vec<MaxSize>>::name(), "!".repeat(SIZE_LIMIT) + "[]");
+ // }
+
+ #[test]
+ fn make_func_without_args() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ );
+ let name = from_utf8(&SIG.signature[..SIG.signature_len]).unwrap();
+ assert_eq!(name, "some_funk()");
+ }
+
+ #[test]
+ fn make_func_with_1_args() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ (u8::SIGNATURE, u8::SIGNATURE_LEN)
+ );
+ let name = from_utf8(&SIG.signature[..SIG.signature_len]).unwrap();
+ assert_eq!(name, "some_funk(uint8)");
+ }
+
+ #[test]
+ fn make_func_with_2_args() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ (u8::SIGNATURE, u8::SIGNATURE_LEN)
+ (<Vec<u32>>::SIGNATURE, <Vec<u32>>::SIGNATURE_LEN)
+ );
+ let name = from_utf8(&SIG.signature[..SIG.signature_len]).unwrap();
+ assert_eq!(name, "some_funk(uint8,uint32[])");
+ }
+
+ #[test]
+ fn make_func_with_3_args() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ (u8::SIGNATURE, u8::SIGNATURE_LEN)
+ (u32::SIGNATURE, u32::SIGNATURE_LEN)
+ (<Vec<u32>>::SIGNATURE, <Vec<u32>>::SIGNATURE_LEN)
+ );
+ let name = from_utf8(&SIG.signature[..SIG.signature_len]).unwrap();
+ assert_eq!(name, "some_funk(uint8,uint32,uint32[])");
+ }
+
+ #[test]
+ fn make_slice_from_signature() {
+ const SOME_FUNK_NAME: FunctionName = FunctionName::new("some_funk");
+ const SIG: FunctionSignature = make_signature!(
+ new fn(&SOME_FUNK_NAME),
+ (u8::SIGNATURE, u8::SIGNATURE_LEN)
+ (u32::SIGNATURE, u32::SIGNATURE_LEN)
+ (<Vec<u32>>::SIGNATURE, <Vec<u32>>::SIGNATURE_LEN)
+ );
+ const NAME: [u8; SIG.signature_len] = {
+ let mut name: [u8; SIG.signature_len] = [0; SIG.signature_len];
+ let mut i = 0;
+ while i < SIG.signature_len {
+ name[i] = SIG.signature[i];
+ i += 1;
+ }
+ name
+ };
+ assert_eq!(&NAME, b"some_funk(uint8,uint32,uint32[])");
+ }
+}
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -15,7 +15,9 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
#![doc = include_str!("../README.md")]
-#![deny(missing_docs)]
+// #![deny(missing_docs)]
+#![warn(missing_docs)]
+#![macro_use]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
extern crate alloc;
@@ -26,6 +28,8 @@
pub use events::{ToLog, ToTopic};
use execution::DispatchInfo;
pub mod execution;
+#[macro_use]
+pub mod custom_signature;
/// Derives call enum implementing [`crate::Callable`], [`crate::Weighted`]
/// and [`crate::Call`] from impl block.
@@ -118,27 +122,54 @@
use alloc::{vec::Vec};
use pallet_evm::account::CrossAccountId;
use primitive_types::{U256, H160, H256};
+ use core::str::from_utf8;
- pub type address = H160;
+ use crate::custom_signature::SIGNATURE_SIZE_LIMIT;
- pub type uint8 = u8;
- pub type uint16 = u16;
- pub type uint32 = u32;
- pub type uint64 = u64;
- pub type uint128 = u128;
- pub type uint256 = U256;
+ pub trait Signature {
+ const SIGNATURE: [u8; SIGNATURE_SIZE_LIMIT];
+ const SIGNATURE_LEN: usize;
- pub type bytes4 = [u8; 4];
+ fn as_str() -> &'static str {
+ from_utf8(&Self::SIGNATURE[..Self::SIGNATURE_LEN]).expect("bad utf-8")
+ }
+ }
- pub type topic = H256;
+ impl Signature for bool {
+ make_signature!(new fixed("bool"));
+ }
+ macro_rules! define_simple_type {
+ (type $ident:ident = $ty:ty) => {
+ pub type $ident = $ty;
+ impl Signature for $ty {
+ make_signature!(new fixed(stringify!($ident)));
+ }
+ };
+ }
+
+ define_simple_type!(type address = H160);
+
+ define_simple_type!(type uint8 = u8);
+ define_simple_type!(type uint16 = u16);
+ define_simple_type!(type uint32 = u32);
+ define_simple_type!(type uint64 = u64);
+ define_simple_type!(type uint128 = u128);
+ define_simple_type!(type uint256 = U256);
+ define_simple_type!(type bytes4 = [u8; 4]);
+
+ define_simple_type!(type topic = H256);
+
#[cfg(not(feature = "std"))]
- pub type string = ::alloc::string::String;
+ define_simple_type!(type string = ::alloc::string::String);
#[cfg(feature = "std")]
- pub type string = ::std::string::String;
+ define_simple_type!(type string = ::std::string::String);
#[derive(Default, Debug)]
pub struct bytes(pub Vec<u8>);
+ impl Signature for bytes {
+ make_signature!(new fixed("bytes"));
+ }
/// Solidity doesn't have `void` type, however we have special implementation
/// for empty tuple return type
@@ -230,12 +261,8 @@
}
}
- impl SignatureString for EthCrossAccount {
- const SIGNATURE_STRING: &'static str = "(address,uint256)";
- }
-
- pub trait SignatureString {
- const SIGNATURE_STRING: &'static str;
+ impl Signature for EthCrossAccount {
+ make_signature!(new fixed("(address,uint256)"));
}
/// Convert `CrossAccountId` to `uint256`.
crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -30,9 +30,10 @@
marker::PhantomData,
cell::{Cell, RefCell},
cmp::Reverse,
+ str::from_utf8,
};
use impl_trait_for_tuples::impl_for_tuples;
-use crate::types::*;
+use crate::{types::*, custom_signature::FunctionSignature};
#[derive(Default)]
pub struct TypeCollector {
@@ -487,7 +488,7 @@
pub selector_str: &'static str,
pub selector: u32,
pub hide: bool,
- pub custom_signature: &'static str,
+ pub custom_signature: FunctionSignature,
pub name: &'static str,
pub args: A,
pub result: R,
@@ -513,7 +514,8 @@
writeln!(
writer,
"\t{hide_comment}/// or in textual repr: {}",
- self.custom_signature
+ // from_utf8(self.custom_signature.as_str()).expect("bad utf8")
+ self.selector_str
)?;
write!(writer, "\t{hide_comment}function {}(", self.name)?;
self.args.solidity_name(writer, tc)?;
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -21,6 +21,8 @@
types::*,
execution::{Result, Error},
weight,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
};
pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};
use pallet_evm_coder_substrate::dispatch_to_evm;
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -20,7 +20,13 @@
use alloc::{format, string::ToString};
use core::marker::PhantomData;
use evm_coder::{
- abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
+ abi::AbiWriter,
+ execution::Result,
+ generate_stubgen, solidity_interface,
+ types::*,
+ ToLog,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
};
use pallet_evm::{
ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -20,7 +20,15 @@
use alloc::{format, string::ToString};
use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
use core::convert::TryInto;
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
+use evm_coder::{
+ ToLog,
+ execution::*,
+ generate_stubgen, solidity_interface,
+ types::*,
+ weight,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
+};
use pallet_common::eth::convert_tuple_to_cross_account;
use up_data_structs::CollectionMode;
use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
pallets/nonfungible/src/erc.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 alloc::{format, string::ToString};24use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27};28use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};29use frame_support::BoundedVec;30use up_data_structs::{31 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,32 CollectionPropertiesVec,33};34use pallet_evm_coder_substrate::dispatch_to_evm;35use sp_std::vec::Vec;36use pallet_common::{37 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},38 CollectionHandle, CollectionPropertyPermissions,39 eth::convert_tuple_to_cross_account,40};41use pallet_evm::{account::CrossAccountId, PrecompileHandle};42use pallet_evm_coder_substrate::call;43use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};4445use crate::{46 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,47 SelfWeightOf, weights::WeightInfo, TokenProperties,48};4950/// @title A contract that allows to set and delete token properties and change token property permissions.51#[solidity_interface(name = TokenProperties)]52impl<T: Config> NonfungibleHandle<T> {53 /// @notice Set permissions for token property.54 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.55 /// @param key Property key.56 /// @param isMutable Permission to mutate property.57 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.58 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.59 fn set_token_property_permission(60 &mut self,61 caller: caller,62 key: string,63 is_mutable: bool,64 collection_admin: bool,65 token_owner: bool,66 ) -> Result<()> {67 let caller = T::CrossAccountId::from_eth(caller);68 <Pallet<T>>::set_property_permission(69 self,70 &caller,71 PropertyKeyPermission {72 key: <Vec<u8>>::from(key)73 .try_into()74 .map_err(|_| "too long key")?,75 permission: PropertyPermission {76 mutable: is_mutable,77 collection_admin,78 token_owner,79 },80 },81 )82 .map_err(dispatch_to_evm::<T>)83 }8485 /// @notice Set token property value.86 /// @dev Throws error if `msg.sender` has no permission to edit the property.87 /// @param tokenId ID of the token.88 /// @param key Property key.89 /// @param value Property value.90 fn set_property(91 &mut self,92 caller: caller,93 token_id: uint256,94 key: string,95 value: bytes,96 ) -> Result<()> {97 let caller = T::CrossAccountId::from_eth(caller);98 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;99 let key = <Vec<u8>>::from(key)100 .try_into()101 .map_err(|_| "key too long")?;102 let value = value.0.try_into().map_err(|_| "value too long")?;103104 let nesting_budget = self105 .recorder106 .weight_calls_budget(<StructureWeight<T>>::find_parent());107108 <Pallet<T>>::set_token_property(109 self,110 &caller,111 TokenId(token_id),112 Property { key, value },113 &nesting_budget,114 )115 .map_err(dispatch_to_evm::<T>)116 }117118 /// @notice Set token properties value.119 /// @dev Throws error if `msg.sender` has no permission to edit the property.120 /// @param tokenId ID of the token.121 /// @param properties settable properties122 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]123 fn set_properties(124 &mut self,125 caller: caller,126 token_id: uint256,127 properties: Vec<(string, bytes)>,128 ) -> Result<()> {129 let caller = T::CrossAccountId::from_eth(caller);130 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;131132 let nesting_budget = self133 .recorder134 .weight_calls_budget(<StructureWeight<T>>::find_parent());135136 let properties = properties137 .into_iter()138 .map(|(key, value)| {139 let key = <Vec<u8>>::from(key)140 .try_into()141 .map_err(|_| "key too large")?;142143 let value = value.0.try_into().map_err(|_| "value too large")?;144145 Ok(Property { key, value })146 })147 .collect::<Result<Vec<_>>>()?;148149 <Pallet<T>>::set_token_properties(150 self,151 &caller,152 TokenId(token_id),153 properties.into_iter(),154 <Pallet<T>>::token_exists(&self, TokenId(token_id)),155 &nesting_budget,156 )157 .map_err(dispatch_to_evm::<T>)158 }159160 /// @notice Delete token property value.161 /// @dev Throws error if `msg.sender` has no permission to edit the property.162 /// @param tokenId ID of the token.163 /// @param key Property key.164 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {165 let caller = T::CrossAccountId::from_eth(caller);166 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;167 let key = <Vec<u8>>::from(key)168 .try_into()169 .map_err(|_| "key too long")?;170171 let nesting_budget = self172 .recorder173 .weight_calls_budget(<StructureWeight<T>>::find_parent());174175 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)176 .map_err(dispatch_to_evm::<T>)177 }178179 /// @notice Get token property value.180 /// @dev Throws error if key not found181 /// @param tokenId ID of the token.182 /// @param key Property key.183 /// @return Property value bytes184 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {185 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;186 let key = <Vec<u8>>::from(key)187 .try_into()188 .map_err(|_| "key too long")?;189190 let props = <TokenProperties<T>>::get((self.id, token_id));191 let prop = props.get(&key).ok_or("key not found")?;192193 Ok(prop.to_vec().into())194 }195}196197#[derive(ToLog)]198pub enum ERC721Events {199 /// @dev This emits when ownership of any NFT changes by any mechanism.200 /// This event emits when NFTs are created (`from` == 0) and destroyed201 /// (`to` == 0). Exception: during contract creation, any number of NFTs202 /// may be created and assigned without emitting Transfer. At the time of203 /// any transfer, the approved address for that NFT (if any) is reset to none.204 Transfer {205 #[indexed]206 from: address,207 #[indexed]208 to: address,209 #[indexed]210 token_id: uint256,211 },212 /// @dev This emits when the approved address for an NFT is changed or213 /// reaffirmed. The zero address indicates there is no approved address.214 /// When a Transfer event emits, this also indicates that the approved215 /// address for that NFT (if any) is reset to none.216 Approval {217 #[indexed]218 owner: address,219 #[indexed]220 approved: address,221 #[indexed]222 token_id: uint256,223 },224 /// @dev This emits when an operator is enabled or disabled for an owner.225 /// The operator can manage all NFTs of the owner.226 #[allow(dead_code)]227 ApprovalForAll {228 #[indexed]229 owner: address,230 #[indexed]231 operator: address,232 approved: bool,233 },234}235236#[derive(ToLog)]237pub enum ERC721UniqueMintableEvents {238 #[allow(dead_code)]239 MintingFinished {},240}241242/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension243/// @dev See https://eips.ethereum.org/EIPS/eip-721244#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]245impl<T: Config> NonfungibleHandle<T>246where247 T::AccountId: From<[u8; 32]>,248{249 /// @notice A descriptive name for a collection of NFTs in this contract250 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`251 #[solidity(hide, rename_selector = "name")]252 fn name_proxy(&self) -> Result<string> {253 self.name()254 }255256 /// @notice An abbreviated name for NFTs in this contract257 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`258 #[solidity(hide, rename_selector = "symbol")]259 fn symbol_proxy(&self) -> Result<string> {260 self.symbol()261 }262263 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.264 ///265 /// @dev If the token has a `url` property and it is not empty, it is returned.266 /// 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`.267 /// If the collection property `baseURI` is empty or absent, return "" (empty string)268 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix269 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).270 ///271 /// @return token's const_metadata272 #[solidity(rename_selector = "tokenURI")]273 fn token_uri(&self, token_id: uint256) -> Result<string> {274 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;275276 match get_token_property(self, token_id_u32, &key::url()).as_deref() {277 Err(_) | Ok("") => (),278 Ok(url) => {279 return Ok(url.into());280 }281 };282283 let base_uri =284 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())285 .map(BoundedVec::into_inner)286 .map(string::from_utf8)287 .transpose()288 .map_err(|e| {289 Error::Revert(alloc::format!(290 "Can not convert value \"baseURI\" to string with error \"{}\"",291 e292 ))293 })?;294295 let base_uri = match base_uri.as_deref() {296 None | Some("") => {297 return Ok("".into());298 }299 Some(base_uri) => base_uri.into(),300 };301302 Ok(303 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {304 Err(_) | Ok("") => base_uri,305 Ok(suffix) => base_uri + suffix,306 },307 )308 }309}310311/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension312/// @dev See https://eips.ethereum.org/EIPS/eip-721313#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]314impl<T: Config> NonfungibleHandle<T> {315 /// @notice Enumerate valid NFTs316 /// @param index A counter less than `totalSupply()`317 /// @return The token identifier for the `index`th NFT,318 /// (sort order not specified)319 fn token_by_index(&self, index: uint256) -> Result<uint256> {320 Ok(index)321 }322323 /// @dev Not implemented324 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {325 // TODO: Not implemetable326 Err("not implemented".into())327 }328329 /// @notice Count NFTs tracked by this contract330 /// @return A count of valid NFTs tracked by this contract, where each one of331 /// them has an assigned and queryable owner not equal to the zero address332 fn total_supply(&self) -> Result<uint256> {333 self.consume_store_reads(1)?;334 Ok(<Pallet<T>>::total_supply(self).into())335 }336}337338/// @title ERC-721 Non-Fungible Token Standard339/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md340#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]341impl<T: Config> NonfungibleHandle<T> {342 /// @notice Count all NFTs assigned to an owner343 /// @dev NFTs assigned to the zero address are considered invalid, and this344 /// function throws for queries about the zero address.345 /// @param owner An address for whom to query the balance346 /// @return The number of NFTs owned by `owner`, possibly zero347 fn balance_of(&self, owner: address) -> Result<uint256> {348 self.consume_store_reads(1)?;349 let owner = T::CrossAccountId::from_eth(owner);350 let balance = <AccountBalance<T>>::get((self.id, owner));351 Ok(balance.into())352 }353 /// @notice Find the owner of an NFT354 /// @dev NFTs assigned to zero address are considered invalid, and queries355 /// about them do throw.356 /// @param tokenId The identifier for an NFT357 /// @return The address of the owner of the NFT358 fn owner_of(&self, token_id: uint256) -> Result<address> {359 self.consume_store_reads(1)?;360 let token: TokenId = token_id.try_into()?;361 Ok(*<TokenData<T>>::get((self.id, token))362 .ok_or("token not found")?363 .owner364 .as_eth())365 }366 /// @dev Not implemented367 #[solidity(rename_selector = "safeTransferFrom")]368 fn safe_transfer_from_with_data(369 &mut self,370 _from: address,371 _to: address,372 _token_id: uint256,373 _data: bytes,374 ) -> Result<void> {375 // TODO: Not implemetable376 Err("not implemented".into())377 }378 /// @dev Not implemented379 fn safe_transfer_from(380 &mut self,381 _from: address,382 _to: address,383 _token_id: uint256,384 ) -> Result<void> {385 // TODO: Not implemetable386 Err("not implemented".into())387 }388389 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE390 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE391 /// THEY MAY BE PERMANENTLY LOST392 /// @dev Throws unless `msg.sender` is the current owner or an authorized393 /// operator for this NFT. Throws if `from` is not the current owner. Throws394 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.395 /// @param from The current owner of the NFT396 /// @param to The new owner397 /// @param tokenId The NFT to transfer398 #[weight(<SelfWeightOf<T>>::transfer_from())]399 fn transfer_from(400 &mut self,401 caller: caller,402 from: address,403 to: address,404 token_id: uint256,405 ) -> Result<void> {406 let caller = T::CrossAccountId::from_eth(caller);407 let from = T::CrossAccountId::from_eth(from);408 let to = T::CrossAccountId::from_eth(to);409 let token = token_id.try_into()?;410 let budget = self411 .recorder412 .weight_calls_budget(<StructureWeight<T>>::find_parent());413414 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)415 .map_err(dispatch_to_evm::<T>)?;416 Ok(())417 }418419 /// @notice Set or reaffirm the approved address for an NFT420 /// @dev The zero address indicates there is no approved address.421 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized422 /// operator of the current owner.423 /// @param approved The new approved NFT controller424 /// @param tokenId The NFT to approve425 #[weight(<SelfWeightOf<T>>::approve())]426 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {427 let caller = T::CrossAccountId::from_eth(caller);428 let approved = T::CrossAccountId::from_eth(approved);429 let token = token_id.try_into()?;430431 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))432 .map_err(dispatch_to_evm::<T>)?;433 Ok(())434 }435436 /// @dev Not implemented437 fn set_approval_for_all(438 &mut self,439 _caller: caller,440 _operator: address,441 _approved: bool,442 ) -> Result<void> {443 // TODO: Not implemetable444 Err("not implemented".into())445 }446447 /// @dev Not implemented448 fn get_approved(&self, _token_id: uint256) -> Result<address> {449 // TODO: Not implemetable450 Err("not implemented".into())451 }452453 /// @dev Not implemented454 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {455 // TODO: Not implemetable456 Err("not implemented".into())457 }458}459460/// @title ERC721 Token that can be irreversibly burned (destroyed).461#[solidity_interface(name = ERC721Burnable)]462impl<T: Config> NonfungibleHandle<T> {463 /// @notice Burns a specific ERC721 token.464 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized465 /// operator of the current owner.466 /// @param tokenId The NFT to approve467 #[weight(<SelfWeightOf<T>>::burn_item())]468 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {469 let caller = T::CrossAccountId::from_eth(caller);470 let token = token_id.try_into()?;471472 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;473 Ok(())474 }475}476477/// @title ERC721 minting logic.478#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]479impl<T: Config> NonfungibleHandle<T> {480 fn minting_finished(&self) -> Result<bool> {481 Ok(false)482 }483484 /// @notice Function to mint token.485 /// @param to The new owner486 /// @return uint256 The id of the newly minted token487 #[weight(<SelfWeightOf<T>>::create_item())]488 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {489 let token_id: uint256 = <TokensMinted<T>>::get(self.id)490 .checked_add(1)491 .ok_or("item id overflow")?492 .into();493 self.mint_check_id(caller, to, token_id)?;494 Ok(token_id)495 }496497 /// @notice Function to mint token.498 /// @dev `tokenId` should be obtained with `nextTokenId` method,499 /// unlike standard, you can't specify it manually500 /// @param to The new owner501 /// @param tokenId ID of the minted NFT502 #[solidity(hide, rename_selector = "mint")]503 #[weight(<SelfWeightOf<T>>::create_item())]504 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {505 let caller = T::CrossAccountId::from_eth(caller);506 let to = T::CrossAccountId::from_eth(to);507 let token_id: u32 = token_id.try_into()?;508 let budget = self509 .recorder510 .weight_calls_budget(<StructureWeight<T>>::find_parent());511512 if <TokensMinted<T>>::get(self.id)513 .checked_add(1)514 .ok_or("item id overflow")?515 != token_id516 {517 return Err("item id should be next".into());518 }519520 <Pallet<T>>::create_item(521 self,522 &caller,523 CreateItemData::<T> {524 properties: BoundedVec::default(),525 owner: to,526 },527 &budget,528 )529 .map_err(dispatch_to_evm::<T>)?;530531 Ok(true)532 }533534 /// @notice Function to mint token with the given tokenUri.535 /// @param to The new owner536 /// @param tokenUri Token URI that would be stored in the NFT properties537 /// @return uint256 The id of the newly minted token538 #[solidity(rename_selector = "mintWithTokenURI")]539 #[weight(<SelfWeightOf<T>>::create_item())]540 fn mint_with_token_uri(541 &mut self,542 caller: caller,543 to: address,544 token_uri: string,545 ) -> Result<uint256> {546 let token_id: uint256 = <TokensMinted<T>>::get(self.id)547 .checked_add(1)548 .ok_or("item id overflow")?549 .into();550 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;551 Ok(token_id)552 }553554 /// @notice Function to mint token with the given tokenUri.555 /// @dev `tokenId` should be obtained with `nextTokenId` method,556 /// unlike standard, you can't specify it manually557 /// @param to The new owner558 /// @param tokenId ID of the minted NFT559 /// @param tokenUri Token URI that would be stored in the NFT properties560 #[solidity(hide, rename_selector = "mintWithTokenURI")]561 #[weight(<SelfWeightOf<T>>::create_item())]562 fn mint_with_token_uri_check_id(563 &mut self,564 caller: caller,565 to: address,566 token_id: uint256,567 token_uri: string,568 ) -> Result<bool> {569 let key = key::url();570 let permission = get_token_permission::<T>(self.id, &key)?;571 if !permission.collection_admin {572 return Err("Operation is not allowed".into());573 }574575 let caller = T::CrossAccountId::from_eth(caller);576 let to = T::CrossAccountId::from_eth(to);577 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;578 let budget = self579 .recorder580 .weight_calls_budget(<StructureWeight<T>>::find_parent());581582 if <TokensMinted<T>>::get(self.id)583 .checked_add(1)584 .ok_or("item id overflow")?585 != token_id586 {587 return Err("item id should be next".into());588 }589590 let mut properties = CollectionPropertiesVec::default();591 properties592 .try_push(Property {593 key,594 value: token_uri595 .into_bytes()596 .try_into()597 .map_err(|_| "token uri is too long")?,598 })599 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;600601 <Pallet<T>>::create_item(602 self,603 &caller,604 CreateItemData::<T> {605 properties,606 owner: to,607 },608 &budget,609 )610 .map_err(dispatch_to_evm::<T>)?;611 Ok(true)612 }613614 /// @dev Not implemented615 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {616 Err("not implementable".into())617 }618}619620fn get_token_property<T: Config>(621 collection: &CollectionHandle<T>,622 token_id: u32,623 key: &up_data_structs::PropertyKey,624) -> Result<string> {625 collection.consume_store_reads(1)?;626 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))627 .map_err(|_| Error::Revert("Token properties not found".into()))?;628 if let Some(property) = properties.get(key) {629 return Ok(string::from_utf8_lossy(property).into());630 }631632 Err("Property tokenURI not found".into())633}634635fn get_token_permission<T: Config>(636 collection_id: CollectionId,637 key: &PropertyKey,638) -> Result<PropertyPermission> {639 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)640 .map_err(|_| Error::Revert("No permissions for collection".into()))?;641 let a = token_property_permissions642 .get(key)643 .map(Clone::clone)644 .ok_or_else(|| {645 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();646 Error::Revert(alloc::format!("No permission for key {}", key))647 })?;648 Ok(a)649}650651/// @title Unique extensions for ERC721.652#[solidity_interface(name = ERC721UniqueExtensions)]653impl<T: Config> NonfungibleHandle<T>654where655 T::AccountId: From<[u8; 32]>,656{657 /// @notice A descriptive name for a collection of NFTs in this contract658 fn name(&self) -> Result<string> {659 Ok(decode_utf16(self.name.iter().copied())660 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))661 .collect::<string>())662 }663664 /// @notice An abbreviated name for NFTs in this contract665 fn symbol(&self) -> Result<string> {666 Ok(string::from_utf8_lossy(&self.token_prefix).into())667 }668669 /// @notice Set or reaffirm the approved address for an NFT670 /// @dev The zero address indicates there is no approved address.671 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized672 /// operator of the current owner.673 /// @param approved The new substrate address approved NFT controller674 /// @param tokenId The NFT to approve675 #[weight(<SelfWeightOf<T>>::approve())]676 fn approve_cross(677 &mut self,678 caller: caller,679 approved: (address, uint256),680 token_id: uint256,681 ) -> Result<void> {682 let caller = T::CrossAccountId::from_eth(caller);683 let approved = convert_tuple_to_cross_account::<T>(approved)?;684 let token = token_id.try_into()?;685686 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))687 .map_err(dispatch_to_evm::<T>)?;688 Ok(())689 }690691 /// @notice Transfer ownership of an NFT692 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`693 /// is the zero address. Throws if `tokenId` is not a valid NFT.694 /// @param to The new owner695 /// @param tokenId The NFT to transfer696 #[weight(<SelfWeightOf<T>>::transfer())]697 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {698 let caller = T::CrossAccountId::from_eth(caller);699 let to = T::CrossAccountId::from_eth(to);700 let token = token_id.try_into()?;701 let budget = self702 .recorder703 .weight_calls_budget(<StructureWeight<T>>::find_parent());704705 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;706 Ok(())707 }708709 /// @notice Transfer ownership of an NFT from cross account address to cross account address710 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`711 /// is the zero address. Throws if `tokenId` is not a valid NFT.712 /// @param from Cross acccount address of current owner713 /// @param to Cross acccount address of new owner714 /// @param tokenId The NFT to transfer715 #[weight(<SelfWeightOf<T>>::transfer())]716 fn transfer_from_cross(717 &mut self,718 caller: caller,719 from: EthCrossAccount,720 to: EthCrossAccount,721 token_id: uint256,722 ) -> Result<void> {723 let caller = T::CrossAccountId::from_eth(caller);724 let from = from.into_sub_cross_account::<T>()?;725 let to = to.into_sub_cross_account::<T>()?;726 let token_id = token_id.try_into()?;727 let budget = self728 .recorder729 .weight_calls_budget(<StructureWeight<T>>::find_parent());730 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)731 .map_err(dispatch_to_evm::<T>)?;732 Ok(())733 }734735 /// @notice Burns a specific ERC721 token.736 /// @dev Throws unless `msg.sender` is the current owner or an authorized737 /// operator for this NFT. Throws if `from` is not the current owner. Throws738 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.739 /// @param from The current owner of the NFT740 /// @param tokenId The NFT to transfer741 #[weight(<SelfWeightOf<T>>::burn_from())]742 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {743 let caller = T::CrossAccountId::from_eth(caller);744 let from = T::CrossAccountId::from_eth(from);745 let token = token_id.try_into()?;746 let budget = self747 .recorder748 .weight_calls_budget(<StructureWeight<T>>::find_parent());749750 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)751 .map_err(dispatch_to_evm::<T>)?;752 Ok(())753 }754755 /// @notice Burns a specific ERC721 token.756 /// @dev Throws unless `msg.sender` is the current owner or an authorized757 /// operator for this NFT. Throws if `from` is not the current owner. Throws758 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.759 /// @param from The current owner of the NFT760 /// @param tokenId The NFT to transfer761 #[weight(<SelfWeightOf<T>>::burn_from())]762 fn burn_from_cross(763 &mut self,764 caller: caller,765 from: (address, uint256),766 token_id: uint256,767 ) -> Result<void> {768 let caller = T::CrossAccountId::from_eth(caller);769 let from = convert_tuple_to_cross_account::<T>(from)?;770 let token = token_id.try_into()?;771 let budget = self772 .recorder773 .weight_calls_budget(<StructureWeight<T>>::find_parent());774775 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)776 .map_err(dispatch_to_evm::<T>)?;777 Ok(())778 }779780 /// @notice Returns next free NFT ID.781 fn next_token_id(&self) -> Result<uint256> {782 self.consume_store_reads(1)?;783 Ok(<TokensMinted<T>>::get(self.id)784 .checked_add(1)785 .ok_or("item id overflow")?786 .into())787 }788789 /// @notice Function to mint multiple tokens.790 /// @dev `tokenIds` should be an array of consecutive numbers and first number791 /// should be obtained with `nextTokenId` method792 /// @param to The new owner793 /// @param tokenIds IDs of the minted NFTs794 #[solidity(hide)]795 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]796 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {797 let caller = T::CrossAccountId::from_eth(caller);798 let to = T::CrossAccountId::from_eth(to);799 let mut expected_index = <TokensMinted<T>>::get(self.id)800 .checked_add(1)801 .ok_or("item id overflow")?;802 let budget = self803 .recorder804 .weight_calls_budget(<StructureWeight<T>>::find_parent());805806 let total_tokens = token_ids.len();807 for id in token_ids.into_iter() {808 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;809 if id != expected_index {810 return Err("item id should be next".into());811 }812 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;813 }814 let data = (0..total_tokens)815 .map(|_| CreateItemData::<T> {816 properties: BoundedVec::default(),817 owner: to.clone(),818 })819 .collect();820821 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)822 .map_err(dispatch_to_evm::<T>)?;823 Ok(true)824 }825826 /// @notice Function to mint multiple tokens with the given tokenUris.827 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive828 /// numbers and first number should be obtained with `nextTokenId` method829 /// @param to The new owner830 /// @param tokens array of pairs of token ID and token URI for minted tokens831 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]832 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]833 fn mint_bulk_with_token_uri(834 &mut self,835 caller: caller,836 to: address,837 tokens: Vec<(uint256, string)>,838 ) -> Result<bool> {839 let key = key::url();840 let caller = T::CrossAccountId::from_eth(caller);841 let to = T::CrossAccountId::from_eth(to);842 let mut expected_index = <TokensMinted<T>>::get(self.id)843 .checked_add(1)844 .ok_or("item id overflow")?;845 let budget = self846 .recorder847 .weight_calls_budget(<StructureWeight<T>>::find_parent());848849 let mut data = Vec::with_capacity(tokens.len());850 for (id, token_uri) in tokens {851 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;852 if id != expected_index {853 return Err("item id should be next".into());854 }855 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;856857 let mut properties = CollectionPropertiesVec::default();858 properties859 .try_push(Property {860 key: key.clone(),861 value: token_uri862 .into_bytes()863 .try_into()864 .map_err(|_| "token uri is too long")?,865 })866 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;867868 data.push(CreateItemData::<T> {869 properties,870 owner: to.clone(),871 });872 }873874 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)875 .map_err(dispatch_to_evm::<T>)?;876 Ok(true)877 }878}879880#[solidity_interface(881 name = UniqueNFT,882 is(883 ERC721,884 ERC721Enumerable,885 ERC721UniqueExtensions,886 ERC721UniqueMintable,887 ERC721Burnable,888 ERC721Metadata(if(this.flags.erc721metadata)),889 Collection(via(common_mut returns CollectionHandle<T>)),890 TokenProperties,891 )892)]893impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}894895// Not a tests, but code generators896generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);897generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);898899impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>900where901 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,902{903 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");904905 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {906 call::<T, UniqueNFTCall<T>, _, _>(handle, self)907 }908}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # 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 alloc::{format, string::ToString};24use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27};28use evm_coder::{29 ToLog,30 execution::*,31 generate_stubgen, solidity, solidity_interface,32 types::*,33 weight,34 custom_signature::{FunctionName, FunctionSignature},35 make_signature,36};37use frame_support::BoundedVec;38use up_data_structs::{39 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,40 CollectionPropertiesVec,41};42use pallet_evm_coder_substrate::dispatch_to_evm;43use sp_std::vec::Vec;44use pallet_common::{45 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},46 CollectionHandle, CollectionPropertyPermissions,47 eth::convert_tuple_to_cross_account,48};49use pallet_evm::{account::CrossAccountId, PrecompileHandle};50use pallet_evm_coder_substrate::call;51use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};5253use crate::{54 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,55 SelfWeightOf, weights::WeightInfo, TokenProperties,56};5758/// @title A contract that allows to set and delete token properties and change token property permissions.59#[solidity_interface(name = TokenProperties)]60impl<T: Config> NonfungibleHandle<T> {61 /// @notice Set permissions for token property.62 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.63 /// @param key Property key.64 /// @param isMutable Permission to mutate property.65 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.66 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.67 fn set_token_property_permission(68 &mut self,69 caller: caller,70 key: string,71 is_mutable: bool,72 collection_admin: bool,73 token_owner: bool,74 ) -> Result<()> {75 let caller = T::CrossAccountId::from_eth(caller);76 <Pallet<T>>::set_property_permission(77 self,78 &caller,79 PropertyKeyPermission {80 key: <Vec<u8>>::from(key)81 .try_into()82 .map_err(|_| "too long key")?,83 permission: PropertyPermission {84 mutable: is_mutable,85 collection_admin,86 token_owner,87 },88 },89 )90 .map_err(dispatch_to_evm::<T>)91 }9293 /// @notice Set token property value.94 /// @dev Throws error if `msg.sender` has no permission to edit the property.95 /// @param tokenId ID of the token.96 /// @param key Property key.97 /// @param value Property value.98 fn set_property(99 &mut self,100 caller: caller,101 token_id: uint256,102 key: string,103 value: bytes,104 ) -> Result<()> {105 let caller = T::CrossAccountId::from_eth(caller);106 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;107 let key = <Vec<u8>>::from(key)108 .try_into()109 .map_err(|_| "key too long")?;110 let value = value.0.try_into().map_err(|_| "value too long")?;111112 let nesting_budget = self113 .recorder114 .weight_calls_budget(<StructureWeight<T>>::find_parent());115116 <Pallet<T>>::set_token_property(117 self,118 &caller,119 TokenId(token_id),120 Property { key, value },121 &nesting_budget,122 )123 .map_err(dispatch_to_evm::<T>)124 }125126 /// @notice Set token properties value.127 /// @dev Throws error if `msg.sender` has no permission to edit the property.128 /// @param tokenId ID of the token.129 /// @param properties settable properties130 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]131 fn set_properties(132 &mut self,133 caller: caller,134 token_id: uint256,135 properties: Vec<(string, bytes)>,136 ) -> Result<()> {137 let caller = T::CrossAccountId::from_eth(caller);138 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;139140 let nesting_budget = self141 .recorder142 .weight_calls_budget(<StructureWeight<T>>::find_parent());143144 let properties = properties145 .into_iter()146 .map(|(key, value)| {147 let key = <Vec<u8>>::from(key)148 .try_into()149 .map_err(|_| "key too large")?;150151 let value = value.0.try_into().map_err(|_| "value too large")?;152153 Ok(Property { key, value })154 })155 .collect::<Result<Vec<_>>>()?;156157 <Pallet<T>>::set_token_properties(158 self,159 &caller,160 TokenId(token_id),161 properties.into_iter(),162 <Pallet<T>>::token_exists(&self, TokenId(token_id)),163 &nesting_budget,164 )165 .map_err(dispatch_to_evm::<T>)166 }167168 /// @notice Delete token property value.169 /// @dev Throws error if `msg.sender` has no permission to edit the property.170 /// @param tokenId ID of the token.171 /// @param key Property key.172 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {173 let caller = T::CrossAccountId::from_eth(caller);174 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;175 let key = <Vec<u8>>::from(key)176 .try_into()177 .map_err(|_| "key too long")?;178179 let nesting_budget = self180 .recorder181 .weight_calls_budget(<StructureWeight<T>>::find_parent());182183 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)184 .map_err(dispatch_to_evm::<T>)185 }186187 /// @notice Get token property value.188 /// @dev Throws error if key not found189 /// @param tokenId ID of the token.190 /// @param key Property key.191 /// @return Property value bytes192 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {193 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;194 let key = <Vec<u8>>::from(key)195 .try_into()196 .map_err(|_| "key too long")?;197198 let props = <TokenProperties<T>>::get((self.id, token_id));199 let prop = props.get(&key).ok_or("key not found")?;200201 Ok(prop.to_vec().into())202 }203}204205#[derive(ToLog)]206pub enum ERC721Events {207 /// @dev This emits when ownership of any NFT changes by any mechanism.208 /// This event emits when NFTs are created (`from` == 0) and destroyed209 /// (`to` == 0). Exception: during contract creation, any number of NFTs210 /// may be created and assigned without emitting Transfer. At the time of211 /// any transfer, the approved address for that NFT (if any) is reset to none.212 Transfer {213 #[indexed]214 from: address,215 #[indexed]216 to: address,217 #[indexed]218 token_id: uint256,219 },220 /// @dev This emits when the approved address for an NFT is changed or221 /// reaffirmed. The zero address indicates there is no approved address.222 /// When a Transfer event emits, this also indicates that the approved223 /// address for that NFT (if any) is reset to none.224 Approval {225 #[indexed]226 owner: address,227 #[indexed]228 approved: address,229 #[indexed]230 token_id: uint256,231 },232 /// @dev This emits when an operator is enabled or disabled for an owner.233 /// The operator can manage all NFTs of the owner.234 #[allow(dead_code)]235 ApprovalForAll {236 #[indexed]237 owner: address,238 #[indexed]239 operator: address,240 approved: bool,241 },242}243244#[derive(ToLog)]245pub enum ERC721UniqueMintableEvents {246 #[allow(dead_code)]247 MintingFinished {},248}249250/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension251/// @dev See https://eips.ethereum.org/EIPS/eip-721252#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]253impl<T: Config> NonfungibleHandle<T>254where255 T::AccountId: From<[u8; 32]>,256{257 /// @notice A descriptive name for a collection of NFTs in this contract258 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`259 #[solidity(hide, rename_selector = "name")]260 fn name_proxy(&self) -> Result<string> {261 self.name()262 }263264 /// @notice An abbreviated name for NFTs in this contract265 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`266 #[solidity(hide, rename_selector = "symbol")]267 fn symbol_proxy(&self) -> Result<string> {268 self.symbol()269 }270271 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.272 ///273 /// @dev If the token has a `url` property and it is not empty, it is returned.274 /// 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`.275 /// If the collection property `baseURI` is empty or absent, return "" (empty string)276 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix277 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).278 ///279 /// @return token's const_metadata280 #[solidity(rename_selector = "tokenURI")]281 fn token_uri(&self, token_id: uint256) -> Result<string> {282 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;283284 match get_token_property(self, token_id_u32, &key::url()).as_deref() {285 Err(_) | Ok("") => (),286 Ok(url) => {287 return Ok(url.into());288 }289 };290291 let base_uri =292 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())293 .map(BoundedVec::into_inner)294 .map(string::from_utf8)295 .transpose()296 .map_err(|e| {297 Error::Revert(alloc::format!(298 "Can not convert value \"baseURI\" to string with error \"{}\"",299 e300 ))301 })?;302303 let base_uri = match base_uri.as_deref() {304 None | Some("") => {305 return Ok("".into());306 }307 Some(base_uri) => base_uri.into(),308 };309310 Ok(311 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {312 Err(_) | Ok("") => base_uri,313 Ok(suffix) => base_uri + suffix,314 },315 )316 }317}318319/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension320/// @dev See https://eips.ethereum.org/EIPS/eip-721321#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]322impl<T: Config> NonfungibleHandle<T> {323 /// @notice Enumerate valid NFTs324 /// @param index A counter less than `totalSupply()`325 /// @return The token identifier for the `index`th NFT,326 /// (sort order not specified)327 fn token_by_index(&self, index: uint256) -> Result<uint256> {328 Ok(index)329 }330331 /// @dev Not implemented332 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {333 // TODO: Not implemetable334 Err("not implemented".into())335 }336337 /// @notice Count NFTs tracked by this contract338 /// @return A count of valid NFTs tracked by this contract, where each one of339 /// them has an assigned and queryable owner not equal to the zero address340 fn total_supply(&self) -> Result<uint256> {341 self.consume_store_reads(1)?;342 Ok(<Pallet<T>>::total_supply(self).into())343 }344}345346/// @title ERC-721 Non-Fungible Token Standard347/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md348#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]349impl<T: Config> NonfungibleHandle<T> {350 /// @notice Count all NFTs assigned to an owner351 /// @dev NFTs assigned to the zero address are considered invalid, and this352 /// function throws for queries about the zero address.353 /// @param owner An address for whom to query the balance354 /// @return The number of NFTs owned by `owner`, possibly zero355 fn balance_of(&self, owner: address) -> Result<uint256> {356 self.consume_store_reads(1)?;357 let owner = T::CrossAccountId::from_eth(owner);358 let balance = <AccountBalance<T>>::get((self.id, owner));359 Ok(balance.into())360 }361 /// @notice Find the owner of an NFT362 /// @dev NFTs assigned to zero address are considered invalid, and queries363 /// about them do throw.364 /// @param tokenId The identifier for an NFT365 /// @return The address of the owner of the NFT366 fn owner_of(&self, token_id: uint256) -> Result<address> {367 self.consume_store_reads(1)?;368 let token: TokenId = token_id.try_into()?;369 Ok(*<TokenData<T>>::get((self.id, token))370 .ok_or("token not found")?371 .owner372 .as_eth())373 }374 /// @dev Not implemented375 #[solidity(rename_selector = "safeTransferFrom")]376 fn safe_transfer_from_with_data(377 &mut self,378 _from: address,379 _to: address,380 _token_id: uint256,381 _data: bytes,382 ) -> Result<void> {383 // TODO: Not implemetable384 Err("not implemented".into())385 }386 /// @dev Not implemented387 fn safe_transfer_from(388 &mut self,389 _from: address,390 _to: address,391 _token_id: uint256,392 ) -> Result<void> {393 // TODO: Not implemetable394 Err("not implemented".into())395 }396397 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE398 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE399 /// THEY MAY BE PERMANENTLY LOST400 /// @dev Throws unless `msg.sender` is the current owner or an authorized401 /// operator for this NFT. Throws if `from` is not the current owner. Throws402 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.403 /// @param from The current owner of the NFT404 /// @param to The new owner405 /// @param tokenId The NFT to transfer406 #[weight(<SelfWeightOf<T>>::transfer_from())]407 fn transfer_from(408 &mut self,409 caller: caller,410 from: address,411 to: address,412 token_id: uint256,413 ) -> Result<void> {414 let caller = T::CrossAccountId::from_eth(caller);415 let from = T::CrossAccountId::from_eth(from);416 let to = T::CrossAccountId::from_eth(to);417 let token = token_id.try_into()?;418 let budget = self419 .recorder420 .weight_calls_budget(<StructureWeight<T>>::find_parent());421422 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)423 .map_err(dispatch_to_evm::<T>)?;424 Ok(())425 }426427 /// @notice Set or reaffirm the approved address for an NFT428 /// @dev The zero address indicates there is no approved address.429 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized430 /// operator of the current owner.431 /// @param approved The new approved NFT controller432 /// @param tokenId The NFT to approve433 #[weight(<SelfWeightOf<T>>::approve())]434 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {435 let caller = T::CrossAccountId::from_eth(caller);436 let approved = T::CrossAccountId::from_eth(approved);437 let token = token_id.try_into()?;438439 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))440 .map_err(dispatch_to_evm::<T>)?;441 Ok(())442 }443444 /// @dev Not implemented445 fn set_approval_for_all(446 &mut self,447 _caller: caller,448 _operator: address,449 _approved: bool,450 ) -> Result<void> {451 // TODO: Not implemetable452 Err("not implemented".into())453 }454455 /// @dev Not implemented456 fn get_approved(&self, _token_id: uint256) -> Result<address> {457 // TODO: Not implemetable458 Err("not implemented".into())459 }460461 /// @dev Not implemented462 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {463 // TODO: Not implemetable464 Err("not implemented".into())465 }466}467468/// @title ERC721 Token that can be irreversibly burned (destroyed).469#[solidity_interface(name = ERC721Burnable)]470impl<T: Config> NonfungibleHandle<T> {471 /// @notice Burns a specific ERC721 token.472 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized473 /// operator of the current owner.474 /// @param tokenId The NFT to approve475 #[weight(<SelfWeightOf<T>>::burn_item())]476 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {477 let caller = T::CrossAccountId::from_eth(caller);478 let token = token_id.try_into()?;479480 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;481 Ok(())482 }483}484485/// @title ERC721 minting logic.486#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]487impl<T: Config> NonfungibleHandle<T> {488 fn minting_finished(&self) -> Result<bool> {489 Ok(false)490 }491492 /// @notice Function to mint token.493 /// @param to The new owner494 /// @return uint256 The id of the newly minted token495 #[weight(<SelfWeightOf<T>>::create_item())]496 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {497 let token_id: uint256 = <TokensMinted<T>>::get(self.id)498 .checked_add(1)499 .ok_or("item id overflow")?500 .into();501 self.mint_check_id(caller, to, token_id)?;502 Ok(token_id)503 }504505 /// @notice Function to mint token.506 /// @dev `tokenId` should be obtained with `nextTokenId` method,507 /// unlike standard, you can't specify it manually508 /// @param to The new owner509 /// @param tokenId ID of the minted NFT510 #[solidity(hide, rename_selector = "mint")]511 #[weight(<SelfWeightOf<T>>::create_item())]512 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {513 let caller = T::CrossAccountId::from_eth(caller);514 let to = T::CrossAccountId::from_eth(to);515 let token_id: u32 = token_id.try_into()?;516 let budget = self517 .recorder518 .weight_calls_budget(<StructureWeight<T>>::find_parent());519520 if <TokensMinted<T>>::get(self.id)521 .checked_add(1)522 .ok_or("item id overflow")?523 != token_id524 {525 return Err("item id should be next".into());526 }527528 <Pallet<T>>::create_item(529 self,530 &caller,531 CreateItemData::<T> {532 properties: BoundedVec::default(),533 owner: to,534 },535 &budget,536 )537 .map_err(dispatch_to_evm::<T>)?;538539 Ok(true)540 }541542 /// @notice Function to mint token with the given tokenUri.543 /// @param to The new owner544 /// @param tokenUri Token URI that would be stored in the NFT properties545 /// @return uint256 The id of the newly minted token546 #[solidity(rename_selector = "mintWithTokenURI")]547 #[weight(<SelfWeightOf<T>>::create_item())]548 fn mint_with_token_uri(549 &mut self,550 caller: caller,551 to: address,552 token_uri: string,553 ) -> Result<uint256> {554 let token_id: uint256 = <TokensMinted<T>>::get(self.id)555 .checked_add(1)556 .ok_or("item id overflow")?557 .into();558 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;559 Ok(token_id)560 }561562 /// @notice Function to mint token with the given tokenUri.563 /// @dev `tokenId` should be obtained with `nextTokenId` method,564 /// unlike standard, you can't specify it manually565 /// @param to The new owner566 /// @param tokenId ID of the minted NFT567 /// @param tokenUri Token URI that would be stored in the NFT properties568 #[solidity(hide, rename_selector = "mintWithTokenURI")]569 #[weight(<SelfWeightOf<T>>::create_item())]570 fn mint_with_token_uri_check_id(571 &mut self,572 caller: caller,573 to: address,574 token_id: uint256,575 token_uri: string,576 ) -> Result<bool> {577 let key = key::url();578 let permission = get_token_permission::<T>(self.id, &key)?;579 if !permission.collection_admin {580 return Err("Operation is not allowed".into());581 }582583 let caller = T::CrossAccountId::from_eth(caller);584 let to = T::CrossAccountId::from_eth(to);585 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;586 let budget = self587 .recorder588 .weight_calls_budget(<StructureWeight<T>>::find_parent());589590 if <TokensMinted<T>>::get(self.id)591 .checked_add(1)592 .ok_or("item id overflow")?593 != token_id594 {595 return Err("item id should be next".into());596 }597598 let mut properties = CollectionPropertiesVec::default();599 properties600 .try_push(Property {601 key,602 value: token_uri603 .into_bytes()604 .try_into()605 .map_err(|_| "token uri is too long")?,606 })607 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;608609 <Pallet<T>>::create_item(610 self,611 &caller,612 CreateItemData::<T> {613 properties,614 owner: to,615 },616 &budget,617 )618 .map_err(dispatch_to_evm::<T>)?;619 Ok(true)620 }621622 /// @dev Not implemented623 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {624 Err("not implementable".into())625 }626}627628fn get_token_property<T: Config>(629 collection: &CollectionHandle<T>,630 token_id: u32,631 key: &up_data_structs::PropertyKey,632) -> Result<string> {633 collection.consume_store_reads(1)?;634 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))635 .map_err(|_| Error::Revert("Token properties not found".into()))?;636 if let Some(property) = properties.get(key) {637 return Ok(string::from_utf8_lossy(property).into());638 }639640 Err("Property tokenURI not found".into())641}642643fn get_token_permission<T: Config>(644 collection_id: CollectionId,645 key: &PropertyKey,646) -> Result<PropertyPermission> {647 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)648 .map_err(|_| Error::Revert("No permissions for collection".into()))?;649 let a = token_property_permissions650 .get(key)651 .map(Clone::clone)652 .ok_or_else(|| {653 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();654 Error::Revert(alloc::format!("No permission for key {}", key))655 })?;656 Ok(a)657}658659/// @title Unique extensions for ERC721.660#[solidity_interface(name = ERC721UniqueExtensions)]661impl<T: Config> NonfungibleHandle<T>662where663 T::AccountId: From<[u8; 32]>,664{665 /// @notice A descriptive name for a collection of NFTs in this contract666 fn name(&self) -> Result<string> {667 Ok(decode_utf16(self.name.iter().copied())668 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))669 .collect::<string>())670 }671672 /// @notice An abbreviated name for NFTs in this contract673 fn symbol(&self) -> Result<string> {674 Ok(string::from_utf8_lossy(&self.token_prefix).into())675 }676677 /// @notice Set or reaffirm the approved address for an NFT678 /// @dev The zero address indicates there is no approved address.679 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized680 /// operator of the current owner.681 /// @param approved The new substrate address approved NFT controller682 /// @param tokenId The NFT to approve683 #[weight(<SelfWeightOf<T>>::approve())]684 fn approve_cross(685 &mut self,686 caller: caller,687 approved: (address, uint256),688 token_id: uint256,689 ) -> Result<void> {690 let caller = T::CrossAccountId::from_eth(caller);691 let approved = convert_tuple_to_cross_account::<T>(approved)?;692 let token = token_id.try_into()?;693694 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))695 .map_err(dispatch_to_evm::<T>)?;696 Ok(())697 }698699 /// @notice Transfer ownership of an NFT700 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`701 /// is the zero address. Throws if `tokenId` is not a valid NFT.702 /// @param to The new owner703 /// @param tokenId The NFT to transfer704 #[weight(<SelfWeightOf<T>>::transfer())]705 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {706 let caller = T::CrossAccountId::from_eth(caller);707 let to = T::CrossAccountId::from_eth(to);708 let token = token_id.try_into()?;709 let budget = self710 .recorder711 .weight_calls_budget(<StructureWeight<T>>::find_parent());712713 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;714 Ok(())715 }716717 /// @notice Transfer ownership of an NFT from cross account address to cross account address718 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`719 /// is the zero address. Throws if `tokenId` is not a valid NFT.720 /// @param from Cross acccount address of current owner721 /// @param to Cross acccount address of new owner722 /// @param tokenId The NFT to transfer723 #[weight(<SelfWeightOf<T>>::transfer())]724 fn transfer_from_cross(725 &mut self,726 caller: caller,727 from: EthCrossAccount,728 to: EthCrossAccount,729 token_id: uint256,730 ) -> Result<void> {731 let caller = T::CrossAccountId::from_eth(caller);732 let from = from.into_sub_cross_account::<T>()?;733 let to = to.into_sub_cross_account::<T>()?;734 let token_id = token_id.try_into()?;735 let budget = self736 .recorder737 .weight_calls_budget(<StructureWeight<T>>::find_parent());738 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)739 .map_err(dispatch_to_evm::<T>)?;740 Ok(())741 }742743 /// @notice Burns a specific ERC721 token.744 /// @dev Throws unless `msg.sender` is the current owner or an authorized745 /// operator for this NFT. Throws if `from` is not the current owner. Throws746 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.747 /// @param from The current owner of the NFT748 /// @param tokenId The NFT to transfer749 #[weight(<SelfWeightOf<T>>::burn_from())]750 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {751 let caller = T::CrossAccountId::from_eth(caller);752 let from = T::CrossAccountId::from_eth(from);753 let token = token_id.try_into()?;754 let budget = self755 .recorder756 .weight_calls_budget(<StructureWeight<T>>::find_parent());757758 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)759 .map_err(dispatch_to_evm::<T>)?;760 Ok(())761 }762763 /// @notice Burns a specific ERC721 token.764 /// @dev Throws unless `msg.sender` is the current owner or an authorized765 /// operator for this NFT. Throws if `from` is not the current owner. Throws766 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.767 /// @param from The current owner of the NFT768 /// @param tokenId The NFT to transfer769 #[weight(<SelfWeightOf<T>>::burn_from())]770 fn burn_from_cross(771 &mut self,772 caller: caller,773 from: (address, uint256),774 token_id: uint256,775 ) -> Result<void> {776 let caller = T::CrossAccountId::from_eth(caller);777 let from = convert_tuple_to_cross_account::<T>(from)?;778 let token = token_id.try_into()?;779 let budget = self780 .recorder781 .weight_calls_budget(<StructureWeight<T>>::find_parent());782783 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)784 .map_err(dispatch_to_evm::<T>)?;785 Ok(())786 }787788 /// @notice Returns next free NFT ID.789 fn next_token_id(&self) -> Result<uint256> {790 self.consume_store_reads(1)?;791 Ok(<TokensMinted<T>>::get(self.id)792 .checked_add(1)793 .ok_or("item id overflow")?794 .into())795 }796797 /// @notice Function to mint multiple tokens.798 /// @dev `tokenIds` should be an array of consecutive numbers and first number799 /// should be obtained with `nextTokenId` method800 /// @param to The new owner801 /// @param tokenIds IDs of the minted NFTs802 #[solidity(hide)]803 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]804 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {805 let caller = T::CrossAccountId::from_eth(caller);806 let to = T::CrossAccountId::from_eth(to);807 let mut expected_index = <TokensMinted<T>>::get(self.id)808 .checked_add(1)809 .ok_or("item id overflow")?;810 let budget = self811 .recorder812 .weight_calls_budget(<StructureWeight<T>>::find_parent());813814 let total_tokens = token_ids.len();815 for id in token_ids.into_iter() {816 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;817 if id != expected_index {818 return Err("item id should be next".into());819 }820 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;821 }822 let data = (0..total_tokens)823 .map(|_| CreateItemData::<T> {824 properties: BoundedVec::default(),825 owner: to.clone(),826 })827 .collect();828829 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)830 .map_err(dispatch_to_evm::<T>)?;831 Ok(true)832 }833834 /// @notice Function to mint multiple tokens with the given tokenUris.835 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive836 /// numbers and first number should be obtained with `nextTokenId` method837 /// @param to The new owner838 /// @param tokens array of pairs of token ID and token URI for minted tokens839 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]840 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]841 fn mint_bulk_with_token_uri(842 &mut self,843 caller: caller,844 to: address,845 tokens: Vec<(uint256, string)>,846 ) -> Result<bool> {847 let key = key::url();848 let caller = T::CrossAccountId::from_eth(caller);849 let to = T::CrossAccountId::from_eth(to);850 let mut expected_index = <TokensMinted<T>>::get(self.id)851 .checked_add(1)852 .ok_or("item id overflow")?;853 let budget = self854 .recorder855 .weight_calls_budget(<StructureWeight<T>>::find_parent());856857 let mut data = Vec::with_capacity(tokens.len());858 for (id, token_uri) in tokens {859 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;860 if id != expected_index {861 return Err("item id should be next".into());862 }863 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;864865 let mut properties = CollectionPropertiesVec::default();866 properties867 .try_push(Property {868 key: key.clone(),869 value: token_uri870 .into_bytes()871 .try_into()872 .map_err(|_| "token uri is too long")?,873 })874 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;875876 data.push(CreateItemData::<T> {877 properties,878 owner: to.clone(),879 });880 }881882 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)883 .map_err(dispatch_to_evm::<T>)?;884 Ok(true)885 }886}887888#[solidity_interface(889 name = UniqueNFT,890 is(891 ERC721,892 ERC721Enumerable,893 ERC721UniqueExtensions,894 ERC721UniqueMintable,895 ERC721Burnable,896 ERC721Metadata(if(this.flags.erc721metadata)),897 Collection(via(common_mut returns CollectionHandle<T>)),898 TokenProperties,899 )900)]901impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}902903// Not a tests, but code generators904generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);905generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);906907impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>908where909 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,910{911 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");912913 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {914 call::<T, UniqueNFTCall<T>, _, _>(handle, self)915 }916}pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -104,7 +104,11 @@
}
/// @title A contract that allows you to work with collections.
+<<<<<<< HEAD
/// @dev the ERC-165 identifier for this interface is 0xb3152af3
+=======
+/// @dev the ERC-165 identifier for this interface is 0x674be726
+>>>>>>> feat: Add custum signature with unlimited nesting.
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -198,7 +202,7 @@
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
///
/// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
- /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// @dev EVM selector for this function is: 0x403e96a7,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
function setCollectionSponsorCross(Tuple6 memory sponsor) public {
require(false, stub_error);
@@ -239,6 +243,7 @@
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
<<<<<<< HEAD
+<<<<<<< HEAD
function collectionSponsor() public view returns (Tuple6 memory) {
require(false, stub_error);
dummy;
@@ -249,6 +254,12 @@
dummy;
return Tuple19(0x0000000000000000000000000000000000000000, 0);
>>>>>>> feat: add `EthCrossAccount` type
+=======
+ function collectionSponsor() public view returns (Tuple8 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple8(0x0000000000000000000000000000000000000000, 0);
+>>>>>>> feat: Add custum signature with unlimited nesting.
}
/// Set limits for the collection.
@@ -297,7 +308,7 @@
/// Add collection admin.
/// @param newAdmin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x859aa7d6,
+ /// @dev EVM selector for this function is: 0x62e3c7c2,
/// or in textual repr: addCollectionAdminCross((address,uint256))
function addCollectionAdminCross(Tuple6 memory newAdmin) public {
require(false, stub_error);
@@ -307,7 +318,7 @@
/// Remove collection admin.
/// @param admin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x6c0cd173,
+ /// @dev EVM selector for this function is: 0x810d1503,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
function removeCollectionAdminCross(Tuple6 memory admin) public {
require(false, stub_error);
@@ -351,7 +362,7 @@
///
/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
/// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
+ /// @dev EVM selector for this function is: 0x112d4586,
/// or in textual repr: setCollectionNesting(bool,address[])
function setCollectionNesting(bool enable, address[] memory collections) public {
require(false, stub_error);
@@ -398,7 +409,7 @@
/// Add user to allowed list.
///
/// @param user User cross account address.
- /// @dev EVM selector for this function is: 0xa0184a3a,
+ /// @dev EVM selector for this function is: 0xf074da88,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
function addToCollectionAllowListCross(Tuple6 memory user) public {
require(false, stub_error);
@@ -420,7 +431,7 @@
/// Remove user from allowed list.
///
/// @param user User cross account address.
- /// @dev EVM selector for this function is: 0x09ba452a,
+ /// @dev EVM selector for this function is: 0xc00df45c,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
function removeFromCollectionAllowListCross(Tuple6 memory user) public {
require(false, stub_error);
@@ -456,7 +467,7 @@
///
/// @param user User cross account to verify
/// @return "true" if account is the owner or admin
- /// @dev EVM selector for this function is: 0x3e75a905,
+ /// @dev EVM selector for this function is: 0x5aba3351,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
function isOwnerOrAdminCross(Tuple6 memory user) public view returns (bool) {
require(false, stub_error);
@@ -483,6 +494,7 @@
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
<<<<<<< HEAD
+<<<<<<< HEAD
function collectionOwner() public view returns (Tuple6 memory) {
require(false, stub_error);
dummy;
@@ -493,6 +505,12 @@
dummy;
return Tuple19(0x0000000000000000000000000000000000000000, 0);
>>>>>>> feat: add `EthCrossAccount` type
+=======
+ function collectionOwner() public view returns (Tuple8 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple8(0x0000000000000000000000000000000000000000, 0);
+>>>>>>> feat: Add custum signature with unlimited nesting.
}
/// Changes collection owner to another account
@@ -523,7 +541,7 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner cross account
- /// @dev EVM selector for this function is: 0xe5c9913f,
+ /// @dev EVM selector for this function is: 0xbdff793d,
/// or in textual repr: setOwnerCross((address,uint256))
function setOwnerCross(Tuple6 memory newOwner) public {
require(false, stub_error);
@@ -532,6 +550,7 @@
}
}
+<<<<<<< HEAD
/// @dev anonymous struct
struct Tuple19 {
address field_0;
@@ -581,6 +600,8 @@
}
}
+=======
+>>>>>>> feat: Add custum signature with unlimited nesting.
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
contract ERC721Burnable is Dummy, ERC165 {
@@ -682,7 +703,11 @@
}
/// @title Unique extensions for ERC721.
+<<<<<<< HEAD
/// @dev the ERC-165 identifier for this interface is 0x244543ee
+=======
+/// @dev the ERC-165 identifier for this interface is 0xcc97cb35
+>>>>>>> feat: Add custum signature with unlimited nesting.
contract ERC721UniqueExtensions is Dummy, ERC165 {
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev EVM selector for this function is: 0x06fdde03,
@@ -708,7 +733,7 @@
/// operator of the current owner.
/// @param approved The new substrate address approved NFT controller
/// @param tokenId The NFT to approve
- /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// @dev EVM selector for this function is: 0x106fdb59,
/// or in textual repr: approveCross((address,uint256),uint256)
function approveCross(Tuple6 memory approved, uint256 tokenId) public {
require(false, stub_error);
@@ -738,10 +763,15 @@
/// @param to Cross acccount address of new owner
/// @param tokenId The NFT to transfer
/// @dev EVM selector for this function is: 0xd5cf430b,
- /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ /// or in textual repr: transferFromCross(EthCrossAccount,EthCrossAccount,uint256)
function transferFromCross(
+<<<<<<< HEAD
Tuple6 memory from,
Tuple6 memory to,
+=======
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
+>>>>>>> feat: Add custum signature with unlimited nesting.
uint256 tokenId
) public {
require(false, stub_error);
@@ -772,7 +802,7 @@
/// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.
/// @param from The current owner of the NFT
/// @param tokenId The NFT to transfer
- /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// @dev EVM selector for this function is: 0xa8106d4a,
/// or in textual repr: burnFromCross((address,uint256),uint256)
function burnFromCross(Tuple6 memory from, uint256 tokenId) public {
require(false, stub_error);
@@ -819,10 +849,46 @@
// return false;
// }
+<<<<<<< HEAD
}
/// @dev anonymous struct
struct Tuple8 {
+=======
+ /// @notice Function to mint multiple tokens.
+ /// @dev `tokenIds` should be an array of consecutive numbers and first number
+ /// should be obtained with `nextTokenId` method
+ /// @param to The new owner
+ /// @param tokenIds IDs of the minted NFTs
+ /// @dev EVM selector for this function is: 0xf9d9a5a3,
+ /// or in textual repr: mintBulk(address,uint256[])
+ function mintBulk(address to, uint256[] memory tokenIds) public returns (bool) {
+ require(false, stub_error);
+ to;
+ tokenIds;
+ dummy = 0;
+ return false;
+ }
+
+ /// @notice Function to mint multiple tokens with the given tokenUris.
+ /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
+ /// numbers and first number should be obtained with `nextTokenId` method
+ /// @param to The new owner
+ /// @param tokens array of pairs of token ID and token URI for minted tokens
+ /// @dev EVM selector for this function is: 0xfd4e2a99,
+ /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
+ function mintBulkWithTokenURI(address to, Tuple12[] memory tokens) public returns (bool) {
+ require(false, stub_error);
+ to;
+ tokens;
+ dummy = 0;
+ return false;
+ }
+}
+
+/// @dev anonymous struct
+struct Tuple12 {
+>>>>>>> feat: Add custum signature with unlimited nesting.
uint256 field_0;
string field_1;
}
@@ -840,6 +906,12 @@
>>>>>>> feat: add `EthCrossAccount` type
}
+/// @dev anonymous struct
+struct Tuple8 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x780e9d63
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -26,7 +26,15 @@
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ ToLog,
+ execution::*,
+ generate_stubgen, solidity, solidity_interface,
+ types::*,
+ weight,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
+};
use frame_support::{BoundedBTreeMap, BoundedVec};
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions,
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -29,7 +29,15 @@
convert::TryInto,
ops::Deref,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
+use evm_coder::{
+ ToLog,
+ execution::*,
+ generate_stubgen, solidity_interface,
+ types::*,
+ weight,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
+};
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -18,7 +18,13 @@
use core::marker::PhantomData;
use ethereum as _;
-use evm_coder::{execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{
+ execution::*,
+ generate_stubgen, solidity, solidity_interface,
+ types::*,
+ custom_signature::{FunctionName, FunctionSignature},
+ make_signature,
+, weight};
use frame_support::{traits::Get, storage::StorageNMap};
use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageDoubleMap;
use crate::Pallet;
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -70,7 +70,11 @@
}
/// @title A contract that allows you to work with collections.
+<<<<<<< HEAD
/// @dev the ERC-165 identifier for this interface is 0xb3152af3
+=======
+/// @dev the ERC-165 identifier for this interface is 0x674be726
+>>>>>>> feat: Add custum signature with unlimited nesting.
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -133,7 +137,7 @@
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
///
/// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
- /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// @dev EVM selector for this function is: 0x403e96a7,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
function setCollectionSponsorCross(Tuple6 memory sponsor) external;
@@ -193,13 +197,13 @@
/// Add collection admin.
/// @param newAdmin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x859aa7d6,
+ /// @dev EVM selector for this function is: 0x62e3c7c2,
/// or in textual repr: addCollectionAdminCross((address,uint256))
function addCollectionAdminCross(Tuple6 memory newAdmin) external;
/// Remove collection admin.
/// @param admin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x6c0cd173,
+ /// @dev EVM selector for this function is: 0x810d1503,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
function removeCollectionAdminCross(Tuple6 memory admin) external;
@@ -227,7 +231,7 @@
///
/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
/// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
+ /// @dev EVM selector for this function is: 0x112d4586,
/// or in textual repr: setCollectionNesting(bool,address[])
function setCollectionNesting(bool enable, address[] memory collections) external;
@@ -256,7 +260,7 @@
/// Add user to allowed list.
///
/// @param user User cross account address.
- /// @dev EVM selector for this function is: 0xa0184a3a,
+ /// @dev EVM selector for this function is: 0xf074da88,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
function addToCollectionAllowListCross(Tuple6 memory user) external;
@@ -270,7 +274,7 @@
/// Remove user from allowed list.
///
/// @param user User cross account address.
- /// @dev EVM selector for this function is: 0x09ba452a,
+ /// @dev EVM selector for this function is: 0xc00df45c,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
function removeFromCollectionAllowListCross(Tuple6 memory user) external;
@@ -293,7 +297,7 @@
///
/// @param user User cross account to verify
/// @return "true" if account is the owner or admin
- /// @dev EVM selector for this function is: 0x3e75a905,
+ /// @dev EVM selector for this function is: 0x5aba3351,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
function isOwnerOrAdminCross(Tuple6 memory user) external view returns (bool);
@@ -332,11 +336,12 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner cross account
- /// @dev EVM selector for this function is: 0xe5c9913f,
+ /// @dev EVM selector for this function is: 0xbdff793d,
/// or in textual repr: setOwnerCross((address,uint256))
function setOwnerCross(Tuple6 memory newOwner) external;
}
+<<<<<<< HEAD
/// @dev anonymous struct
struct Tuple19 {
address field_0;
@@ -373,6 +378,8 @@
function tokenURI(uint256 tokenId) external view returns (string memory);
}
+=======
+>>>>>>> feat: Add custum signature with unlimited nesting.
/// @title ERC721 Token that can be irreversibly burned (destroyed).
/// @dev the ERC-165 identifier for this interface is 0x42966c68
interface ERC721Burnable is Dummy, ERC165 {
@@ -438,7 +445,11 @@
}
/// @title Unique extensions for ERC721.
+<<<<<<< HEAD
/// @dev the ERC-165 identifier for this interface is 0x244543ee
+=======
+/// @dev the ERC-165 identifier for this interface is 0xcc97cb35
+>>>>>>> feat: Add custum signature with unlimited nesting.
interface ERC721UniqueExtensions is Dummy, ERC165 {
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev EVM selector for this function is: 0x06fdde03,
@@ -456,7 +467,7 @@
/// operator of the current owner.
/// @param approved The new substrate address approved NFT controller
/// @param tokenId The NFT to approve
- /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// @dev EVM selector for this function is: 0x106fdb59,
/// or in textual repr: approveCross((address,uint256),uint256)
function approveCross(Tuple6 memory approved, uint256 tokenId) external;
@@ -476,10 +487,15 @@
/// @param to Cross acccount address of new owner
/// @param tokenId The NFT to transfer
/// @dev EVM selector for this function is: 0xd5cf430b,
- /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ /// or in textual repr: transferFromCross(EthCrossAccount,EthCrossAccount,uint256)
function transferFromCross(
+<<<<<<< HEAD
Tuple6 memory from,
Tuple6 memory to,
+=======
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
+>>>>>>> feat: Add custum signature with unlimited nesting.
uint256 tokenId
) external;
@@ -499,7 +515,7 @@
/// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.
/// @param from The current owner of the NFT
/// @param tokenId The NFT to transfer
- /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// @dev EVM selector for this function is: 0xa8106d4a,
/// or in textual repr: burnFromCross((address,uint256),uint256)
function burnFromCross(Tuple6 memory from, uint256 tokenId) external;
@@ -507,6 +523,7 @@
/// @dev EVM selector for this function is: 0x75794a3c,
/// or in textual repr: nextTokenId()
function nextTokenId() external view returns (uint256);
+<<<<<<< HEAD
// /// @notice Function to mint multiple tokens.
// /// @dev `tokenIds` should be an array of consecutive numbers and first number
// /// should be obtained with `nextTokenId` method
@@ -528,6 +545,30 @@
/// @dev anonymous struct
struct Tuple8 {
+=======
+
+ /// @notice Function to mint multiple tokens.
+ /// @dev `tokenIds` should be an array of consecutive numbers and first number
+ /// should be obtained with `nextTokenId` method
+ /// @param to The new owner
+ /// @param tokenIds IDs of the minted NFTs
+ /// @dev EVM selector for this function is: 0xf9d9a5a3,
+ /// or in textual repr: mintBulk(address,uint256[])
+ function mintBulk(address to, uint256[] memory tokenIds) external returns (bool);
+
+ /// @notice Function to mint multiple tokens with the given tokenUris.
+ /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
+ /// numbers and first number should be obtained with `nextTokenId` method
+ /// @param to The new owner
+ /// @param tokens array of pairs of token ID and token URI for minted tokens
+ /// @dev EVM selector for this function is: 0xfd4e2a99,
+ /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
+ function mintBulkWithTokenURI(address to, Tuple12[] memory tokens) external returns (bool);
+}
+
+/// @dev anonymous struct
+struct Tuple12 {
+>>>>>>> feat: Add custum signature with unlimited nesting.
uint256 field_0;
string field_1;
}
@@ -538,6 +579,12 @@
uint256 field_1;
}
+/// @dev anonymous struct
+struct Tuple8 {
+ address field_0;
+ uint256 field_1;
+}
+
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x780e9d63
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -409,7 +409,7 @@
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
});
- itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
+ itEth.only('Can perform transferFromCross()', async ({helper, privateKey}) => {
const alice = privateKey('//Alice');
const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -251,10 +251,14 @@
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
<<<<<<< HEAD
+<<<<<<< HEAD
"internalType": "struct Tuple6",
=======
"internalType": "struct Tuple19",
>>>>>>> feat: add `EthCrossAccount` type
+=======
+ "internalType": "struct Tuple8",
+>>>>>>> feat: Add custum signature with unlimited nesting.
"name": "",
"type": "tuple"
}
@@ -263,6 +267,7 @@
"type": "function"
},
{
+<<<<<<< HEAD
"inputs": [
{ "internalType": "string[]", "name": "keys", "type": "string[]" }
],
@@ -278,6 +283,11 @@
"type": "tuple[]"
}
],
+=======
+ "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
+ "name": "collectionProperty",
+ "outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
+>>>>>>> feat: Add custum signature with unlimited nesting.
"stateMutability": "view",
"type": "function"
},
@@ -298,10 +308,14 @@
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
<<<<<<< HEAD
+<<<<<<< HEAD
"internalType": "struct Tuple6",
=======
"internalType": "struct Tuple19",
>>>>>>> feat: add `EthCrossAccount` type
+=======
+ "internalType": "struct Tuple8",
+>>>>>>> feat: Add custum signature with unlimited nesting.
"name": "",
"type": "tuple"
}
@@ -324,6 +338,7 @@
"type": "function"
},
{
+<<<<<<< HEAD
"inputs": [
{ "internalType": "string[]", "name": "keys", "type": "string[]" }
],
@@ -333,6 +348,8 @@
"type": "function"
},
{
+=======
+>>>>>>> feat: Add custum signature with unlimited nesting.
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "deleteCollectionProperty",
"outputs": [],
@@ -409,19 +426,64 @@
"type": "function"
},
{
+<<<<<<< HEAD
"inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
"name": "mint",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+=======
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "mint",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+>>>>>>> feat: Add custum signature with unlimited nesting.
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{ "internalType": "address", "name": "to", "type": "address" },
+<<<<<<< HEAD
{ "internalType": "string", "name": "tokenUri", "type": "string" }
],
"name": "mintWithTokenURI",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+=======
+ { "internalType": "uint256[]", "name": "tokenIds", "type": "uint256[]" }
+ ],
+ "name": "mintBulk",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ {
+ "components": [
+ { "internalType": "uint256", "name": "field_0", "type": "uint256" },
+ { "internalType": "string", "name": "field_1", "type": "string" }
+ ],
+ "internalType": "struct Tuple12[]",
+ "name": "tokens",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "mintBulkWithTokenURI",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ { "internalType": "string", "name": "tokenUri", "type": "string" }
+ ],
+ "name": "mintWithTokenURI",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+>>>>>>> feat: Add custum signature with unlimited nesting.
"stateMutability": "nonpayable",
"type": "function"
},
@@ -614,6 +676,7 @@
},
{
"inputs": [
+<<<<<<< HEAD
{
"components": [
{ "internalType": "string", "name": "field_0", "type": "string" },
@@ -623,6 +686,10 @@
"name": "properties",
"type": "tuple[]"
}
+=======
+ { "internalType": "string", "name": "key", "type": "string" },
+ { "internalType": "bytes", "name": "value", "type": "bytes" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
"name": "setCollectionProperties",
"outputs": [],
@@ -667,6 +734,7 @@
},
{
"inputs": [
+<<<<<<< HEAD
{
"components": [
{ "internalType": "address", "name": "field_0", "type": "address" },
@@ -676,6 +744,9 @@
"name": "newOwner",
"type": "tuple"
}
+=======
+ { "internalType": "address", "name": "newOwner", "type": "address" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
"name": "setOwnerCross",
"outputs": [],
@@ -687,8 +758,13 @@
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{
"components": [
+<<<<<<< HEAD
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
+=======
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
"internalType": "struct Tuple19[]",
"name": "properties",
@@ -799,8 +875,13 @@
"inputs": [
{
"components": [
+<<<<<<< HEAD
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
+=======
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
<<<<<<< HEAD
"internalType": "struct Tuple6",
@@ -812,8 +893,13 @@
},
{
"components": [
+<<<<<<< HEAD
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
+=======
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+>>>>>>> feat: Add custum signature with unlimited nesting.
],
<<<<<<< HEAD
"internalType": "struct Tuple6",
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -14,10 +14,8 @@
args: { [key: string]: string }
};
export interface TEthCrossAccount {
- readonly 0: string,
- readonly 1: string | Uint8Array,
- readonly field_0: string,
- readonly field_1: string | Uint8Array,
+ readonly eth: string,
+ readonly sub: string | Uint8Array,
}
export type EthProperty = string[];
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -364,19 +364,15 @@
export class EthCrossAccountGroup extends EthGroupBase {
fromAddress(address: TEthereumAccount): TEthCrossAccount {
return {
- 0: address,
- 1: '0',
- field_0: address,
- field_1: '0',
+ eth: address,
+ sub: '0',
};
}
fromKeyringPair(keyring: IKeyringPair): TEthCrossAccount {
return {
- 0: '0x0000000000000000000000000000000000000000',
- 1: keyring.addressRaw,
- field_0: '0x0000000000000000000000000000000000000000',
- field_1: keyring.addressRaw,
+ eth: '0x0000000000000000000000000000000000000000',
+ sub: keyring.addressRaw,
};
}
}
@@ -429,7 +425,6 @@
ethAddress: EthAddressGroup;
ethNativeContract: NativeContractGroup;
ethContract: ContractGroup;
- ethCrossAccount: EthCrossAccountGroup;
ethProperty: EthPropertyGroup;
constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {