difftreelog
Merge branch 'develop' into tests/increase_timeout
in: master
60 files changed
.maintain/scripts/compile_stub.shdiffbeforeafterboth--- a/.maintain/scripts/compile_stub.sh
+++ b/.maintain/scripts/compile_stub.sh
@@ -6,6 +6,7 @@
tmp=$(mktemp -d)
cd $tmp
cp $dir/$INPUT input.sol
+echo "Tmp file: $tmp/input.sol"
solcjs --optimize --bin input.sol -o $PWD
mv input_sol_$(basename $OUTPUT .raw).bin out.bin
.maintain/scripts/generate_sol.shdiffbeforeafterboth--- a/.maintain/scripts/generate_sol.sh
+++ b/.maintain/scripts/generate_sol.sh
@@ -4,7 +4,7 @@
PRETTIER_CONFIG="$(pwd)""/.prettierrc"
tmp=$(mktemp)
-cargo test --package $PACKAGE -- $NAME --exact --nocapture --ignored | tee $tmp
+cargo test --package=$PACKAGE --features=stubgen -- $NAME --exact --nocapture --ignored | tee $tmp
raw=$(mktemp --suffix .sol)
sed -n '/=== SNIP START ===/, /=== SNIP END ===/{ /=== SNIP START ===/! { /=== SNIP END ===/! p } }' $tmp > $raw
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -252,11 +252,12 @@
[[package]]
name = "async-lock"
-version = "2.5.0"
+version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e97a171d191782fba31bb902b14ad94e24a68145032b7eedf871ab0bc0d077b6"
+checksum = "c8101efe8695a6c17e02911402145357e718ac92d3ff88ae8419e84b1707b685"
dependencies = [
"event-listener",
+ "futures-lite",
]
[[package]]
@@ -977,9 +978,9 @@
[[package]]
name = "clap"
-version = "3.2.22"
+version = "3.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "86447ad904c7fb335a790c9d7fe3d0d971dc523b8ccd1561a520de9a85302750"
+checksum = "71655c45cb9845d3270c9d6df84ebe72b4dad3c2ba3f7023ad47c144e4e473a5"
dependencies = [
"atty",
"bitflags",
@@ -1871,9 +1872,9 @@
[[package]]
name = "cxx"
-version = "1.0.78"
+version = "1.0.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "19f39818dcfc97d45b03953c1292efc4e80954e1583c4aa770bac1383e2310a4"
+checksum = "6b7d4e43b25d3c994662706a1d4fcfc32aaa6afd287502c111b237093bb23f3a"
dependencies = [
"cc",
"cxxbridge-flags",
@@ -1883,9 +1884,9 @@
[[package]]
name = "cxx-build"
-version = "1.0.78"
+version = "1.0.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e580d70777c116df50c390d1211993f62d40302881e54d4b79727acb83d0199"
+checksum = "84f8829ddc213e2c1368e51a2564c552b65a8cb6a28f31e576270ac81d5e5827"
dependencies = [
"cc",
"codespan-reporting",
@@ -1898,15 +1899,15 @@
[[package]]
name = "cxxbridge-flags"
-version = "1.0.78"
+version = "1.0.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "56a46460b88d1cec95112c8c363f0e2c39afdb237f60583b0b36343bf627ea9c"
+checksum = "e72537424b474af1460806647c41d4b6d35d09ef7fe031c5c2fa5766047cc56a"
[[package]]
name = "cxxbridge-macro"
-version = "1.0.78"
+version = "1.0.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "747b608fecf06b0d72d440f27acc99288207324b793be2c17991839f3d4995ea"
+checksum = "309e4fb93eed90e1e14bea0da16b209f81813ba9fc7830c20ed151dd7bc0a4d7"
dependencies = [
"proc-macro2",
"quote",
@@ -2128,15 +2129,15 @@
[[package]]
name = "ed25519-zebra"
-version = "3.0.0"
+version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "403ef3e961ab98f0ba902771d29f842058578bb1ce7e3c59dad5a6a93e784c69"
+checksum = "7c24f403d068ad0b359e577a77f92392118be3f3c927538f2bb544a5ecd828c6"
dependencies = [
"curve25519-dalek 3.2.0",
+ "hashbrown",
"hex",
"rand_core 0.6.4",
"sha2 0.9.9",
- "thiserror",
"zeroize",
]
@@ -2331,7 +2332,7 @@
[[package]]
name = "evm-coder"
-version = "0.1.3"
+version = "0.1.4"
dependencies = [
"concat-idents",
"ethereum",
@@ -2341,14 +2342,17 @@
"hex",
"hex-literal",
"impl-trait-for-tuples",
+ "pallet-evm",
"primitive-types",
+ "sha3-const",
"similar-asserts",
"sp-std",
+ "trybuild",
]
[[package]]
name = "evm-coder-procedural"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"Inflector",
"hex",
@@ -3336,9 +3340,9 @@
[[package]]
name = "h2"
-version = "0.3.14"
+version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ca32592cf21ac7ccab1825cd87f6c9b3d9022c44d086172ed0966bec8af30be"
+checksum = "5f9f29bc9dda355256b2916cf526ab02ce0aeaaaf2bad60d65ef3f12f11dd0f4"
dependencies = [
"bytes",
"fnv",
@@ -3561,9 +3565,9 @@
[[package]]
name = "iana-time-zone-haiku"
-version = "0.1.0"
+version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fde6edd6cef363e9359ed3c98ba64590ba9eecba2293eb5a723ab32aee8926aa"
+checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca"
dependencies = [
"cxx",
"cxx-build",
@@ -3702,9 +3706,9 @@
[[package]]
name = "io-lifetimes"
-version = "0.7.3"
+version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1ea37f355c05dde75b84bba2d767906ad522e97cd9e2eef2be7a4ab7fb442c06"
+checksum = "e6e481ccbe3dea62107216d0d1138bb8ad8e5e5c43009a098bd1990272c497b0"
[[package]]
name = "ip_network"
@@ -4093,9 +4097,9 @@
[[package]]
name = "libc"
-version = "0.2.135"
+version = "0.2.137"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c"
+checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89"
[[package]]
name = "libloading"
@@ -4967,14 +4971,14 @@
[[package]]
name = "mio"
-version = "0.8.4"
+version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "57ee1c23c7c63b0c9250c339ffdc69255f110b298b901b9f6c82547b7b87caaf"
+checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de"
dependencies = [
"libc",
"log",
"wasi 0.11.0+wasi-snapshot-preview1",
- "windows-sys 0.36.1",
+ "windows-sys 0.42.0",
]
[[package]]
@@ -5826,7 +5830,7 @@
[[package]]
name = "pallet-common"
-version = "0.1.9"
+version = "0.1.10"
dependencies = [
"ethereum",
"evm-coder",
@@ -6116,7 +6120,7 @@
[[package]]
name = "pallet-fungible"
-version = "0.1.5"
+version = "0.1.6"
dependencies = [
"ethereum",
"evm-coder",
@@ -6359,7 +6363,7 @@
[[package]]
name = "pallet-nonfungible"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"ethereum",
"evm-coder",
@@ -6481,7 +6485,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.2.5"
+version = "0.2.6"
dependencies = [
"derivative",
"ethereum",
@@ -7248,9 +7252,9 @@
[[package]]
name = "pkg-config"
-version = "0.3.25"
+version = "0.3.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae"
+checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"
[[package]]
name = "platforms"
@@ -8501,9 +8505,9 @@
[[package]]
name = "polling"
-version = "2.3.0"
+version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "899b00b9c8ab553c743b3e11e87c5c7d423b2a2de229ba95b24a756344748011"
+checksum = "ab4609a838d88b73d8238967b60dd115cc08d38e2bbaf51ee1e4b695f89122e2"
dependencies = [
"autocfg",
"cfg-if 1.0.0",
@@ -9408,9 +9412,9 @@
[[package]]
name = "rustix"
-version = "0.35.11"
+version = "0.35.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fbb2fda4666def1433b1b05431ab402e42a1084285477222b72d6c564c417cef"
+checksum = "985947f9b6423159c4726323f373be0a21bdb514c5af06a849cb3d2dce2d01e8"
dependencies = [
"bitflags",
"errno",
@@ -10683,9 +10687,9 @@
[[package]]
name = "secp256k1"
-version = "0.24.0"
+version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b7649a0b3ffb32636e60c7ce0d70511eda9c52c658cd0634e194d5a19943aeff"
+checksum = "ff55dc09d460954e9ef2fa8a7ced735a964be9981fd50e870b2b3b0705e14964"
dependencies = [
"secp256k1-sys",
]
@@ -10766,18 +10770,18 @@
[[package]]
name = "serde"
-version = "1.0.146"
+version = "1.0.147"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6df50b7a60a0ad48e1b42eb38373eac8ff785d619fb14db917b4e63d5439361f"
+checksum = "d193d69bae983fc11a79df82342761dfbf28a99fc8d203dca4c3c1b590948965"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.146"
+version = "1.0.147"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a714fd32ba1d66047ce7d53dabd809e9922d538f9047de13cc4cffca47b36205"
+checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852"
dependencies = [
"proc-macro2",
"quote",
@@ -10786,9 +10790,9 @@
[[package]]
name = "serde_json"
-version = "1.0.86"
+version = "1.0.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41feea4228a6f1cd09ec7a3593a682276702cd67b5273544757dae23c096f074"
+checksum = "6ce777b7b150d76b9cf60d28b55f5847135a003f7d7350c6be7a773508ce7d45"
dependencies = [
"itoa",
"ryu",
@@ -10875,6 +10879,12 @@
]
[[package]]
+name = "sha3-const"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b04774de876479a8f712e787f8271b14712971329a4be66c6dff144db7cfc343"
+
+[[package]]
name = "sharded-slab"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -12067,9 +12077,9 @@
[[package]]
name = "syn"
-version = "1.0.102"
+version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fcd952facd492f9be3ef0d0b7032a6e442ee9b361d4acc2b1d0c4aaa5f613a1"
+checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d"
dependencies = [
"proc-macro2",
"quote",
@@ -12198,9 +12208,9 @@
[[package]]
name = "textwrap"
-version = "0.15.1"
+version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "949517c0cf1bf4ee812e2e07e08ab448e3ae0d23472aee8a06c985f0c8815b16"
+checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d"
[[package]]
name = "thiserror"
@@ -12643,6 +12653,21 @@
]
[[package]]
+name = "trybuild"
+version = "1.0.71"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea496675d71016e9bc76aa42d87f16aefd95447cc5818e671e12b2d7e269075d"
+dependencies = [
+ "glob",
+ "once_cell",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "termcolor",
+ "toml",
+]
+
+[[package]]
name = "tt-call"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
crates/evm-coder/CHANGELOG.mddiffbeforeafterboth--- a/crates/evm-coder/CHANGELOG.md
+++ b/crates/evm-coder/CHANGELOG.md
@@ -2,13 +2,17 @@
All notable changes to this project will be documented in this file.
-## [0.1.3] - 2022-08-29
+<!-- bureaucrate goes here -->
+## [v0.1.4] - 2022-11-02
+### Added
+ - Named structures support.
+
+## [v0.1.3] - 2022-08-29
### Fixed
- Parsing simple values.
-<!-- bureaucrate goes here -->
## [v0.1.2] 2022-08-19
### Added
crates/evm-coder/Cargo.tomldiffbeforeafterboth--- a/crates/evm-coder/Cargo.toml
+++ b/crates/evm-coder/Cargo.toml
@@ -1,10 +1,11 @@
[package]
name = "evm-coder"
-version = "0.1.3"
+version = "0.1.4"
license = "GPLv3"
edition = "2021"
[dependencies]
+sha3-const = { version = "0.1.1", default-features = false }
# evm-coder reexports those proc-macro
evm-coder-procedural = { path = "./procedural" }
# Evm uses primitive-types for H160, H256 and others
@@ -18,12 +19,15 @@
# We have tuple-heavy code in solidity.rs
impl-trait-for-tuples = "0.2.2"
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.30" }
+
[dev-dependencies]
# We want to assert some large binary blobs equality in tests
hex = "0.4.3"
hex-literal = "0.3.4"
similar-asserts = "1.4.2"
concat-idents = "1.1.3"
+trybuild = "1.0"
[features]
default = ["std"]
@@ -33,3 +37,5 @@
"evm-core/std",
"frame-support/std",
]
+# Stub/interface generation
+stubgen = []
crates/evm-coder/procedural/Cargo.tomldiffbeforeafterboth--- a/crates/evm-coder/procedural/Cargo.toml
+++ b/crates/evm-coder/procedural/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "evm-coder-procedural"
-version = "0.2.0"
+version = "0.2.1"
license = "GPLv3"
edition = "2021"
crates/evm-coder/procedural/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/lib.rs
+++ b/crates/evm-coder/procedural/src/lib.rs
@@ -107,7 +107,7 @@
if path.segments.len() != 1 {
return Err(syn::Error::new(
path.span(),
- "expected path to have only segment",
+ "expected path to have only one segment",
));
}
let last_segment = &path.segments.last().unwrap();
crates/evm-coder/procedural/src/solidity_interface.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#![allow(dead_code)]1819// NOTE: In order to understand this Rust macro better, first read this chapter20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html2223use quote::{quote, ToTokens};24use inflector::cases;25use std::fmt::Write;26use syn::{27 Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,28 MetaNameValue, PatType, PathArguments, ReturnType, Type,29 spanned::Spanned,30 parse::{Parse, ParseStream},31 parenthesized, Token, LitInt, LitStr,32};3334use crate::{35 fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,36 parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,37 snake_ident_to_screaming,38};3940struct Is {41 name: Ident,42 pascal_call_name: Ident,43 snake_call_name: Ident,44 via: Option<(Type, Ident)>,45 condition: Option<Expr>,46}47impl Is {48 fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {49 let name = &self.name;50 let pascal_call_name = &self.pascal_call_name;51 quote! {52 #name(#pascal_call_name #gen_ref)53 }54 }5556 fn expand_interface_id(&self) -> proc_macro2::TokenStream {57 let pascal_call_name = &self.pascal_call_name;58 quote! {59 interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());60 }61 }6263 fn expand_supports_interface(64 &self,65 generics: &proc_macro2::TokenStream,66 ) -> proc_macro2::TokenStream {67 let pascal_call_name = &self.pascal_call_name;68 let condition = self.condition.as_ref().map(|condition| {69 quote! {70 (#condition) &&71 }72 });73 quote! {74 #condition <#pascal_call_name #generics>::supports_interface(this, interface_id)75 }76 }7778 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {79 let name = &self.name;80 quote! {81 Self::#name(call) => call.weight()82 }83 }8485 fn expand_variant_call(86 &self,87 call_name: &proc_macro2::Ident,88 generics: &proc_macro2::TokenStream,89 ) -> proc_macro2::TokenStream {90 let name = &self.name;91 let pascal_call_name = &self.pascal_call_name;92 let via_typ = self93 .via94 .as_ref()95 .map(|(t, _)| quote! {#t})96 .unwrap_or_else(|| quote! {Self});97 let via_map = self98 .via99 .as_ref()100 .map(|(_, i)| quote! {.#i()})101 .unwrap_or_default();102 let condition = self.condition.as_ref().map(|condition| {103 quote! {104 if ({let this = &self; (#condition)})105 }106 });107 quote! {108 #call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {109 call,110 caller: c.caller,111 value: c.value,112 })113 }114 }115116 fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {117 let name = &self.name;118 let pascal_call_name = &self.pascal_call_name;119 quote! {120 if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {121 return Ok(Some(Self::#name(parsed_call)))122 }123 }124 }125126 fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {127 let pascal_call_name = &self.pascal_call_name;128 quote! {129 <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);130 }131 }132133 fn expand_event_generator(&self) -> proc_macro2::TokenStream {134 let name = &self.name;135 quote! {136 #name::generate_solidity_interface(tc, is_impl);137 }138 }139}140141#[derive(Default)]142struct IsList(Vec<Is>);143impl Parse for IsList {144 fn parse(input: ParseStream) -> syn::Result<Self> {145 let mut out = vec![];146 loop {147 if input.is_empty() {148 break;149 }150 let name = input.parse::<Ident>()?;151 let lookahead = input.lookahead1();152153 let mut condition: Option<Expr> = None;154 let mut via: Option<(Type, Ident)> = None;155156 if lookahead.peek(syn::token::Paren) {157 let contents;158 parenthesized!(contents in input);159 let input = contents;160161 while !input.is_empty() {162 let lookahead = input.lookahead1();163 if lookahead.peek(Token![if]) {164 input.parse::<Token![if]>()?;165 let contents;166 parenthesized!(contents in input);167 let contents = contents.parse::<Expr>()?;168169 if condition.replace(contents).is_some() {170 return Err(syn::Error::new(input.span(), "condition is already set"));171 }172 } else if lookahead.peek(kw::via) {173 input.parse::<kw::via>()?;174 let contents;175 parenthesized!(contents in input);176177 let method = contents.parse::<Ident>()?;178 contents.parse::<kw::returns>()?;179 let ty = contents.parse::<Type>()?;180181 if via.replace((ty, method)).is_some() {182 return Err(syn::Error::new(input.span(), "via is already set"));183 }184 } else {185 return Err(lookahead.error());186 }187188 if input.peek(Token![,]) {189 input.parse::<Token![,]>()?;190 } else if !input.is_empty() {191 return Err(syn::Error::new(input.span(), "expected end"));192 }193 }194 } else if lookahead.peek(Token![,]) || input.is_empty() {195 // Pass196 } else {197 return Err(lookahead.error());198 };199 out.push(Is {200 pascal_call_name: pascal_ident_to_call(&name),201 snake_call_name: pascal_ident_to_snake_call(&name),202 name,203 via,204 condition,205 });206 if input.peek(Token![,]) {207 input.parse::<Token![,]>()?;208 continue;209 } else {210 break;211 }212 }213 Ok(Self(out))214 }215}216217pub struct InterfaceInfo {218 name: Ident,219 is: IsList,220 inline_is: IsList,221 events: IsList,222 expect_selector: Option<u32>,223}224impl Parse for InterfaceInfo {225 fn parse(input: ParseStream) -> syn::Result<Self> {226 let mut name = None;227 let mut is = None;228 let mut inline_is = None;229 let mut events = None;230 let mut expect_selector = None;231 // TODO: create proc-macro to optimize proc-macro boilerplate? :D232 loop {233 let lookahead = input.lookahead1();234 if lookahead.peek(kw::name) {235 let k = input.parse::<kw::name>()?;236 input.parse::<Token![=]>()?;237 if name.replace(input.parse::<Ident>()?).is_some() {238 return Err(syn::Error::new(k.span(), "name is already set"));239 }240 } else if lookahead.peek(kw::is) {241 let k = input.parse::<kw::is>()?;242 let contents;243 parenthesized!(contents in input);244 if is.replace(contents.parse::<IsList>()?).is_some() {245 return Err(syn::Error::new(k.span(), "is is already set"));246 }247 } else if lookahead.peek(kw::inline_is) {248 let k = input.parse::<kw::inline_is>()?;249 let contents;250 parenthesized!(contents in input);251 if inline_is.replace(contents.parse::<IsList>()?).is_some() {252 return Err(syn::Error::new(k.span(), "inline_is is already set"));253 }254 } else if lookahead.peek(kw::events) {255 let k = input.parse::<kw::events>()?;256 let contents;257 parenthesized!(contents in input);258 if events.replace(contents.parse::<IsList>()?).is_some() {259 return Err(syn::Error::new(k.span(), "events is already set"));260 }261 } else if lookahead.peek(kw::expect_selector) {262 let k = input.parse::<kw::expect_selector>()?;263 input.parse::<Token![=]>()?;264 let value = input.parse::<LitInt>()?;265 if expect_selector266 .replace(value.base10_parse::<u32>()?)267 .is_some()268 {269 return Err(syn::Error::new(k.span(), "expect_selector is already set"));270 }271 } else if input.is_empty() {272 break;273 } else {274 return Err(lookahead.error());275 }276 if input.peek(Token![,]) {277 input.parse::<Token![,]>()?;278 } else {279 break;280 }281 }282 Ok(Self {283 name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,284 is: is.unwrap_or_default(),285 inline_is: inline_is.unwrap_or_default(),286 events: events.unwrap_or_default(),287 expect_selector,288 })289 }290}291292struct MethodInfo {293 rename_selector: Option<String>,294 hide: bool,295}296impl Parse for MethodInfo {297 fn parse(input: ParseStream) -> syn::Result<Self> {298 let mut rename_selector = None;299 let mut hide = false;300 while !input.is_empty() {301 let lookahead = input.lookahead1();302 if lookahead.peek(kw::rename_selector) {303 let k = input.parse::<kw::rename_selector>()?;304 input.parse::<Token![=]>()?;305 if rename_selector306 .replace(input.parse::<LitStr>()?.value())307 .is_some()308 {309 return Err(syn::Error::new(k.span(), "rename_selector is already set"));310 }311 } else if lookahead.peek(kw::hide) {312 input.parse::<kw::hide>()?;313 hide = true;314 } else {315 return Err(lookahead.error());316 }317318 if input.peek(Token![,]) {319 input.parse::<Token![,]>()?;320 } else if !input.is_empty() {321 return Err(syn::Error::new(input.span(), "expected end"));322 }323 }324 Ok(Self {325 rename_selector,326 hide,327 })328 }329}330331enum AbiType {332 // type333 Plain(Ident),334 // (type1,type2)335 Tuple(Vec<AbiType>),336 // type[]337 Vec(Box<AbiType>),338 // type[20]339 Array(Box<AbiType>, usize),340}341impl AbiType {342 fn try_from(value: &Type) -> syn::Result<Self> {343 let value = Self::try_maybe_special_from(value)?;344 if value.is_special() {345 return Err(syn::Error::new(value.span(), "unexpected special type"));346 }347 Ok(value)348 }349 fn try_maybe_special_from(value: &Type) -> syn::Result<Self> {350 match value {351 Type::Array(arr) => {352 let wrapped = AbiType::try_from(&arr.elem)?;353 match &arr.len {354 Expr::Lit(l) => match &l.lit {355 Lit::Int(i) => {356 let num = i.base10_parse::<usize>()?;357 Ok(AbiType::Array(Box::new(wrapped), num as usize))358 }359 _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),360 },361 _ => Err(syn::Error::new(arr.len.span(), "should be literal")),362 }363 }364 Type::Path(_) => {365 let path = parse_path(value)?;366 let segment = parse_path_segment(path)?;367 if segment.ident == "Vec" {368 let args = match &segment.arguments {369 PathArguments::AngleBracketed(e) => e,370 _ => {371 return Err(syn::Error::new(372 segment.arguments.span(),373 "missing Vec generic",374 ))375 }376 };377 let args = &args.args;378 if args.len() != 1 {379 return Err(syn::Error::new(380 args.span(),381 "expected only one generic for vec",382 ));383 }384 let arg = args.first().expect("first arg");385386 let ty = match arg {387 GenericArgument::Type(ty) => ty,388 _ => {389 return Err(syn::Error::new(390 arg.span(),391 "expected first generic to be type",392 ))393 }394 };395396 let wrapped = AbiType::try_from(ty)?;397 Ok(Self::Vec(Box::new(wrapped)))398 } else {399 if !segment.arguments.is_empty() {400 return Err(syn::Error::new(401 segment.arguments.span(),402 "unexpected generic arguments for non-vec type",403 ));404 }405 Ok(Self::Plain(segment.ident.clone()))406 }407 }408 Type::Tuple(t) => {409 let mut out = Vec::with_capacity(t.elems.len());410 for el in t.elems.iter() {411 out.push(AbiType::try_from(el)?)412 }413 Ok(Self::Tuple(out))414 }415 _ => Err(syn::Error::new(416 value.span(),417 "unexpected type, only arrays, plain types and tuples are supported",418 )),419 }420 }421 fn is_value(&self) -> bool {422 matches!(self, Self::Plain(v) if v == "value")423 }424 fn is_caller(&self) -> bool {425 matches!(self, Self::Plain(v) if v == "caller")426 }427 fn is_special(&self) -> bool {428 self.is_caller() || self.is_value()429 }430 fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {431 match self {432 AbiType::Plain(t) => {433 write!(buf, "{}", t)434 }435 AbiType::Tuple(t) => {436 write!(buf, "(")?;437 for (i, t) in t.iter().enumerate() {438 if i != 0 {439 write!(buf, ",")?;440 }441 t.selector_ty_buf(buf)?;442 }443 write!(buf, ")")444 }445 AbiType::Vec(v) => {446 v.selector_ty_buf(buf)?;447 write!(buf, "[]")448 }449 AbiType::Array(v, len) => {450 v.selector_ty_buf(buf)?;451 write!(buf, "[{}]", len)452 }453 }454 }455 fn selector_ty(&self) -> String {456 let mut out = String::new();457 self.selector_ty_buf(&mut out).expect("no fmt error");458 out459 }460}461impl ToTokens for AbiType {462 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {463 match self {464 AbiType::Plain(t) => tokens.extend(quote! {#t}),465 AbiType::Tuple(t) => {466 tokens.extend(quote! {(467 #(#t),*468 )});469 }470 AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),471 AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),472 }473 }474}475476struct MethodArg {477 name: Ident,478 camel_name: String,479 ty: AbiType,480}481impl MethodArg {482 fn try_from(value: &PatType) -> syn::Result<Self> {483 let name = parse_ident_from_pat(&value.pat)?.clone();484 Ok(Self {485 camel_name: cases::camelcase::to_camel_case(&name.to_string()),486 name,487 ty: AbiType::try_maybe_special_from(&value.ty)?,488 })489 }490 fn is_value(&self) -> bool {491 self.ty.is_value()492 }493 fn is_caller(&self) -> bool {494 self.ty.is_caller()495 }496 fn is_special(&self) -> bool {497 self.ty.is_special()498 }499 fn selector_ty(&self) -> String {500 assert!(!self.is_special());501 self.ty.selector_ty()502 }503504 fn expand_call_def(&self) -> proc_macro2::TokenStream {505 assert!(!self.is_special());506 let name = &self.name;507 let ty = &self.ty;508509 quote! {510 #name: #ty511 }512 }513514 fn expand_parse(&self) -> proc_macro2::TokenStream {515 assert!(!self.is_special());516 let name = &self.name;517 quote! {518 #name: reader.abi_read()?519 }520 }521522 fn expand_call_arg(&self) -> proc_macro2::TokenStream {523 if self.is_value() {524 quote! {525 c.value.clone()526 }527 } else if self.is_caller() {528 quote! {529 c.caller.clone()530 }531 } else {532 let name = &self.name;533 quote! {534 #name535 }536 }537 }538539 fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {540 let camel_name = &self.camel_name.to_string();541 let ty = &self.ty;542 quote! {543 <NamedArgument<#ty>>::new(#camel_name)544 }545 }546}547548#[derive(PartialEq)]549enum Mutability {550 Mutable,551 View,552 Pure,553}554555/// Group all keywords for this macro. Usage example:556/// #[solidity_interface(name = "B", inline_is(A))]557mod kw {558 syn::custom_keyword!(weight);559560 syn::custom_keyword!(via);561 syn::custom_keyword!(returns);562 syn::custom_keyword!(name);563 syn::custom_keyword!(is);564 syn::custom_keyword!(inline_is);565 syn::custom_keyword!(events);566 syn::custom_keyword!(expect_selector);567568 syn::custom_keyword!(rename_selector);569 syn::custom_keyword!(hide);570}571572/// Rust methods are parsed into this structure when Solidity code is generated573struct Method {574 name: Ident,575 camel_name: String,576 pascal_name: Ident,577 screaming_name: Ident,578 selector_str: String,579 selector: u32,580 hide: bool,581 args: Vec<MethodArg>,582 has_normal_args: bool,583 has_value_args: bool,584 mutability: Mutability,585 result: Type,586 weight: Option<Expr>,587 docs: Vec<String>,588}589impl Method {590 fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {591 let mut info = MethodInfo {592 rename_selector: None,593 hide: false,594 };595 let mut docs = Vec::new();596 let mut weight = None;597 for attr in &value.attrs {598 let ident = parse_ident_from_path(&attr.path, false)?;599 if ident == "solidity" {600 info = attr.parse_args::<MethodInfo>()?;601 } else if ident == "doc" {602 let args = attr.parse_meta().unwrap();603 let value = match args {604 Meta::NameValue(MetaNameValue {605 lit: Lit::Str(str), ..606 }) => str.value(),607 _ => unreachable!(),608 };609 docs.push(value);610 } else if ident == "weight" {611 weight = Some(attr.parse_args::<Expr>()?);612 }613 }614 let ident = &value.sig.ident;615 let ident_str = ident.to_string();616 if !cases::snakecase::is_snake_case(&ident_str) {617 return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));618 }619620 let mut mutability = Mutability::Pure;621622 if let Some(FnArg::Receiver(receiver)) = value623 .sig624 .inputs625 .iter()626 .find(|arg| matches!(arg, FnArg::Receiver(_)))627 {628 if receiver.reference.is_none() {629 return Err(syn::Error::new(630 receiver.span(),631 "receiver should be by ref",632 ));633 }634 if receiver.mutability.is_some() {635 mutability = Mutability::Mutable;636 } else {637 mutability = Mutability::View;638 }639 }640 let mut args = Vec::new();641 for typ in value642 .sig643 .inputs644 .iter()645 .filter(|arg| matches!(arg, FnArg::Typed(_)))646 {647 let typ = match typ {648 FnArg::Typed(typ) => typ,649 _ => unreachable!(),650 };651 args.push(MethodArg::try_from(typ)?);652 }653654 if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {655 return Err(syn::Error::new(656 args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),657 "payable function should be mutable",658 ));659 }660661 let result = match &value.sig.output {662 ReturnType::Type(_, ty) => ty,663 _ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),664 };665 let result = parse_result_ok(result)?;666667 let camel_name = info668 .rename_selector669 .unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));670 let mut selector_str = camel_name.clone();671 selector_str.push('(');672 let mut has_normal_args = false;673 for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {674 if i != 0 {675 selector_str.push(',');676 }677 write!(selector_str, "{}", arg.selector_ty()).unwrap();678 has_normal_args = true;679 }680 let has_value_args = args.iter().any(|a| a.is_value());681 selector_str.push(')');682 let selector = fn_selector_str(&selector_str);683684 Ok(Self {685 name: ident.clone(),686 camel_name,687 pascal_name: snake_ident_to_pascal(ident),688 screaming_name: snake_ident_to_screaming(ident),689 selector_str,690 selector,691 hide: info.hide,692 args,693 has_normal_args,694 has_value_args,695 mutability,696 result: result.clone(),697 weight,698 docs,699 })700 }701 fn expand_call_def(&self) -> proc_macro2::TokenStream {702 let defs = self703 .args704 .iter()705 .filter(|a| !a.is_special())706 .map(|a| a.expand_call_def());707 let pascal_name = &self.pascal_name;708 let docs = &self.docs;709710 if self.has_normal_args {711 quote! {712 #(#[doc = #docs])*713 #[allow(missing_docs)]714 #pascal_name {715 #(716 #defs,717 )*718 }719 }720 } else {721 quote! {#pascal_name}722 }723 }724725 fn expand_const(&self) -> proc_macro2::TokenStream {726 let screaming_name = &self.screaming_name;727 let selector = u32::to_be_bytes(self.selector);728 let selector_str = &self.selector_str;729 quote! {730 #[doc = #selector_str]731 const #screaming_name: ::evm_coder::types::bytes4 = [#(#selector,)*];732 }733 }734735 fn expand_interface_id(&self) -> proc_macro2::TokenStream {736 let screaming_name = &self.screaming_name;737 quote! {738 interface_id ^= u32::from_be_bytes(Self::#screaming_name);739 }740 }741742 fn expand_parse(&self) -> proc_macro2::TokenStream {743 let pascal_name = &self.pascal_name;744 let screaming_name = &self.screaming_name;745 if self.has_normal_args {746 let parsers = self747 .args748 .iter()749 .filter(|a| !a.is_special())750 .map(|a| a.expand_parse());751 quote! {752 Self::#screaming_name => return Ok(Some(Self::#pascal_name {753 #(754 #parsers,755 )*756 }))757 }758 } else {759 quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }760 }761 }762763 fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {764 let pascal_name = &self.pascal_name;765 let name = &self.name;766767 let matcher = if self.has_normal_args {768 let names = self769 .args770 .iter()771 .filter(|a| !a.is_special())772 .map(|a| &a.name);773774 quote! {{775 #(776 #names,777 )*778 }}779 } else {780 quote! {}781 };782783 let receiver = match self.mutability {784 Mutability::Mutable | Mutability::View => quote! {self.},785 Mutability::Pure => quote! {Self::},786 };787 let args = self.args.iter().map(|a| a.expand_call_arg());788789 quote! {790 #call_name::#pascal_name #matcher => {791 let result = #receiver #name(792 #(793 #args,794 )*795 )?;796 (&result).to_result()797 }798 }799 }800801 fn expand_variant_weight(&self) -> proc_macro2::TokenStream {802 let pascal_name = &self.pascal_name;803 if let Some(weight) = &self.weight {804 let matcher = if self.has_normal_args {805 let names = self806 .args807 .iter()808 .filter(|a| !a.is_special())809 .map(|a| &a.name);810811 quote! {{812 #(813 #names,814 )*815 }}816 } else {817 quote! {}818 };819 quote! {820 Self::#pascal_name #matcher => (#weight).into()821 }822 } else {823 let matcher = if self.has_normal_args {824 quote! {{..}}825 } else {826 quote! {}827 };828 quote! {829 Self::#pascal_name #matcher => ().into()830 }831 }832 }833834 fn expand_solidity_function(&self) -> proc_macro2::TokenStream {835 let camel_name = &self.camel_name;836 let mutability = match self.mutability {837 Mutability::Mutable => quote! {SolidityMutability::Mutable},838 Mutability::View => quote! { SolidityMutability::View },839 Mutability::Pure => quote! {SolidityMutability::Pure},840 };841 let result = &self.result;842843 let args = self844 .args845 .iter()846 .filter(|a| !a.is_special())847 .map(MethodArg::expand_solidity_argument);848 let docs = &self.docs;849 let selector_str = &self.selector_str;850 let selector = self.selector;851 let hide = self.hide;852 let is_payable = self.has_value_args;853 quote! {854 SolidityFunction {855 docs: &[#(#docs),*],856 selector_str: #selector_str,857 selector: #selector,858 hide: #hide,859 name: #camel_name,860 mutability: #mutability,861 is_payable: #is_payable,862 args: (863 #(864 #args,865 )*866 ),867 result: <UnnamedArgument<#result>>::default(),868 }869 }870 }871}872873fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {874 if gen.params.is_empty() {875 return quote! {};876 }877 let params = gen.params.iter().map(|p| match p {878 syn::GenericParam::Type(id) => {879 let v = &id.ident;880 quote! {#v}881 }882 syn::GenericParam::Lifetime(lt) => {883 let v = <.lifetime;884 quote! {#v}885 }886 syn::GenericParam::Const(c) => {887 let i = &c.ident;888 quote! {#i}889 }890 });891 quote! { #(#params),* }892}893fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {894 if gen.params.is_empty() {895 return quote! {};896 }897 let list = generics_list(gen);898 quote! { <#list> }899}900fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {901 let list = generics_list(gen);902 if gen.params.len() == 1 {903 quote! {#list}904 } else {905 quote! { (#list) }906 }907}908909pub struct SolidityInterface {910 generics: Generics,911 name: Box<syn::Type>,912 info: InterfaceInfo,913 methods: Vec<Method>,914 docs: Vec<String>,915}916impl SolidityInterface {917 pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {918 let mut methods = Vec::new();919920 for item in &value.items {921 if let ImplItem::Method(method) = item {922 methods.push(Method::try_from(method)?)923 }924 }925 let mut docs = vec![];926 for attr in &value.attrs {927 let ident = parse_ident_from_path(&attr.path, false)?;928 if ident == "doc" {929 let args = attr.parse_meta().unwrap();930 let value = match args {931 Meta::NameValue(MetaNameValue {932 lit: Lit::Str(str), ..933 }) => str.value(),934 _ => unreachable!(),935 };936 docs.push(value);937 }938 }939 Ok(Self {940 generics: value.generics.clone(),941 name: value.self_ty.clone(),942 info,943 methods,944 docs,945 })946 }947 pub fn expand(self) -> proc_macro2::TokenStream {948 let name = self.name;949950 let solidity_name = self.info.name.to_string();951 let call_name = pascal_ident_to_call(&self.info.name);952 let generics = self.generics;953 let gen_ref = generics_reference(&generics);954 let gen_data = generics_data(&generics);955 let gen_where = &generics.where_clause;956957 let call_sub = self958 .info959 .inline_is960 .0961 .iter()962 .chain(self.info.is.0.iter())963 .map(|c| Is::expand_call_def(c, &gen_ref));964 let call_parse = self965 .info966 .inline_is967 .0968 .iter()969 .chain(self.info.is.0.iter())970 .map(|is| Is::expand_parse(is, &gen_ref));971 let call_variants = self972 .info973 .inline_is974 .0975 .iter()976 .chain(self.info.is.0.iter())977 .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));978 let weight_variants = self979 .info980 .inline_is981 .0982 .iter()983 .chain(self.info.is.0.iter())984 .map(Is::expand_variant_weight);985986 let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);987 let supports_interface = self988 .info989 .is990 .0991 .iter()992 .map(|is| Is::expand_supports_interface(is, &gen_ref));993994 let calls = self.methods.iter().map(Method::expand_call_def);995 let consts = self.methods.iter().map(Method::expand_const);996 let interface_id = self.methods.iter().map(Method::expand_interface_id);997 let parsers = self.methods.iter().map(Method::expand_parse);998 let call_variants_this = self999 .methods1000 .iter()1001 .map(|m| Method::expand_variant_call(m, &call_name));1002 let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);1003 let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);10041005 // TODO: Inline inline_is1006 let solidity_is = self1007 .info1008 .is1009 .01010 .iter()1011 .chain(self.info.inline_is.0.iter())1012 .map(|is| is.name.to_string());1013 let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());1014 let solidity_generators = self1015 .info1016 .is1017 .01018 .iter()1019 .chain(self.info.inline_is.0.iter())1020 .map(|is| Is::expand_generator(is, &gen_ref));1021 let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);10221023 let docs = &self.docs;10241025 if let Some(expect_selector) = &self.info.expect_selector {1026 if !self.info.inline_is.0.is_empty() {1027 return syn::Error::new(1028 name.span(),1029 "expect_selector is not compatible with inline_is",1030 )1031 .to_compile_error();1032 }1033 let selector = self1034 .methods1035 .iter()1036 .map(|m| m.selector)1037 .fold(0, |a, b| a ^ b);10381039 if *expect_selector != selector {1040 let mut methods = String::new();1041 for meth in self.methods.iter() {1042 write!(methods, "\n- {}", meth.selector_str).expect("write to string");1043 }1044 return syn::Error::new(name.span(), format!("expected selector mismatch, expected {expect_selector:0>8x}, but implementation has {selector:0>8x}{methods}")).to_compile_error();1045 }1046 }1047 // let methods = self.methods.iter().map(Method::solidity_def);10481049 quote! {1050 #[derive(Debug)]1051 #(#[doc = #docs])*1052 pub enum #call_name #gen_ref {1053 /// Inherited method1054 ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),1055 #(1056 #calls,1057 )*1058 #(1059 #call_sub,1060 )*1061 }1062 impl #gen_ref #call_name #gen_ref {1063 #(1064 #consts1065 )*1066 /// Return this call ERC165 selector1067 pub fn interface_id() -> ::evm_coder::types::bytes4 {1068 let mut interface_id = 0;1069 #(#interface_id)*1070 #(#inline_interface_id)*1071 u32::to_be_bytes(interface_id)1072 }1073 /// Generate solidity definitions for methods described in this interface1074 pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {1075 use evm_coder::solidity::*;1076 use core::fmt::Write;1077 let interface = SolidityInterface {1078 docs: &[#(#docs),*],1079 name: #solidity_name,1080 selector: Self::interface_id(),1081 is: &["Dummy", "ERC165", #(1082 #solidity_is,1083 )* #(1084 #solidity_events_is,1085 )* ],1086 functions: (#(1087 #solidity_functions,1088 )*),1089 };10901091 let mut out = ::evm_coder::types::string::new();1092 if #solidity_name.starts_with("Inline") {1093 out.push_str("/// @dev inlined interface\n");1094 }1095 let _ = interface.format(is_impl, &mut out, tc);1096 tc.collect(out);1097 #(1098 #solidity_event_generators1099 )*1100 #(1101 #solidity_generators1102 )*1103 if is_impl {1104 tc.collect("/// @dev common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());1105 } else {1106 tc.collect("/// @dev common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());1107 }1108 }1109 }1110 impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1111 fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1112 use ::evm_coder::abi::AbiRead;1113 match method_id {1114 ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1115 ::evm_coder::ERC165Call::parse(method_id, reader)?1116 .map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1117 ),1118 #(1119 #parsers,1120 )*1121 _ => {},1122 }1123 #(1124 #call_parse1125 )else*1126 return Ok(None);1127 }1128 }1129 impl #generics #call_name #gen_ref1130 #gen_where1131 {1132 /// Is this contract implements specified ERC165 selector1133 pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1134 interface_id != u32::to_be_bytes(0xffffff) && (1135 interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1136 interface_id == Self::interface_id()1137 #(1138 || #supports_interface1139 )*1140 )1141 }1142 }1143 impl #generics ::evm_coder::Weighted for #call_name #gen_ref1144 #gen_where1145 {1146 #[allow(unused_variables)]1147 fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1148 match self {1149 #(1150 #weight_variants,1151 )*1152 // TODO: It should be very cheap, but not free1153 Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1154 #(1155 #weight_variants_this,1156 )*1157 }1158 }1159 }1160 impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1161 #gen_where1162 {1163 #[allow(unreachable_code)] // In case of no inner calls1164 fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1165 use ::evm_coder::abi::AbiWrite;1166 match c.call {1167 #(1168 #call_variants,1169 )*1170 #call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1171 let mut writer = ::evm_coder::abi::AbiWriter::default();1172 writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1173 return Ok(writer.into());1174 }1175 _ => {},1176 }1177 let mut writer = ::evm_coder::abi::AbiWriter::default();1178 match c.call {1179 #(1180 #call_variants_this,1181 )*1182 _ => Err(::evm_coder::execution::Error::from("method is not available").into()),1183 }1184 }1185 }1186 }1187 }1188}crates/evm-coder/procedural/src/to_log.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/to_log.rs
+++ b/crates/evm-coder/procedural/src/to_log.rs
@@ -195,6 +195,8 @@
#consts
)*
+ /// Generate solidity definitions for methods described in this interface
+ #[cfg(feature = "stubgen")]
pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {
use evm_coder::solidity::*;
use core::fmt::Write;
crates/evm-coder/src/abi.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi.rs
+++ b/crates/evm-coder/src/abi.rs
@@ -26,6 +26,8 @@
use crate::{
execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},
types::*,
+ make_signature,
+ custom_signature::{SignatureUnit},
};
use crate::execution::Result;
@@ -340,18 +342,18 @@
}
}
-/// [`AbiReader`] implements reading of many types, but it should
-/// be limited to types defined in spec
-///
-/// As this trait can't be made sealed,
-/// instead of having `impl AbiRead for T`, we have `impl AbiRead<T> for AbiReader`
-pub trait AbiRead<T> {
+/// [`AbiReader`] implements reading of many types.
+pub trait AbiRead {
/// Read item from current position, advanding decoder
- fn abi_read(&mut self) -> Result<T>;
+ fn abi_read(reader: &mut AbiReader) -> Result<Self>
+ where
+ Self: Sized;
}
macro_rules! impl_abi_readable {
($ty:ty, $method:ident, $dynamic:literal) => {
+ impl sealed::CanBePlacedInVec for $ty {}
+
impl TypeHelper for $ty {
fn is_dynamic() -> bool {
$dynamic
@@ -361,16 +363,16 @@
ABI_ALIGNMENT
}
}
- impl AbiRead<$ty> for AbiReader<'_> {
- fn abi_read(&mut self) -> Result<$ty> {
- self.$method()
+
+ impl AbiRead for $ty {
+ fn abi_read(reader: &mut AbiReader) -> Result<$ty> {
+ reader.$method()
}
}
};
}
impl_abi_readable!(bool, bool, false);
-impl_abi_readable!(uint8, uint8, false);
impl_abi_readable!(uint32, uint32, false);
impl_abi_readable!(uint64, uint64, false);
impl_abi_readable!(uint128, uint128, false);
@@ -378,8 +380,21 @@
impl_abi_readable!(bytes4, bytes4, false);
impl_abi_readable!(address, address, false);
impl_abi_readable!(string, string, true);
-// impl_abi_readable!(bytes, bytes, true);
+impl TypeHelper for uint8 {
+ fn is_dynamic() -> bool {
+ false
+ }
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+impl AbiRead for uint8 {
+ fn abi_read(reader: &mut AbiReader) -> Result<uint8> {
+ reader.uint8()
+ }
+}
+
impl TypeHelper for bytes {
fn is_dynamic() -> bool {
true
@@ -388,9 +403,9 @@
ABI_ALIGNMENT
}
}
-impl AbiRead<bytes> for AbiReader<'_> {
- fn abi_read(&mut self) -> Result<bytes> {
- Ok(bytes(self.bytes()?))
+impl AbiRead for bytes {
+ fn abi_read(reader: &mut AbiReader) -> Result<bytes> {
+ Ok(bytes(reader.bytes()?))
}
}
@@ -399,26 +414,57 @@
pub trait CanBePlacedInVec {}
}
-impl sealed::CanBePlacedInVec for U256 {}
-impl sealed::CanBePlacedInVec for string {}
-impl sealed::CanBePlacedInVec for H160 {}
-
-impl<R: sealed::CanBePlacedInVec> AbiRead<Vec<R>> for AbiReader<'_>
-where
- Self: AbiRead<R>,
-{
- fn abi_read(&mut self) -> Result<Vec<R>> {
- let mut sub = self.subresult(None)?;
+impl<R: AbiRead + sealed::CanBePlacedInVec> AbiRead for Vec<R> {
+ fn abi_read(reader: &mut AbiReader) -> Result<Vec<R>> {
+ let mut sub = reader.subresult(None)?;
let size = sub.uint32()? as usize;
sub.subresult_offset = sub.offset;
let mut out = Vec::with_capacity(size);
for _ in 0..size {
- out.push(<Self as AbiRead<R>>::abi_read(&mut sub)?);
+ out.push(<R>::abi_read(&mut sub)?);
}
Ok(out)
}
}
+impl<R: Signature> Signature for Vec<R> {
+ const SIGNATURE: SignatureUnit = make_signature!(new nameof(R::SIGNATURE) fixed("[]"));
+}
+
+impl sealed::CanBePlacedInVec for EthCrossAccount {}
+
+impl TypeHelper for EthCrossAccount {
+ fn is_dynamic() -> bool {
+ address::is_dynamic() || uint256::is_dynamic()
+ }
+
+ fn size() -> usize {
+ <address as TypeHelper>::size() + <uint256 as TypeHelper>::size()
+ }
+}
+
+impl AbiRead for EthCrossAccount {
+ fn abi_read(reader: &mut AbiReader) -> Result<EthCrossAccount> {
+ let size = if !EthCrossAccount::is_dynamic() {
+ Some(<EthCrossAccount as TypeHelper>::size())
+ } else {
+ None
+ };
+ let mut subresult = reader.subresult(size)?;
+ let eth = <address>::abi_read(&mut subresult)?;
+ let sub = <uint256>::abi_read(&mut subresult)?;
+
+ Ok(EthCrossAccount { eth, sub })
+ }
+}
+
+impl AbiWrite for EthCrossAccount {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ self.eth.abi_write(writer);
+ self.sub.abi_write(writer);
+ }
+}
+
macro_rules! impl_tuples {
($($ident:ident)+) => {
impl<$($ident: TypeHelper,)+> TypeHelper for ($($ident,)+)
@@ -438,22 +484,23 @@
0 $(+ <$ident>::size())+
}
}
+
impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}
- impl<$($ident),+> AbiRead<($($ident,)+)> for AbiReader<'_>
+
+ impl<$($ident),+> AbiRead for ($($ident,)+)
where
- $(
- Self: AbiRead<$ident>,
- )+
+ $($ident: AbiRead,)+
($($ident,)+): TypeHelper,
{
- fn abi_read(&mut self) -> Result<($($ident,)+)> {
+ fn abi_read(reader: &mut AbiReader) -> Result<($($ident,)+)> {
let size = if !<($($ident,)+)>::is_dynamic() { Some(<($($ident,)+)>::size()) } else { None };
- let mut subresult = self.subresult(size)?;
+ let mut subresult = reader.subresult(size)?;
Ok((
- $(<Self as AbiRead<$ident>>::abi_read(&mut subresult)?,)+
+ $(<$ident>::abi_read(&mut subresult)?,)+
))
}
}
+
#[allow(non_snake_case)]
impl<$($ident),+> AbiWrite for ($($ident,)+)
where
@@ -470,6 +517,18 @@
}
}
}
+
+ impl<$($ident),+> Signature for ($($ident,)+)
+ where
+ $($ident: Signature,)+
+ {
+ const SIGNATURE: SignatureUnit = make_signature!(
+ new fixed("(")
+ $(nameof(<$ident>::SIGNATURE) fixed(","))+
+ shift_left(1)
+ fixed(")")
+ );
+ }
};
}
@@ -630,7 +689,7 @@
let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
assert_eq!(call, u32::to_be_bytes(function_identifier));
- let data = <AbiReader<'_> as AbiRead<$type>>::abi_read(&mut decoder).unwrap();
+ let data = <$type>::abi_read(&mut decoder).unwrap();
assert_eq!(data, decoded_data);
let mut writer = AbiWriter::new_call(function_identifier);
@@ -699,13 +758,13 @@
1ACF2D55
0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
-
+
0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
000000000000000000000000000000000000000000000000000000000000000A // uint256
-
+
000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
0000000000000000000000000000000000000000000000000000000000000014 // uint256
-
+
0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
000000000000000000000000000000000000000000000000000000000000001E // uint256
"
@@ -836,8 +895,7 @@
let (call, mut decoder) = AbiReader::new_call(encoded_data).unwrap();
assert_eq!(call, u32::to_be_bytes(decoded_data.0));
let address = decoder.address().unwrap();
- let data =
- <AbiReader<'_> as AbiRead<Vec<(uint256, string)>>>::abi_read(&mut decoder).unwrap();
+ let data = <Vec<(uint256, string)>>::abi_read(&mut decoder).unwrap();
assert_eq!(data, decoded_data.1);
let mut writer = AbiWriter::new_call(decoded_data.0);
crates/evm-coder/src/custom_signature.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/src/custom_signature.rs
@@ -0,0 +1,326 @@
+//! # A module for custom signature support.
+//!
+//! ## Overview
+//! This module allows you to create arbitrary signatures for types and functions in compile time.
+//!
+//! ### Type signatures
+//! To create the desired type signature, you need to create your own trait with the `SIGNATURE` constant.
+//! Then in the implementation, for the required type, use the macro [`make_signature`]
+//! #### Example
+//! ```
+//! use std::str::from_utf8;
+//! use evm_coder::{custom_signature::SignatureUnit, make_signature};
+//!
+//! // Create trait for our signature
+//! trait SoliditySignature {
+//! const SIGNATURE: SignatureUnit;
+//!
+//! fn name() -> &'static str {
+//! from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+//! }
+//! }
+//!
+//! // Make signatures for some types
+//! impl SoliditySignature for u8 {
+//! const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint8"));
+//! }
+//! impl SoliditySignature for u32 {
+//! const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint32"));
+//! }
+//! impl<T: SoliditySignature> SoliditySignature for Vec<T> {
+//! const SIGNATURE: SignatureUnit = make_signature!(new nameof(T::SIGNATURE) fixed("[]"));
+//! }
+//! impl<A: SoliditySignature, B: SoliditySignature> SoliditySignature for (A, B) {
+//! const SIGNATURE: SignatureUnit = make_signature!(new fixed("(") nameof(A::SIGNATURE) fixed(",") nameof(B::SIGNATURE) fixed(")"));
+//! }
+//! impl<A: SoliditySignature> SoliditySignature for (A,) {
+//! const SIGNATURE: SignatureUnit = make_signature!(new fixed("(") nameof(A::SIGNATURE) fixed(",") shift_left(1) fixed(")"));
+//! }
+//!
+//! assert_eq!(u8::name(), "uint8");
+//! assert_eq!(<Vec<u8>>::name(), "uint8[]");
+//! assert_eq!(<(u32, u8)>::name(), "(uint32,uint8)");
+//! ```
+//!
+//! ### Function signatures
+//! To create a function signature, the macro [`make_signature`] is also used, which accepts
+//! settings for the function format [`SignaturePreferences`] and function parameters [`SignatureUnit`]
+//! #### Example
+//! ```
+//! use core::str::from_utf8;
+//! use evm_coder::{custom_signature::SignatureUnit, make_signature};
+//! // Trait for our signature
+//! trait SoliditySignature {
+//! const SIGNATURE: SignatureUnit;
+//!
+//! fn name() -> &'static str {
+//! from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+//! }
+//! }
+//!
+//! // Make signatures for some types
+//! impl SoliditySignature for u8 {
+//! const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint8"));
+//! }
+//! impl<T: SoliditySignature> SoliditySignature for Vec<T> {
+//! const SIGNATURE: SignatureUnit = make_signature!(new nameof(T::SIGNATURE) fixed("[]"));
+//! }
+//! ```
+
+/// The maximum length of the signature.
+pub const SIGNATURE_SIZE_LIMIT: usize = 256;
+
+/// Storage for the signature or its elements.
+#[derive(Debug)]
+pub struct SignatureUnit {
+ /// Signature data.
+ pub data: [u8; SIGNATURE_SIZE_LIMIT],
+ /// The actual size of the data.
+ pub len: usize,
+}
+
+impl SignatureUnit {
+ /// Create a signature from `&str'.
+ pub const fn new(name: &'static str) -> SignatureUnit {
+ 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));
+ SignatureUnit {
+ data: signature,
+ len: name_len,
+ }
+ }
+ /// String conversion
+ pub fn as_str(&self) -> Option<&str> {
+ core::str::from_utf8(&self.data[0..self.len]).ok()
+ }
+}
+
+/// ### Macro to create signatures of types and functions.
+///
+/// Format for creating a type of signature:
+/// ```ignore
+/// make_signature!(new fixed("uint8")); // Simple type
+/// make_signature!(new fixed("(") nameof(u8) fixed(",") nameof(u8) fixed(")")); // Composite type
+/// ```
+#[macro_export]
+macro_rules! make_signature {
+ (new $($tt:tt)*) => {
+ ($crate::custom_signature::SignatureUnit {
+ data: {
+ let mut out = [0u8; $crate::custom_signature::SIGNATURE_SIZE_LIMIT];
+ let mut dst_offset = 0;
+ $crate::make_signature!(@data(out, dst_offset); $($tt)*);
+ out
+ },
+ len: {0 + $crate::make_signature!(@size; $($tt)*)},
+ })
+ };
+
+ (@size;) => {
+ 0
+ };
+ (@size; fixed($expr:expr) $($tt:tt)*) => {
+ $expr.len() + $crate::make_signature!(@size; $($tt)*)
+ };
+ (@size; nameof($expr:expr) $($tt:tt)*) => {
+ $expr.len + $crate::make_signature!(@size; $($tt)*)
+ };
+ (@size; numof($expr:expr) $($tt:tt)*) => {
+ {
+ let mut out = 0;
+ let mut v = $expr;
+ if v == 0 {
+ out = 1;
+ } else {
+ while v > 0 {
+ out += 1;
+ v /= 10;
+ }
+ }
+ out
+ } + $crate::make_signature!(@size; $($tt)*)
+ };
+ (@size; shift_left($expr:expr) $($tt:tt)*) => {
+ $crate::make_signature!(@size; $($tt)*) - $expr
+ };
+
+ (@data($dst:ident, $dst_offset:ident);) => {};
+ (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
+ {
+ let data = $expr.as_bytes();
+ let data_len = data.len();
+ $crate::make_signature!(@copy(data, $dst, data_len, $dst_offset));
+ }
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+ (@data($dst:ident, $dst_offset:ident); nameof($expr:expr) $($tt:tt)*) => {
+ {
+ $crate::make_signature!(@copy(&$expr.data, $dst, $expr.len, $dst_offset));
+ }
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+ (@data($dst:ident, $dst_offset:ident); numof($expr:expr) $($tt:tt)*) => {
+ {
+ let mut v = $expr;
+ let mut need_to_swap = 0;
+ if v == 0 {
+ $dst[$dst_offset] = b'0';
+ $dst_offset += 1;
+ } else {
+ while v > 0 {
+ let n = (v % 10) as u8;
+ $dst[$dst_offset] = b'0' + n;
+ v /= 10;
+ need_to_swap += 1;
+ $dst_offset += 1;
+ }
+ }
+ let mut i = 0;
+ #[allow(clippy::manual_swap)]
+ while i < need_to_swap / 2 {
+ let a = $dst_offset - i - 1;
+ let b = $dst_offset - need_to_swap + i;
+ let v = $dst[a];
+ $dst[a] = $dst[b];
+ $dst[b] = v;
+ i += 1;
+ }
+ }
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+ (@data($dst:ident, $dst_offset:ident); shift_left($expr:expr) $($tt:tt)*) => {
+ $dst_offset -= $expr;
+ $crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+ };
+
+ (@copy($src:expr, $dst:expr, $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 super::{SIGNATURE_SIZE_LIMIT, SignatureUnit};
+
+ trait Name {
+ const NAME: SignatureUnit;
+
+ fn name() -> &'static str {
+ from_utf8(&Self::NAME.data[..Self::NAME.len]).expect("bad utf-8")
+ }
+ }
+
+ impl Name for u8 {
+ const NAME: SignatureUnit = make_signature!(new fixed("uint8"));
+ }
+ impl Name for u32 {
+ const NAME: SignatureUnit = make_signature!(new fixed("uint32"));
+ }
+ impl<T: Name> Name for Vec<T> {
+ const NAME: SignatureUnit = make_signature!(new nameof(T::NAME) fixed("[]"));
+ }
+ impl<A: Name, B: Name> Name for (A, B) {
+ const NAME: SignatureUnit =
+ make_signature!(new fixed("(") nameof(A::NAME) fixed(",") nameof(B::NAME) fixed(")"));
+ }
+ impl<A: Name> Name for (A,) {
+ const NAME: SignatureUnit =
+ make_signature!(new fixed("(") nameof(A::NAME) fixed(",") shift_left(1) fixed(")"));
+ }
+ impl<A: Name, const SIZE: usize> Name for [A; SIZE] {
+ const NAME: SignatureUnit =
+ make_signature!(new nameof(A::NAME) fixed("[") numof(SIZE) fixed("]"));
+ }
+
+ struct MaxSize();
+ impl Name for MaxSize {
+ const NAME: SignatureUnit = SignatureUnit {
+ data: [b'!'; SIGNATURE_SIZE_LIMIT],
+ len: 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));
+ }
+
+ #[test]
+ fn shift() {
+ assert_eq!(<(u32,)>::name(), "(uint32)");
+ }
+
+ #[test]
+ fn num() {
+ assert_eq!(<[u8; 0]>::name(), "uint8[0]");
+ assert_eq!(<[u8; 1234]>::name(), "uint8[1234]");
+ assert_eq!(<[u8; 12345]>::name(), "uint8[12345]");
+ }
+
+ #[test]
+ fn over_max_size() {
+ let t = trybuild::TestCases::new();
+ t.compile_fail("tests/build_failed/custom_signature_over_max_size.rs");
+ }
+}
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -16,6 +16,7 @@
#![doc = include_str!("../README.md")]
#![deny(missing_docs)]
+#![macro_use]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
extern crate alloc;
@@ -26,6 +27,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.
@@ -90,6 +93,7 @@
pub use evm_coder_procedural::solidity;
/// See [`solidity_interface`]
pub use evm_coder_procedural::weight;
+pub use sha3_const;
/// Derives [`ToLog`] for enum
///
@@ -104,6 +108,7 @@
#[doc(hidden)]
pub mod events;
#[doc(hidden)]
+#[cfg(feature = "stubgen")]
pub mod solidity;
/// Solidity type definitions (aliases from solidity name to rust type)
@@ -114,28 +119,55 @@
#[cfg(not(feature = "std"))]
use alloc::{vec::Vec};
+ use pallet_evm::account::CrossAccountId;
use primitive_types::{U256, H160, H256};
+ use core::str::from_utf8;
+
+ use crate::custom_signature::SignatureUnit;
+
+ pub trait Signature {
+ const SIGNATURE: SignatureUnit;
+
+ fn as_str() -> &'static str {
+ from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+ }
+ }
+
+ impl Signature for bool {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bool"));
+ }
- pub type address = H160;
+ macro_rules! define_simple_type {
+ (type $ident:ident = $ty:ty) => {
+ pub type $ident = $ty;
+ impl Signature for $ty {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ident)));
+ }
+ };
+ }
- pub type uint8 = u8;
- pub type uint16 = u16;
- pub type uint32 = u32;
- pub type uint64 = u64;
- pub type uint128 = u128;
- pub type uint256 = U256;
+ define_simple_type!(type address = H160);
- pub type bytes4 = [u8; 4];
+ 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]);
- pub type topic = H256;
+ 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 {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));
+ }
/// Solidity doesn't have `void` type, however we have special implementation
/// for empty tuple return type
@@ -166,6 +198,7 @@
}
}
+ #[allow(clippy::from_over_into)]
impl Into<Vec<u8>> for bytes {
fn into(self) -> Vec<u8> {
self.0
@@ -183,6 +216,76 @@
self.len() == 0
}
}
+
+ #[derive(Debug, Default)]
+ pub struct EthCrossAccount {
+ pub(crate) eth: address,
+ pub(crate) sub: uint256,
+ }
+
+ impl EthCrossAccount {
+ pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self
+ where
+ T: pallet_evm::account::Config,
+ T::AccountId: AsRef<[u8; 32]>,
+ {
+ if cross_account_id.is_canonical_substrate() {
+ Self {
+ eth: Default::default(),
+ sub: convert_cross_account_to_uint256::<T>(cross_account_id),
+ }
+ } else {
+ Self {
+ eth: *cross_account_id.as_eth(),
+ sub: Default::default(),
+ }
+ }
+ }
+
+ pub fn into_sub_cross_account<T>(&self) -> crate::execution::Result<T::CrossAccountId>
+ where
+ T: pallet_evm::account::Config,
+ T::AccountId: From<[u8; 32]>,
+ {
+ if self.eth == Default::default() && self.sub == Default::default() {
+ Err("All fields of cross account is zeroed".into())
+ } else if self.eth == Default::default() {
+ Ok(convert_uint256_to_cross_account::<T>(self.sub))
+ } else if self.sub == Default::default() {
+ Ok(T::CrossAccountId::from_eth(self.eth))
+ } else {
+ Err("All fields of cross account is non zeroed".into())
+ }
+ }
+ }
+
+ impl Signature for EthCrossAccount {
+ const SIGNATURE: SignatureUnit = make_signature!(new fixed("(address,uint256)"));
+ }
+
+ /// Convert `CrossAccountId` to `uint256`.
+ pub fn convert_cross_account_to_uint256<T: pallet_evm::account::Config>(
+ from: &T::CrossAccountId,
+ ) -> uint256
+ where
+ T::AccountId: AsRef<[u8; 32]>,
+ {
+ let slice = from.as_sub().as_ref();
+ uint256::from_big_endian(slice)
+ }
+
+ /// Convert `uint256` to `CrossAccountId`.
+ pub fn convert_uint256_to_cross_account<T: pallet_evm::account::Config>(
+ from: uint256,
+ ) -> T::CrossAccountId
+ where
+ T::AccountId: From<[u8; 32]>,
+ {
+ let mut new_admin_arr = [0_u8; 32];
+ from.to_big_endian(&mut new_admin_arr);
+ let account_id = T::AccountId::from(new_admin_arr);
+ T::CrossAccountId::from_sub(account_id)
+ }
}
/// Parseable EVM call, this trait should be implemented with [`solidity_interface`] macro
@@ -239,7 +342,7 @@
return Ok(None);
}
Ok(Some(Self::SupportsInterface {
- interface_id: input.abi_read()?,
+ interface_id: types::bytes4::abi_read(input)?,
}))
}
}
@@ -252,6 +355,7 @@
#[macro_export]
macro_rules! generate_stubgen {
($name:ident, $decl:ty, $is_impl:literal) => {
+ #[cfg(feature = "stubgen")]
#[test]
#[ignore]
fn $name() {
crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -32,7 +32,7 @@
cmp::Reverse,
};
use impl_trait_for_tuples::impl_for_tuples;
-use crate::types::*;
+use crate::{types::*, custom_signature::SignatureUnit};
#[derive(Default)]
pub struct TypeCollector {
@@ -72,6 +72,10 @@
self.anonymous.borrow_mut().insert(names, id);
format!("Tuple{}", id)
}
+ pub fn collect_struct<T: StructCollect>(&self) -> String {
+ self.collect(<T as StructCollect>::declaration());
+ <T as StructCollect>::name()
+ }
pub fn finish(self) -> Vec<string> {
let mut data = self.structs.into_inner().into_iter().collect::<Vec<_>>();
data.sort_by_key(|(_, id)| Reverse(*id));
@@ -79,6 +83,13 @@
}
}
+pub trait StructCollect: 'static {
+ /// Structure name.
+ fn name() -> String;
+ /// Structure declaration.
+ fn declaration() -> String;
+}
+
pub trait SolidityTypeName: 'static {
fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;
/// "simple" types are stored inline, no `memory` modifier should be used in solidity
@@ -145,6 +156,7 @@
impl sealed::CanBePlacedInVec for uint256 {}
impl sealed::CanBePlacedInVec for string {}
impl sealed::CanBePlacedInVec for address {}
+impl sealed::CanBePlacedInVec for EthCrossAccount {}
impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {
fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
@@ -161,6 +173,60 @@
}
}
+impl SolidityTupleType for EthCrossAccount {
+ fn names(tc: &TypeCollector) -> Vec<string> {
+ let mut collected = Vec::with_capacity(Self::len());
+ {
+ let mut out = string::new();
+ address::solidity_name(&mut out, tc).expect("no fmt error");
+ collected.push(out);
+ }
+ {
+ let mut out = string::new();
+ uint256::solidity_name(&mut out, tc).expect("no fmt error");
+ collected.push(out);
+ }
+ collected
+ }
+
+ fn len() -> usize {
+ 2
+ }
+}
+impl SolidityTypeName for EthCrossAccount {
+ fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
+ write!(writer, "{}", tc.collect_struct::<Self>())
+ }
+
+ fn is_simple() -> bool {
+ false
+ }
+
+ fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
+ write!(writer, "{}(", tc.collect_struct::<Self>())?;
+ address::solidity_default(writer, tc)?;
+ write!(writer, ",")?;
+ uint256::solidity_default(writer, tc)?;
+ write!(writer, ")")
+ }
+}
+
+impl StructCollect for EthCrossAccount {
+ fn name() -> String {
+ "EthCrossAccount".into()
+ }
+
+ fn declaration() -> String {
+ let mut str = String::new();
+ writeln!(str, "/// @dev Cross account struct").unwrap();
+ writeln!(str, "struct {} {{", Self::name()).unwrap();
+ writeln!(str, "\taddress eth;").unwrap();
+ writeln!(str, "\tuint256 sub;").unwrap();
+ writeln!(str, "}}").unwrap();
+ str
+ }
+}
+
pub trait SolidityTupleType {
fn names(tc: &TypeCollector) -> Vec<String>;
fn len() -> usize;
@@ -418,9 +484,9 @@
}
pub struct SolidityFunction<A, R> {
pub docs: &'static [&'static str],
- pub selector_str: &'static str,
pub selector: u32,
pub hide: bool,
+ pub custom_signature: SignatureUnit,
pub name: &'static str,
pub args: A,
pub result: R,
@@ -446,7 +512,7 @@
writeln!(
writer,
"\t{hide_comment}/// or in textual repr: {}",
- self.selector_str
+ self.custom_signature.as_str().expect("bad utf-8")
)?;
write!(writer, "\t{hide_comment}function {}(", self.name)?;
self.args.solidity_name(writer, tc)?;
crates/evm-coder/tests/build_failed/custom_signature_over_max_size.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/tests/build_failed/custom_signature_over_max_size.rs
@@ -0,0 +1,34 @@
+#![allow(dead_code)]
+use std::str::from_utf8;
+
+use evm_coder::{
+ make_signature,
+ custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT},
+};
+
+trait Name {
+ const SIGNATURE: SignatureUnit;
+
+ fn name() -> &'static str {
+ from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+ }
+}
+
+impl<T: Name> Name for Vec<T> {
+ const SIGNATURE: SignatureUnit =
+ evm_coder::make_signature!(new nameof(T::SIGNATURE) fixed("[]"));
+}
+
+struct MaxSize();
+impl Name for MaxSize {
+ const SIGNATURE: SignatureUnit = SignatureUnit {
+ data: [b'!'; SIGNATURE_SIZE_LIMIT],
+ len: SIGNATURE_SIZE_LIMIT,
+ };
+}
+
+const NAME: SignatureUnit = <Vec<MaxSize>>::SIGNATURE;
+
+fn main() {
+ assert!(false);
+}
crates/evm-coder/tests/build_failed/custom_signature_over_max_size.stderrdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/tests/build_failed/custom_signature_over_max_size.stderr
@@ -0,0 +1,29 @@
+warning: unused import: `make_signature`
+ --> tests/build_failed/custom_signature_over_max_size.rs:5:2
+ |
+5 | make_signature,
+ | ^^^^^^^^^^^^^^
+ |
+ = note: `#[warn(unused_imports)]` on by default
+
+error: any use of this value will cause an error
+ --> tests/build_failed/custom_signature_over_max_size.rs:19:3
+ |
+18 | const SIGNATURE: SignatureUnit =
+ | ------------------------------
+19 | evm_coder::make_signature!(new nameof(T::SIGNATURE) fixed("[]"));
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ index out of bounds: the length is 256 but the index is 256
+ |
+ = note: `#[deny(const_err)]` on by default
+ = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+ = note: for more information, see issue #71800 <https://github.com/rust-lang/rust/issues/71800>
+ = note: this error originates in the macro `$crate::make_signature` which comes from the expansion of the macro `evm_coder::make_signature` (in Nightly builds, run with -Z macro-backtrace for more info)
+
+error: any use of this value will cause an error
+ --> tests/build_failed/custom_signature_over_max_size.rs:30:29
+ |
+30 | const NAME: SignatureUnit = <Vec<MaxSize>>::SIGNATURE;
+ | ------------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^ referenced constant has errors
+ |
+ = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+ = note: for more information, see issue #71800 <https://github.com/rust-lang/rust/issues/71800>
crates/evm-coder/tests/random.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/random.rs
+++ b/crates/evm-coder/tests/random.rs
@@ -17,6 +17,7 @@
#![allow(dead_code)] // This test only checks that macros is not panicking
use evm_coder::{ToLog, execution::Result, solidity_interface, types::*, solidity, weight};
+use evm_coder::{types::Signature};
pub struct Impls;
crates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/solidity_generation.rs
+++ b/crates/evm-coder/tests/solidity_generation.rs
@@ -15,6 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
+use evm_coder::{types::Signature};
pub struct ERC20;
pallets/common/CHANGELOG.mddiffbeforeafterboth--- a/pallets/common/CHANGELOG.md
+++ b/pallets/common/CHANGELOG.md
@@ -2,6 +2,10 @@
All notable changes to this project will be documented in this file.
+## [0.1.10] - 2022-11-02
+### Changed
+ - Use named structure `EthCrossAccount` in eth functions.
+
## [0.1.9] - 2022-10-13
## Added
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-common"
-version = "0.1.9"
+version = "0.1.10"
license = "GPLv3"
edition = "2021"
@@ -45,3 +45,4 @@
"up-data-structs/runtime-benchmarks",
]
try-runtime = ["frame-support/try-runtime"]
+stubgen = ["evm-coder/stubgen"]
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -33,11 +33,7 @@
use crate::{
Pallet, CollectionHandle, Config, CollectionProperties, SelfWeightOf,
- eth::{
- convert_cross_account_to_uint256, convert_cross_account_to_tuple,
- convert_tuple_to_cross_account,
- },
- weights::WeightInfo,
+ eth::convert_cross_account_to_uint256, weights::WeightInfo,
};
/// Events for ethereum collection helper.
@@ -64,6 +60,7 @@
/// Does not always represent a full collection, for RFT it is either
/// collection (Implementing ERC721), or specific collection token (Implementing ERC20).
pub trait CommonEvmHandler {
+ /// Raw compiled binary code of the contract stub
const CODE: &'static [u8];
/// Call precompiled handle.
@@ -229,13 +226,13 @@
fn set_collection_sponsor_cross(
&mut self,
caller: caller,
- sponsor: (address, uint256),
+ sponsor: EthCrossAccount,
) -> Result<void> {
self.consume_store_reads_and_writes(1, 1)?;
check_is_owner_or_admin(caller, self)?;
- let sponsor = convert_tuple_to_cross_account::<T>(sponsor)?;
+ let sponsor = sponsor.into_sub_cross_account::<T>()?;
self.set_sponsor(sponsor.as_sub().clone())
.map_err(dispatch_to_evm::<T>)?;
save(self)
@@ -386,12 +383,12 @@
fn add_collection_admin_cross(
&mut self,
caller: caller,
- new_admin: (address, uint256),
+ new_admin: EthCrossAccount,
) -> Result<void> {
self.consume_store_writes(2)?;
let caller = T::CrossAccountId::from_eth(caller);
- let new_admin = convert_tuple_to_cross_account::<T>(new_admin)?;
+ let new_admin = new_admin.into_sub_cross_account::<T>()?;
<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -401,12 +398,12 @@
fn remove_collection_admin_cross(
&mut self,
caller: caller,
- admin: (address, uint256),
+ admin: EthCrossAccount,
) -> Result<void> {
self.consume_store_writes(2)?;
let caller = T::CrossAccountId::from_eth(caller);
- let admin = convert_tuple_to_cross_account::<T>(admin)?;
+ let admin = admin.into_sub_cross_account::<T>()?;
<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -564,12 +561,12 @@
fn add_to_collection_allow_list_cross(
&mut self,
caller: caller,
- user: (address, uint256),
+ user: EthCrossAccount,
) -> Result<void> {
self.consume_store_writes(1)?;
let caller = T::CrossAccountId::from_eth(caller);
- let user = convert_tuple_to_cross_account::<T>(user)?;
+ let user = user.into_sub_cross_account::<T>()?;
Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -592,12 +589,12 @@
fn remove_from_collection_allow_list_cross(
&mut self,
caller: caller,
- user: (address, uint256),
+ user: EthCrossAccount,
) -> Result<void> {
self.consume_store_writes(1)?;
let caller = T::CrossAccountId::from_eth(caller);
- let user = convert_tuple_to_cross_account::<T>(user)?;
+ let user = user.into_sub_cross_account::<T>()?;
Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -637,8 +634,8 @@
///
/// @param user User cross account to verify
/// @return "true" if account is the owner or admin
- fn is_owner_or_admin_cross(&self, user: (address, uint256)) -> Result<bool> {
- let user = convert_tuple_to_cross_account::<T>(user)?;
+ fn is_owner_or_admin_cross(&self, user: EthCrossAccount) -> Result<bool> {
+ let user = user.into_sub_cross_account::<T>()?;
Ok(self.is_owner_or_admin(&user))
}
@@ -656,10 +653,10 @@
/// Get collection owner.
///
- /// @return Tuple with sponsor address and his substrate mirror.
+ /// @return Tuble with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
- fn collection_owner(&self) -> Result<(address, uint256)> {
- Ok(convert_cross_account_to_tuple::<T>(
+ fn collection_owner(&self) -> Result<EthCrossAccount> {
+ Ok(EthCrossAccount::from_sub_cross_account::<T>(
&T::CrossAccountId::from_sub(self.owner.clone()),
))
}
@@ -682,9 +679,9 @@
///
/// @return Vector of tuples with admins address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
- fn collection_admins(&self) -> Result<Vec<(address, uint256)>> {
+ fn collection_admins(&self) -> Result<Vec<EthCrossAccount>> {
let result = crate::IsAdmin::<T>::iter_prefix((self.id,))
- .map(|(admin, _)| crate::eth::convert_cross_account_to_tuple::<T>(&admin))
+ .map(|(admin, _)| EthCrossAccount::from_sub_cross_account::<T>(&admin))
.collect();
Ok(result)
}
@@ -693,11 +690,11 @@
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner cross account
- fn set_owner_cross(&mut self, caller: caller, new_owner: (address, uint256)) -> Result<void> {
+ fn set_owner_cross(&mut self, caller: caller, new_owner: EthCrossAccount) -> Result<void> {
self.consume_store_writes(1)?;
let caller = T::CrossAccountId::from_eth(caller);
- let new_owner = convert_tuple_to_cross_account::<T>(new_owner)?;
+ let new_owner = new_owner.into_sub_cross_account::<T>()?;
self.set_owner_internal(caller, new_owner)
.map_err(dispatch_to_evm::<T>)
}
pallets/common/src/weights.rsdiffbeforeafterboth--- a/pallets/common/src/weights.rs
+++ b/pallets/common/src/weights.rs
@@ -26,6 +26,7 @@
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
+#![allow(missing_docs)]
#![allow(clippy::unnecessary_cast)]
use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
pallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-contract-helpers/Cargo.toml
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -27,7 +27,7 @@
evm-coder = { default-features = false, path = '../../crates/evm-coder' }
pallet-common = { default-features = false, path = '../../pallets/common' }
pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
-pallet-evm-transaction-payment = { default-features = false, path = '../../pallets/evm-transaction-payment' }
+pallet-evm-transaction-payment = { default-features = false, path = '../../pallets/evm-transaction-payment' }
up-data-structs = { default-features = false, path = '../../primitives/data-structs', features = [
'serde1',
] }
@@ -52,3 +52,4 @@
"up-sponsorship/std",
]
try-runtime = ["frame-support/try-runtime"]
+stubgen = ["evm-coder/stubgen"]
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -16,6 +16,7 @@
//! Implementation of magic contract
+extern crate alloc;
use core::marker::PhantomData;
use evm_coder::{
abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -172,7 +172,7 @@
>;
#[pallet::event]
- #[pallet::generate_deposit(pub fn deposit_event)]
+ #[pallet::generate_deposit(fn deposit_event)]
pub enum Event<T: Config> {
/// Contract sponsor was set.
ContractSponsorSet(
@@ -350,6 +350,7 @@
pub fn sponsoring_mode(contract: H160) -> SponsoringModeT {
<SponsoringMode<T>>::get(contract)
.or_else(|| {
+ #[allow(deprecated)]
<SelfSponsoring<T>>::get(contract).then(|| SponsoringModeT::Allowlisted)
})
.unwrap_or_default()
@@ -362,6 +363,7 @@
} else {
<SponsoringMode<T>>::insert(contract, mode);
}
+ #[allow(deprecated)]
<SelfSponsoring<T>>::remove(contract)
}
@@ -424,6 +426,7 @@
_ => return None,
})
}
+ #[allow(dead_code)]
fn to_eth(self) -> u8 {
match self {
SponsoringModeT::Disabled => 0,
pallets/fungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/fungible/CHANGELOG.md
+++ b/pallets/fungible/CHANGELOG.md
@@ -2,6 +2,9 @@
All notable changes to this project will be documented in this file.
+## [0.1.6] - 2022-11-02
+### Changed
+ - Use named structure `EthCrossAccount` in eth functions.
## [0.1.5] - 2022-08-29
pallets/fungible/Cargo.tomldiffbeforeafterboth--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-fungible"
-version = "0.1.5"
+version = "0.1.6"
license = "GPLv3"
edition = "2021"
@@ -46,3 +46,4 @@
]
runtime-benchmarks = ['frame-benchmarking', 'pallet-common/runtime-benchmarks']
try-runtime = ["frame-support/try-runtime"]
+stubgen = ["evm-coder/stubgen", "pallet-common/stubgen"]
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -16,10 +16,10 @@
//! ERC-20 standart support implementation.
+extern crate alloc;
use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
use core::convert::TryInto;
use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
-use pallet_common::eth::convert_tuple_to_cross_account;
use up_data_structs::CollectionMode;
use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
use sp_std::vec::Vec;
@@ -158,11 +158,11 @@
fn approve_cross(
&mut self,
caller: caller,
- spender: (address, uint256),
+ spender: EthCrossAccount,
amount: uint256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
- let spender = convert_tuple_to_cross_account::<T>(spender)?;
+ let spender = spender.into_sub_cross_account::<T>()?;
let amount = amount.try_into().map_err(|_| "amount overflow")?;
<Pallet<T>>::set_allowance(self, &caller, &spender, amount)
@@ -198,11 +198,11 @@
fn burn_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
+ from: EthCrossAccount,
amount: uint256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
+ let from = from.into_sub_cross_account::<T>()?;
let amount = amount.try_into().map_err(|_| "amount overflow")?;
let budget = self
.recorder
@@ -240,13 +240,13 @@
fn transfer_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
- to: (address, uint256),
+ from: EthCrossAccount,
+ to: EthCrossAccount,
amount: uint256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
- let to = convert_tuple_to_cross_account::<T>(to)?;
+ let from = from.into_sub_cross_account::<T>()?;
+ let to = to.into_sub_cross_account::<T>()?;
let amount = amount.try_into().map_err(|_| "amount overflow")?;
let budget = self
.recorder
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -38,7 +38,7 @@
/// @param properties Vector of properties key/value pair.
/// @dev EVM selector for this function is: 0x50b26b2a,
/// or in textual repr: setCollectionProperties((string,bytes)[])
- function setCollectionProperties(Tuple10[] memory properties) public {
+ function setCollectionProperties(Tuple14[] memory properties) public {
require(false, stub_error);
properties;
dummy = 0;
@@ -87,11 +87,11 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) public view returns (Tuple10[] memory) {
+ function collectionProperties(string[] memory keys) public view returns (Tuple14[] memory) {
require(false, stub_error);
keys;
dummy;
- return new Tuple10[](0);
+ return new Tuple14[](0);
}
/// Set the sponsor of the collection.
@@ -114,7 +114,7 @@
/// @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,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
- function setCollectionSponsorCross(Tuple6 memory sponsor) public {
+ function setCollectionSponsorCross(EthCrossAccount memory sponsor) public {
require(false, stub_error);
sponsor;
dummy = 0;
@@ -152,10 +152,10 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() public view returns (Tuple6 memory) {
+ function collectionSponsor() public view returns (Tuple8 memory) {
require(false, stub_error);
dummy;
- return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ return Tuple8(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -206,7 +206,7 @@
/// @param newAdmin Cross account administrator address.
/// @dev EVM selector for this function is: 0x859aa7d6,
/// or in textual repr: addCollectionAdminCross((address,uint256))
- function addCollectionAdminCross(Tuple6 memory newAdmin) public {
+ function addCollectionAdminCross(EthCrossAccount memory newAdmin) public {
require(false, stub_error);
newAdmin;
dummy = 0;
@@ -216,7 +216,7 @@
/// @param admin Cross account administrator address.
/// @dev EVM selector for this function is: 0x6c0cd173,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
- function removeCollectionAdminCross(Tuple6 memory admin) public {
+ function removeCollectionAdminCross(EthCrossAccount memory admin) public {
require(false, stub_error);
admin;
dummy = 0;
@@ -307,7 +307,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0xa0184a3a,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
- function addToCollectionAllowListCross(Tuple6 memory user) public {
+ function addToCollectionAllowListCross(EthCrossAccount memory user) public {
require(false, stub_error);
user;
dummy = 0;
@@ -329,7 +329,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0x09ba452a,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
- function removeFromCollectionAllowListCross(Tuple6 memory user) public {
+ function removeFromCollectionAllowListCross(EthCrossAccount memory user) public {
require(false, stub_error);
user;
dummy = 0;
@@ -365,7 +365,7 @@
/// @return "true" if account is the owner or admin
/// @dev EVM selector for this function is: 0x3e75a905,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
- function isOwnerOrAdminCross(Tuple6 memory user) public view returns (bool) {
+ function isOwnerOrAdminCross(EthCrossAccount memory user) public view returns (bool) {
require(false, stub_error);
user;
dummy;
@@ -385,14 +385,14 @@
/// Get collection owner.
///
- /// @return Tuple with sponsor address and his substrate mirror.
+ /// @return Tuble with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() public view returns (Tuple6 memory) {
+ function collectionOwner() public view returns (EthCrossAccount memory) {
require(false, stub_error);
dummy;
- return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ return EthCrossAccount(0x0000000000000000000000000000000000000000, 0);
}
/// Changes collection owner to another account
@@ -413,10 +413,10 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0x5813216b,
/// or in textual repr: collectionAdmins()
- function collectionAdmins() public view returns (Tuple6[] memory) {
+ function collectionAdmins() public view returns (EthCrossAccount[] memory) {
require(false, stub_error);
dummy;
- return new Tuple6[](0);
+ return new EthCrossAccount[](0);
}
/// Changes collection owner to another account
@@ -425,15 +425,21 @@
/// @param newOwner new owner cross account
/// @dev EVM selector for this function is: 0xe5c9913f,
/// or in textual repr: setOwnerCross((address,uint256))
- function setOwnerCross(Tuple6 memory newOwner) public {
+ function setOwnerCross(EthCrossAccount memory newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
}
}
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
+}
+
/// @dev anonymous struct
-struct Tuple10 {
+struct Tuple14 {
string field_0;
bytes field_1;
}
@@ -442,7 +448,7 @@
contract ERC20UniqueExtensions is Dummy, ERC165 {
/// @dev EVM selector for this function is: 0x0ecd0ab0,
/// or in textual repr: approveCross((address,uint256),uint256)
- function approveCross(Tuple6 memory spender, uint256 amount) public returns (bool) {
+ function approveCross(EthCrossAccount memory spender, uint256 amount) public returns (bool) {
require(false, stub_error);
spender;
amount;
@@ -472,7 +478,7 @@
/// @param amount The amount that will be burnt.
/// @dev EVM selector for this function is: 0xbb2f5a58,
/// or in textual repr: burnFromCross((address,uint256),uint256)
- function burnFromCross(Tuple6 memory from, uint256 amount) public returns (bool) {
+ function burnFromCross(EthCrossAccount memory from, uint256 amount) public returns (bool) {
require(false, stub_error);
from;
amount;
@@ -484,7 +490,7 @@
/// @param amounts array of pairs of account address and amount
/// @dev EVM selector for this function is: 0x1acf2d55,
/// or in textual repr: mintBulk((address,uint256)[])
- function mintBulk(Tuple6[] memory amounts) public returns (bool) {
+ function mintBulk(Tuple8[] memory amounts) public returns (bool) {
require(false, stub_error);
amounts;
dummy = 0;
@@ -494,8 +500,8 @@
/// @dev EVM selector for this function is: 0xd5cf430b,
/// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
function transferFromCross(
- Tuple6 memory from,
- Tuple6 memory to,
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
uint256 amount
) public returns (bool) {
require(false, stub_error);
@@ -508,7 +514,7 @@
}
/// @dev anonymous struct
-struct Tuple6 {
+struct Tuple8 {
address field_0;
uint256 field_1;
}
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -3,6 +3,9 @@
All notable changes to this project will be documented in this file.
<!-- bureaucrate goes here -->
+## [v0.1.7] - 2022-11-02
+### Changed
+ - Use named structure `EthCrossAccount` in eth functions.
## [v0.1.6] - 2022-20-10
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-nonfungible"
-version = "0.1.6"
+version = "0.1.7"
license = "GPLv3"
edition = "2021"
@@ -52,3 +52,4 @@
'up-data-structs/runtime-benchmarks',
]
try-runtime = ["frame-support/try-runtime"]
+stubgen = ["evm-coder/stubgen", "pallet-common/stubgen"]
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -35,7 +35,6 @@
use pallet_common::{
erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
CollectionHandle, CollectionPropertyPermissions,
- eth::convert_tuple_to_cross_account,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
@@ -675,11 +674,11 @@
fn approve_cross(
&mut self,
caller: caller,
- approved: (address, uint256),
+ approved: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let approved = convert_tuple_to_cross_account::<T>(approved)?;
+ let approved = approved.into_sub_cross_account::<T>()?;
let token = token_id.try_into()?;
<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))
@@ -715,13 +714,13 @@
fn transfer_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
- to: (address, uint256),
+ from: EthCrossAccount,
+ to: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
- let to = convert_tuple_to_cross_account::<T>(to)?;
+ let from = from.into_sub_cross_account::<T>()?;
+ let to = to.into_sub_cross_account::<T>()?;
let token_id = token_id.try_into()?;
let budget = self
.recorder
@@ -761,11 +760,11 @@
fn burn_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
+ from: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
+ let from = from.into_sub_cross_account::<T>()?;
let token = token_id.try_into()?;
let budget = self
.recorder
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -67,7 +67,7 @@
/// @param properties settable properties
/// @dev EVM selector for this function is: 0x14ed3a6e,
/// or in textual repr: setProperties(uint256,(string,bytes)[])
- function setProperties(uint256 tokenId, Tuple19[] memory properties) public {
+ function setProperties(uint256 tokenId, Tuple21[] memory properties) public {
require(false, stub_error);
tokenId;
properties;
@@ -124,7 +124,7 @@
/// @param properties Vector of properties key/value pair.
/// @dev EVM selector for this function is: 0x50b26b2a,
/// or in textual repr: setCollectionProperties((string,bytes)[])
- function setCollectionProperties(Tuple19[] memory properties) public {
+ function setCollectionProperties(Tuple21[] memory properties) public {
require(false, stub_error);
properties;
dummy = 0;
@@ -173,11 +173,11 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) public view returns (Tuple19[] memory) {
+ function collectionProperties(string[] memory keys) public view returns (Tuple21[] memory) {
require(false, stub_error);
keys;
dummy;
- return new Tuple19[](0);
+ return new Tuple21[](0);
}
/// Set the sponsor of the collection.
@@ -200,7 +200,7 @@
/// @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,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
- function setCollectionSponsorCross(Tuple6 memory sponsor) public {
+ function setCollectionSponsorCross(EthCrossAccount memory sponsor) public {
require(false, stub_error);
sponsor;
dummy = 0;
@@ -238,10 +238,10 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() public view returns (Tuple6 memory) {
+ function collectionSponsor() public view returns (Tuple24 memory) {
require(false, stub_error);
dummy;
- return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ return Tuple24(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -292,7 +292,7 @@
/// @param newAdmin Cross account administrator address.
/// @dev EVM selector for this function is: 0x859aa7d6,
/// or in textual repr: addCollectionAdminCross((address,uint256))
- function addCollectionAdminCross(Tuple6 memory newAdmin) public {
+ function addCollectionAdminCross(EthCrossAccount memory newAdmin) public {
require(false, stub_error);
newAdmin;
dummy = 0;
@@ -302,7 +302,7 @@
/// @param admin Cross account administrator address.
/// @dev EVM selector for this function is: 0x6c0cd173,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
- function removeCollectionAdminCross(Tuple6 memory admin) public {
+ function removeCollectionAdminCross(EthCrossAccount memory admin) public {
require(false, stub_error);
admin;
dummy = 0;
@@ -393,7 +393,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0xa0184a3a,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
- function addToCollectionAllowListCross(Tuple6 memory user) public {
+ function addToCollectionAllowListCross(EthCrossAccount memory user) public {
require(false, stub_error);
user;
dummy = 0;
@@ -415,7 +415,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0x09ba452a,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
- function removeFromCollectionAllowListCross(Tuple6 memory user) public {
+ function removeFromCollectionAllowListCross(EthCrossAccount memory user) public {
require(false, stub_error);
user;
dummy = 0;
@@ -451,7 +451,7 @@
/// @return "true" if account is the owner or admin
/// @dev EVM selector for this function is: 0x3e75a905,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
- function isOwnerOrAdminCross(Tuple6 memory user) public view returns (bool) {
+ function isOwnerOrAdminCross(EthCrossAccount memory user) public view returns (bool) {
require(false, stub_error);
user;
dummy;
@@ -471,14 +471,14 @@
/// Get collection owner.
///
- /// @return Tuple with sponsor address and his substrate mirror.
+ /// @return Tuble with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() public view returns (Tuple6 memory) {
+ function collectionOwner() public view returns (EthCrossAccount memory) {
require(false, stub_error);
dummy;
- return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ return EthCrossAccount(0x0000000000000000000000000000000000000000, 0);
}
/// Changes collection owner to another account
@@ -499,10 +499,10 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0x5813216b,
/// or in textual repr: collectionAdmins()
- function collectionAdmins() public view returns (Tuple6[] memory) {
+ function collectionAdmins() public view returns (EthCrossAccount[] memory) {
require(false, stub_error);
dummy;
- return new Tuple6[](0);
+ return new EthCrossAccount[](0);
}
/// Changes collection owner to another account
@@ -511,15 +511,27 @@
/// @param newOwner new owner cross account
/// @dev EVM selector for this function is: 0xe5c9913f,
/// or in textual repr: setOwnerCross((address,uint256))
- function setOwnerCross(Tuple6 memory newOwner) public {
+ function setOwnerCross(EthCrossAccount memory newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
}
}
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
+}
+
/// @dev anonymous struct
-struct Tuple19 {
+struct Tuple24 {
+ address field_0;
+ uint256 field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple21 {
string field_0;
bytes field_1;
}
@@ -696,7 +708,7 @@
/// @param tokenId The NFT to approve
/// @dev EVM selector for this function is: 0x0ecd0ab0,
/// or in textual repr: approveCross((address,uint256),uint256)
- function approveCross(Tuple6 memory approved, uint256 tokenId) public {
+ function approveCross(EthCrossAccount memory approved, uint256 tokenId) public {
require(false, stub_error);
approved;
tokenId;
@@ -726,8 +738,8 @@
/// @dev EVM selector for this function is: 0xd5cf430b,
/// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
function transferFromCross(
- Tuple6 memory from,
- Tuple6 memory to,
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
uint256 tokenId
) public {
require(false, stub_error);
@@ -760,7 +772,7 @@
/// @param tokenId The NFT to transfer
/// @dev EVM selector for this function is: 0xbb2f5a58,
/// or in textual repr: burnFromCross((address,uint256),uint256)
- function burnFromCross(Tuple6 memory from, uint256 tokenId) public {
+ function burnFromCross(EthCrossAccount memory from, uint256 tokenId) public {
require(false, stub_error);
from;
tokenId;
@@ -797,7 +809,7 @@
// /// @param tokens array of pairs of token ID and token URI for minted tokens
// /// @dev EVM selector for this function is: 0x36543006,
// /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- // function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+ // function mintBulkWithTokenURI(address to, Tuple10[] memory tokens) public returns (bool) {
// require(false, stub_error);
// to;
// tokens;
@@ -808,15 +820,9 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple10 {
uint256 field_0;
string field_1;
-}
-
-/// @dev anonymous struct
-struct Tuple6 {
- address field_0;
- uint256 field_1;
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -2,6 +2,10 @@
All notable changes to this project will be documented in this file.
+## [v0.2.6] - 2022-11-02
+### Changed
+ - Use named structure `EthCrossAccount` in eth functions.
+
## [v0.2.5] - 2022-20-10
### Change
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-refungible"
-version = "0.2.5"
+version = "0.2.6"
license = "GPLv3"
edition = "2021"
@@ -26,7 +26,9 @@
struct-versioning = { path = "../../crates/struct-versioning" }
up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
ethereum = { version = "0.12.0", default-features = false }
-scale-info = { version = "2.0.1", default-features = false, features = ["derive",] }
+scale-info = { version = "2.0.1", default-features = false, features = [
+ "derive",
+] }
derivative = { version = "2.2.0", features = ["use_core"] }
[features]
@@ -52,3 +54,4 @@
'up-data-structs/runtime-benchmarks',
]
try-runtime = ["frame-support/try-runtime"]
+stubgen = ["evm-coder/stubgen", "pallet-common/stubgen"]
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -30,7 +30,6 @@
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions,
erc::{CommonEvmHandler, CollectionCall, static_property::key},
- eth::convert_tuple_to_cross_account,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -725,13 +724,13 @@
fn transfer_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
- to: (address, uint256),
+ from: EthCrossAccount,
+ to: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
- let to = convert_tuple_to_cross_account::<T>(to)?;
+ let from = from.into_sub_cross_account::<T>()?;
+ let to = to.into_sub_cross_account::<T>()?;
let token_id = token_id.try_into()?;
let budget = self
.recorder
@@ -780,11 +779,11 @@
fn burn_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
+ from: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
+ let from = from.into_sub_cross_account::<T>()?;
let token = token_id.try_into()?;
let budget = self
.recorder
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -137,7 +137,6 @@
/// for the convenience of database access. Notably contains the token metadata.
#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]
-#[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]
pub struct ItemData {
pub const_data: BoundedVec<u8, CustomDataLimit>,
@@ -279,7 +278,8 @@
fn on_runtime_upgrade() -> Weight {
let storage_version = StorageVersion::get::<Pallet<T>>();
if storage_version < StorageVersion::new(2) {
- <TokenData<T>>::remove_all(None);
+ #[allow(deprecated)]
+ let _ = <TokenData<T>>::clear(u32::MAX, None);
}
StorageVersion::new(2).put::<Pallet<T>>();
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -67,7 +67,7 @@
/// @param properties settable properties
/// @dev EVM selector for this function is: 0x14ed3a6e,
/// or in textual repr: setProperties(uint256,(string,bytes)[])
- function setProperties(uint256 tokenId, Tuple19[] memory properties) public {
+ function setProperties(uint256 tokenId, Tuple20[] memory properties) public {
require(false, stub_error);
tokenId;
properties;
@@ -124,7 +124,7 @@
/// @param properties Vector of properties key/value pair.
/// @dev EVM selector for this function is: 0x50b26b2a,
/// or in textual repr: setCollectionProperties((string,bytes)[])
- function setCollectionProperties(Tuple19[] memory properties) public {
+ function setCollectionProperties(Tuple20[] memory properties) public {
require(false, stub_error);
properties;
dummy = 0;
@@ -173,11 +173,11 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) public view returns (Tuple19[] memory) {
+ function collectionProperties(string[] memory keys) public view returns (Tuple20[] memory) {
require(false, stub_error);
keys;
dummy;
- return new Tuple19[](0);
+ return new Tuple20[](0);
}
/// Set the sponsor of the collection.
@@ -200,7 +200,7 @@
/// @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,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
- function setCollectionSponsorCross(Tuple6 memory sponsor) public {
+ function setCollectionSponsorCross(EthCrossAccount memory sponsor) public {
require(false, stub_error);
sponsor;
dummy = 0;
@@ -238,10 +238,10 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() public view returns (Tuple6 memory) {
+ function collectionSponsor() public view returns (Tuple23 memory) {
require(false, stub_error);
dummy;
- return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ return Tuple23(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -292,7 +292,7 @@
/// @param newAdmin Cross account administrator address.
/// @dev EVM selector for this function is: 0x859aa7d6,
/// or in textual repr: addCollectionAdminCross((address,uint256))
- function addCollectionAdminCross(Tuple6 memory newAdmin) public {
+ function addCollectionAdminCross(EthCrossAccount memory newAdmin) public {
require(false, stub_error);
newAdmin;
dummy = 0;
@@ -302,7 +302,7 @@
/// @param admin Cross account administrator address.
/// @dev EVM selector for this function is: 0x6c0cd173,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
- function removeCollectionAdminCross(Tuple6 memory admin) public {
+ function removeCollectionAdminCross(EthCrossAccount memory admin) public {
require(false, stub_error);
admin;
dummy = 0;
@@ -393,7 +393,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0xa0184a3a,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
- function addToCollectionAllowListCross(Tuple6 memory user) public {
+ function addToCollectionAllowListCross(EthCrossAccount memory user) public {
require(false, stub_error);
user;
dummy = 0;
@@ -415,7 +415,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0x09ba452a,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
- function removeFromCollectionAllowListCross(Tuple6 memory user) public {
+ function removeFromCollectionAllowListCross(EthCrossAccount memory user) public {
require(false, stub_error);
user;
dummy = 0;
@@ -451,7 +451,7 @@
/// @return "true" if account is the owner or admin
/// @dev EVM selector for this function is: 0x3e75a905,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
- function isOwnerOrAdminCross(Tuple6 memory user) public view returns (bool) {
+ function isOwnerOrAdminCross(EthCrossAccount memory user) public view returns (bool) {
require(false, stub_error);
user;
dummy;
@@ -471,14 +471,14 @@
/// Get collection owner.
///
- /// @return Tuple with sponsor address and his substrate mirror.
+ /// @return Tuble with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() public view returns (Tuple6 memory) {
+ function collectionOwner() public view returns (EthCrossAccount memory) {
require(false, stub_error);
dummy;
- return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ return EthCrossAccount(0x0000000000000000000000000000000000000000, 0);
}
/// Changes collection owner to another account
@@ -499,10 +499,10 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0x5813216b,
/// or in textual repr: collectionAdmins()
- function collectionAdmins() public view returns (Tuple6[] memory) {
+ function collectionAdmins() public view returns (EthCrossAccount[] memory) {
require(false, stub_error);
dummy;
- return new Tuple6[](0);
+ return new EthCrossAccount[](0);
}
/// Changes collection owner to another account
@@ -511,15 +511,27 @@
/// @param newOwner new owner cross account
/// @dev EVM selector for this function is: 0xe5c9913f,
/// or in textual repr: setOwnerCross((address,uint256))
- function setOwnerCross(Tuple6 memory newOwner) public {
+ function setOwnerCross(EthCrossAccount memory newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
}
}
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
+}
+
/// @dev anonymous struct
-struct Tuple19 {
+struct Tuple23 {
+ address field_0;
+ uint256 field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple20 {
string field_0;
bytes field_1;
}
@@ -710,8 +722,8 @@
/// @dev EVM selector for this function is: 0xd5cf430b,
/// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
function transferFromCross(
- Tuple6 memory from,
- Tuple6 memory to,
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
uint256 tokenId
) public {
require(false, stub_error);
@@ -746,7 +758,7 @@
/// @param tokenId The RFT to transfer
/// @dev EVM selector for this function is: 0xbb2f5a58,
/// or in textual repr: burnFromCross((address,uint256),uint256)
- function burnFromCross(Tuple6 memory from, uint256 tokenId) public {
+ function burnFromCross(EthCrossAccount memory from, uint256 tokenId) public {
require(false, stub_error);
from;
tokenId;
@@ -784,7 +796,7 @@
// /// @param tokens array of pairs of token ID and token URI for minted tokens
// /// @dev EVM selector for this function is: 0x36543006,
// /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- // function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+ // function mintBulkWithTokenURI(address to, Tuple9[] memory tokens) public returns (bool) {
// require(false, stub_error);
// to;
// tokens;
@@ -806,15 +818,9 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple9 {
uint256 field_0;
string field_1;
-}
-
-/// @dev anonymous struct
-struct Tuple6 {
- address field_0;
- uint256 field_1;
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -20,7 +20,6 @@
use ethereum as _;
use evm_coder::{execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use frame_support::traits::Get;
-
use crate::Pallet;
use pallet_common::{
runtime/common/config/pallets/scheduler.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/scheduler.rs
+++ b/runtime/common/config/pallets/scheduler.rs
@@ -25,7 +25,7 @@
use codec::Decode;
use crate::{
runtime_common::{scheduler::SchedulerPaymentExecutor, config::substrate::RuntimeBlockWeights},
- Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, OriginCaller, Balances,
+ Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, OriginCaller,
};
use pallet_unique_scheduler::ScheduledEnsureOriginSuccess;
use up_common::types::AccountId;
runtime/common/scheduler.rsdiffbeforeafterboth--- a/runtime/common/scheduler.rs
+++ b/runtime/common/scheduler.rs
@@ -14,19 +14,16 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use frame_support::{
- traits::NamedReservableCurrency,
- dispatch::{GetDispatchInfo, PostDispatchInfo, DispatchInfo},
-};
+use frame_support::dispatch::{GetDispatchInfo, PostDispatchInfo, DispatchInfo};
use sp_runtime::{
traits::{Dispatchable, Applyable, Member},
generic::Era,
transaction_validity::TransactionValidityError,
- DispatchErrorWithPostInfo, DispatchError,
+ DispatchErrorWithPostInfo,
};
use codec::Encode;
-use crate::{Runtime, RuntimeCall, RuntimeOrigin, Balances};
-use up_common::types::{AccountId, Balance};
+use crate::{Runtime, RuntimeCall, RuntimeOrigin};
+use up_common::types::AccountId;
use fp_self_contained::SelfContainedCall;
use pallet_unique_scheduler::DispatchCall;
use pallet_transaction_payment::ChargeTransactionPayment;
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -169,6 +169,7 @@
]
limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
unique-runtime = []
+stubgen = ["evm-coder/stubgen"]
refungible = []
scheduler = []
tests/src/eth/allowlist.test.tsdiffbeforeafterboth--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -89,21 +89,21 @@
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
});
- //itEth('Collection allowlist can be added and removed by [cross] address', async ({helper}) => {
- // const owner = await helper.eth.createAccountWithBalance(donor);
- // const user = donor;
- //
- // const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
- // const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- // const userCross = helper.ethCrossAccount.fromKeyringPair(user);
- //
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
- // await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
- //
- // await collectionEvm.methods.removeFromCollectionAllowListCross(userCross).send({from: owner});
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
- //});
+ itEth('Collection allowlist can be added and removed by [cross] address', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const user = donor;
+
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ const userCross = helper.ethCrossAccount.fromKeyringPair(user);
+
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+
+ await collectionEvm.methods.removeFromCollectionAllowListCross(userCross).send({from: owner});
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ });
itEth('Collection allowlist can not be add and remove [eth] address by not owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
@@ -122,22 +122,22 @@
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
});
- //itEth('Collection allowlist can not be add and remove [cross] address by not owner', async ({helper}) => {
- // const owner = await helper.eth.createAccountWithBalance(donor);
- // const notOwner = await helper.eth.createAccountWithBalance(donor);
- // const user = donor;
- //
- // const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
- // const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- //
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
- // const userCross = helper.ethCrossAccount.fromKeyringPair(user);
- // await expect(collectionEvm.methods.addToCollectionAllowListCross(userCross).call({from: notOwner})).to.be.rejectedWith('NoPermission');
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
- // await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
- //
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
- // await expect(collectionEvm.methods.removeFromCollectionAllowListCross(userCross).call({from: notOwner})).to.be.rejectedWith('NoPermission');
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
- //});
+ itEth('Collection allowlist can not be add and remove [cross] address by not owner', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const notOwner = await helper.eth.createAccountWithBalance(donor);
+ const user = donor;
+
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ const userCross = helper.ethCrossAccount.fromKeyringPair(user);
+ await expect(collectionEvm.methods.addToCollectionAllowListCross(userCross).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
+
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+ await expect(collectionEvm.methods.removeFromCollectionAllowListCross(userCross).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+ });
});
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -28,7 +28,7 @@
/// @param properties Vector of properties key/value pair.
/// @dev EVM selector for this function is: 0x50b26b2a,
/// or in textual repr: setCollectionProperties((string,bytes)[])
- function setCollectionProperties(Tuple10[] memory properties) external;
+ function setCollectionProperties(Tuple14[] memory properties) external;
/// Delete collection property.
///
@@ -60,7 +60,7 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) external view returns (Tuple10[] memory);
+ function collectionProperties(string[] memory keys) external view returns (Tuple14[] memory);
/// Set the sponsor of the collection.
///
@@ -78,7 +78,7 @@
/// @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,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
- function setCollectionSponsorCross(Tuple6 memory sponsor) external;
+ function setCollectionSponsorCross(EthCrossAccount memory sponsor) external;
/// Whether there is a pending sponsor.
/// @dev EVM selector for this function is: 0x058ac185,
@@ -102,7 +102,7 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() external view returns (Tuple6 memory);
+ function collectionSponsor() external view returns (Tuple8 memory);
/// Set limits for the collection.
/// @dev Throws error if limit not found.
@@ -138,13 +138,13 @@
/// @param newAdmin Cross account administrator address.
/// @dev EVM selector for this function is: 0x859aa7d6,
/// or in textual repr: addCollectionAdminCross((address,uint256))
- function addCollectionAdminCross(Tuple6 memory newAdmin) external;
+ function addCollectionAdminCross(EthCrossAccount memory newAdmin) external;
/// Remove collection admin.
/// @param admin Cross account administrator address.
/// @dev EVM selector for this function is: 0x6c0cd173,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
- function removeCollectionAdminCross(Tuple6 memory admin) external;
+ function removeCollectionAdminCross(EthCrossAccount memory admin) external;
/// Add collection admin.
/// @param newAdmin Address of the added administrator.
@@ -201,7 +201,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0xa0184a3a,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
- function addToCollectionAllowListCross(Tuple6 memory user) external;
+ function addToCollectionAllowListCross(EthCrossAccount memory user) external;
/// Remove the user from the allowed list.
///
@@ -215,7 +215,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0x09ba452a,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
- function removeFromCollectionAllowListCross(Tuple6 memory user) external;
+ function removeFromCollectionAllowListCross(EthCrossAccount memory user) external;
/// Switch permission for minting.
///
@@ -238,7 +238,7 @@
/// @return "true" if account is the owner or admin
/// @dev EVM selector for this function is: 0x3e75a905,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
- function isOwnerOrAdminCross(Tuple6 memory user) external view returns (bool);
+ function isOwnerOrAdminCross(EthCrossAccount memory user) external view returns (bool);
/// Returns collection type
///
@@ -249,11 +249,11 @@
/// Get collection owner.
///
- /// @return Tuple with sponsor address and his substrate mirror.
+ /// @return Tuble with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() external view returns (Tuple6 memory);
+ function collectionOwner() external view returns (EthCrossAccount memory);
/// Changes collection owner to another account
///
@@ -269,7 +269,7 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0x5813216b,
/// or in textual repr: collectionAdmins()
- function collectionAdmins() external view returns (Tuple6[] memory);
+ function collectionAdmins() external view returns (EthCrossAccount[] memory);
/// Changes collection owner to another account
///
@@ -277,11 +277,17 @@
/// @param newOwner new owner cross account
/// @dev EVM selector for this function is: 0xe5c9913f,
/// or in textual repr: setOwnerCross((address,uint256))
- function setOwnerCross(Tuple6 memory newOwner) external;
+ function setOwnerCross(EthCrossAccount memory newOwner) external;
+}
+
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
}
/// @dev anonymous struct
-struct Tuple10 {
+struct Tuple14 {
string field_0;
bytes field_1;
}
@@ -290,7 +296,7 @@
interface ERC20UniqueExtensions is Dummy, ERC165 {
/// @dev EVM selector for this function is: 0x0ecd0ab0,
/// or in textual repr: approveCross((address,uint256),uint256)
- function approveCross(Tuple6 memory spender, uint256 amount) external returns (bool);
+ function approveCross(EthCrossAccount memory spender, uint256 amount) external returns (bool);
/// Burn tokens from account
/// @dev Function that burns an `amount` of the tokens of a given account,
@@ -308,25 +314,25 @@
/// @param amount The amount that will be burnt.
/// @dev EVM selector for this function is: 0xbb2f5a58,
/// or in textual repr: burnFromCross((address,uint256),uint256)
- function burnFromCross(Tuple6 memory from, uint256 amount) external returns (bool);
+ function burnFromCross(EthCrossAccount memory from, uint256 amount) external returns (bool);
/// Mint tokens for multiple accounts.
/// @param amounts array of pairs of account address and amount
/// @dev EVM selector for this function is: 0x1acf2d55,
/// or in textual repr: mintBulk((address,uint256)[])
- function mintBulk(Tuple6[] memory amounts) external returns (bool);
+ function mintBulk(Tuple8[] memory amounts) external returns (bool);
/// @dev EVM selector for this function is: 0xd5cf430b,
/// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
function transferFromCross(
- Tuple6 memory from,
- Tuple6 memory to,
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
uint256 amount
) external returns (bool);
}
/// @dev anonymous struct
-struct Tuple6 {
+struct Tuple8 {
address field_0;
uint256 field_1;
}
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -49,7 +49,7 @@
/// @param properties settable properties
/// @dev EVM selector for this function is: 0x14ed3a6e,
/// or in textual repr: setProperties(uint256,(string,bytes)[])
- function setProperties(uint256 tokenId, Tuple19[] memory properties) external;
+ function setProperties(uint256 tokenId, Tuple21[] memory properties) external;
/// @notice Delete token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
@@ -85,7 +85,7 @@
/// @param properties Vector of properties key/value pair.
/// @dev EVM selector for this function is: 0x50b26b2a,
/// or in textual repr: setCollectionProperties((string,bytes)[])
- function setCollectionProperties(Tuple19[] memory properties) external;
+ function setCollectionProperties(Tuple21[] memory properties) external;
/// Delete collection property.
///
@@ -117,7 +117,7 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) external view returns (Tuple19[] memory);
+ function collectionProperties(string[] memory keys) external view returns (Tuple21[] memory);
/// Set the sponsor of the collection.
///
@@ -135,7 +135,7 @@
/// @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,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
- function setCollectionSponsorCross(Tuple6 memory sponsor) external;
+ function setCollectionSponsorCross(EthCrossAccount memory sponsor) external;
/// Whether there is a pending sponsor.
/// @dev EVM selector for this function is: 0x058ac185,
@@ -159,7 +159,7 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() external view returns (Tuple6 memory);
+ function collectionSponsor() external view returns (Tuple24 memory);
/// Set limits for the collection.
/// @dev Throws error if limit not found.
@@ -195,13 +195,13 @@
/// @param newAdmin Cross account administrator address.
/// @dev EVM selector for this function is: 0x859aa7d6,
/// or in textual repr: addCollectionAdminCross((address,uint256))
- function addCollectionAdminCross(Tuple6 memory newAdmin) external;
+ function addCollectionAdminCross(EthCrossAccount memory newAdmin) external;
/// Remove collection admin.
/// @param admin Cross account administrator address.
/// @dev EVM selector for this function is: 0x6c0cd173,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
- function removeCollectionAdminCross(Tuple6 memory admin) external;
+ function removeCollectionAdminCross(EthCrossAccount memory admin) external;
/// Add collection admin.
/// @param newAdmin Address of the added administrator.
@@ -258,7 +258,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0xa0184a3a,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
- function addToCollectionAllowListCross(Tuple6 memory user) external;
+ function addToCollectionAllowListCross(EthCrossAccount memory user) external;
/// Remove the user from the allowed list.
///
@@ -272,7 +272,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0x09ba452a,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
- function removeFromCollectionAllowListCross(Tuple6 memory user) external;
+ function removeFromCollectionAllowListCross(EthCrossAccount memory user) external;
/// Switch permission for minting.
///
@@ -295,7 +295,7 @@
/// @return "true" if account is the owner or admin
/// @dev EVM selector for this function is: 0x3e75a905,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
- function isOwnerOrAdminCross(Tuple6 memory user) external view returns (bool);
+ function isOwnerOrAdminCross(EthCrossAccount memory user) external view returns (bool);
/// Returns collection type
///
@@ -306,11 +306,11 @@
/// Get collection owner.
///
- /// @return Tuple with sponsor address and his substrate mirror.
+ /// @return Tuble with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() external view returns (Tuple6 memory);
+ function collectionOwner() external view returns (EthCrossAccount memory);
/// Changes collection owner to another account
///
@@ -326,7 +326,7 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0x5813216b,
/// or in textual repr: collectionAdmins()
- function collectionAdmins() external view returns (Tuple6[] memory);
+ function collectionAdmins() external view returns (EthCrossAccount[] memory);
/// Changes collection owner to another account
///
@@ -334,11 +334,23 @@
/// @param newOwner new owner cross account
/// @dev EVM selector for this function is: 0xe5c9913f,
/// or in textual repr: setOwnerCross((address,uint256))
- function setOwnerCross(Tuple6 memory newOwner) external;
+ function setOwnerCross(EthCrossAccount memory newOwner) external;
+}
+
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
}
/// @dev anonymous struct
-struct Tuple19 {
+struct Tuple24 {
+ address field_0;
+ uint256 field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple21 {
string field_0;
bytes field_1;
}
@@ -458,7 +470,7 @@
/// @param tokenId The NFT to approve
/// @dev EVM selector for this function is: 0x0ecd0ab0,
/// or in textual repr: approveCross((address,uint256),uint256)
- function approveCross(Tuple6 memory approved, uint256 tokenId) external;
+ function approveCross(EthCrossAccount memory approved, uint256 tokenId) external;
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
@@ -478,8 +490,8 @@
/// @dev EVM selector for this function is: 0xd5cf430b,
/// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
function transferFromCross(
- Tuple6 memory from,
- Tuple6 memory to,
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
uint256 tokenId
) external;
@@ -501,7 +513,7 @@
/// @param tokenId The NFT to transfer
/// @dev EVM selector for this function is: 0xbb2f5a58,
/// or in textual repr: burnFromCross((address,uint256),uint256)
- function burnFromCross(Tuple6 memory from, uint256 tokenId) external;
+ function burnFromCross(EthCrossAccount memory from, uint256 tokenId) external;
/// @notice Returns next free NFT ID.
/// @dev EVM selector for this function is: 0x75794a3c,
@@ -523,20 +535,14 @@
// /// @param tokens array of pairs of token ID and token URI for minted tokens
// /// @dev EVM selector for this function is: 0x36543006,
// /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- // function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+ // function mintBulkWithTokenURI(address to, Tuple10[] memory tokens) external returns (bool);
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple10 {
uint256 field_0;
string field_1;
-}
-
-/// @dev anonymous struct
-struct Tuple6 {
- address field_0;
- uint256 field_1;
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -49,7 +49,7 @@
/// @param properties settable properties
/// @dev EVM selector for this function is: 0x14ed3a6e,
/// or in textual repr: setProperties(uint256,(string,bytes)[])
- function setProperties(uint256 tokenId, Tuple19[] memory properties) external;
+ function setProperties(uint256 tokenId, Tuple20[] memory properties) external;
/// @notice Delete token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
@@ -85,7 +85,7 @@
/// @param properties Vector of properties key/value pair.
/// @dev EVM selector for this function is: 0x50b26b2a,
/// or in textual repr: setCollectionProperties((string,bytes)[])
- function setCollectionProperties(Tuple19[] memory properties) external;
+ function setCollectionProperties(Tuple20[] memory properties) external;
/// Delete collection property.
///
@@ -117,7 +117,7 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) external view returns (Tuple19[] memory);
+ function collectionProperties(string[] memory keys) external view returns (Tuple20[] memory);
/// Set the sponsor of the collection.
///
@@ -135,7 +135,7 @@
/// @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,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
- function setCollectionSponsorCross(Tuple6 memory sponsor) external;
+ function setCollectionSponsorCross(EthCrossAccount memory sponsor) external;
/// Whether there is a pending sponsor.
/// @dev EVM selector for this function is: 0x058ac185,
@@ -159,7 +159,7 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() external view returns (Tuple6 memory);
+ function collectionSponsor() external view returns (Tuple23 memory);
/// Set limits for the collection.
/// @dev Throws error if limit not found.
@@ -195,13 +195,13 @@
/// @param newAdmin Cross account administrator address.
/// @dev EVM selector for this function is: 0x859aa7d6,
/// or in textual repr: addCollectionAdminCross((address,uint256))
- function addCollectionAdminCross(Tuple6 memory newAdmin) external;
+ function addCollectionAdminCross(EthCrossAccount memory newAdmin) external;
/// Remove collection admin.
/// @param admin Cross account administrator address.
/// @dev EVM selector for this function is: 0x6c0cd173,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
- function removeCollectionAdminCross(Tuple6 memory admin) external;
+ function removeCollectionAdminCross(EthCrossAccount memory admin) external;
/// Add collection admin.
/// @param newAdmin Address of the added administrator.
@@ -258,7 +258,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0xa0184a3a,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
- function addToCollectionAllowListCross(Tuple6 memory user) external;
+ function addToCollectionAllowListCross(EthCrossAccount memory user) external;
/// Remove the user from the allowed list.
///
@@ -272,7 +272,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0x09ba452a,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
- function removeFromCollectionAllowListCross(Tuple6 memory user) external;
+ function removeFromCollectionAllowListCross(EthCrossAccount memory user) external;
/// Switch permission for minting.
///
@@ -295,7 +295,7 @@
/// @return "true" if account is the owner or admin
/// @dev EVM selector for this function is: 0x3e75a905,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
- function isOwnerOrAdminCross(Tuple6 memory user) external view returns (bool);
+ function isOwnerOrAdminCross(EthCrossAccount memory user) external view returns (bool);
/// Returns collection type
///
@@ -306,11 +306,11 @@
/// Get collection owner.
///
- /// @return Tuple with sponsor address and his substrate mirror.
+ /// @return Tuble with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() external view returns (Tuple6 memory);
+ function collectionOwner() external view returns (EthCrossAccount memory);
/// Changes collection owner to another account
///
@@ -326,7 +326,7 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0x5813216b,
/// or in textual repr: collectionAdmins()
- function collectionAdmins() external view returns (Tuple6[] memory);
+ function collectionAdmins() external view returns (EthCrossAccount[] memory);
/// Changes collection owner to another account
///
@@ -334,11 +334,23 @@
/// @param newOwner new owner cross account
/// @dev EVM selector for this function is: 0xe5c9913f,
/// or in textual repr: setOwnerCross((address,uint256))
- function setOwnerCross(Tuple6 memory newOwner) external;
+ function setOwnerCross(EthCrossAccount memory newOwner) external;
+}
+
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
}
/// @dev anonymous struct
-struct Tuple19 {
+struct Tuple23 {
+ address field_0;
+ uint256 field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple20 {
string field_0;
bytes field_1;
}
@@ -467,8 +479,8 @@
/// @dev EVM selector for this function is: 0xd5cf430b,
/// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
function transferFromCross(
- Tuple6 memory from,
- Tuple6 memory to,
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
uint256 tokenId
) external;
@@ -492,7 +504,7 @@
/// @param tokenId The RFT to transfer
/// @dev EVM selector for this function is: 0xbb2f5a58,
/// or in textual repr: burnFromCross((address,uint256),uint256)
- function burnFromCross(Tuple6 memory from, uint256 tokenId) external;
+ function burnFromCross(EthCrossAccount memory from, uint256 tokenId) external;
/// @notice Returns next free RFT ID.
/// @dev EVM selector for this function is: 0x75794a3c,
@@ -515,7 +527,7 @@
// /// @param tokens array of pairs of token ID and token URI for minted tokens
// /// @dev EVM selector for this function is: 0x36543006,
// /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- // function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+ // function mintBulkWithTokenURI(address to, Tuple9[] memory tokens) external returns (bool);
/// Returns EVM address for refungible token
///
@@ -526,15 +538,9 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple9 {
uint256 field_0;
string field_1;
-}
-
-/// @dev anonymous struct
-struct Tuple6 {
- address field_0;
- uint256 field_1;
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -116,7 +116,7 @@
await checkInterface(helper, '0x780e9d63', true, true);
});
- itEth('ERC721UniqueExtensions - 0x244543ee - support', async ({helper}) => {
+ itEth('ERC721UniqueExtensions support', async ({helper}) => {
await checkInterface(helper, '0x244543ee', true, true);
});
tests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -14,7 +14,10 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {usingEthPlaygrounds, itEth, expect, EthUniqueHelper} from './util';
+import {expect} from 'chai';
+import {IEthCrossAccountId} from '../util/playgrounds/types';
+import {usingEthPlaygrounds, itEth} from './util';
+import {EthUniqueHelper} from './util/playgrounds/unique.dev';
async function recordEthFee(helper: EthUniqueHelper, userAddress: string, call: () => Promise<any>) {
const before = await helper.balance.getSubstrate(helper.address.ethToSubstrate(userAddress));
@@ -63,24 +66,25 @@
expect(adminList).to.be.like([{Substrate: newAdmin.address}]);
});
- // itEth('Check adminlist', async ({helper, privateKey}) => {
- // const owner = await helper.eth.createAccountWithBalance(donor);
+ itEth('Check adminlist', async ({helper, privateKey}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
- // const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
- // const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+ const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- // const admin1 = helper.eth.createAccount();
- // const admin2 = await privateKey('admin');
- // await collectionEvm.methods.addCollectionAdmin(admin1).send();
- // await collectionEvm.methods.addCollectionAdminCross(helper.ethCrossAccount.fromKeyringPair(admin2)).send();
+ const admin1 = helper.eth.createAccount();
+ const admin2 = await privateKey('admin');
+ const admin2Cross = helper.ethCrossAccount.fromKeyringPair(admin2);
+ await collectionEvm.methods.addCollectionAdmin(admin1).send();
+ await collectionEvm.methods.addCollectionAdminCross(admin2Cross).send();
- // const adminListRpc = await helper.collection.getAdmins(collectionId);
- // let adminListEth = await collectionEvm.methods.collectionAdmins().call();
- // adminListEth = adminListEth.map((element: IEthCrossAccountId) => {
- // return helper.address.convertCrossAccountFromEthCrossAcoount(element);
- // });
- // expect(adminListRpc).to.be.like(adminListEth);
- // });
+ const adminListRpc = await helper.collection.getAdmins(collectionId);
+ let adminListEth = await collectionEvm.methods.collectionAdmins().call();
+ adminListEth = adminListEth.map((element: IEthCrossAccountId) => {
+ return helper.address.convertCrossAccountFromEthCrossAcoount(element);
+ });
+ expect(adminListRpc).to.be.like(adminListEth);
+ });
itEth('Verify owner or admin', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
@@ -93,25 +97,6 @@
await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
expect(await collectionEvm.methods.isOwnerOrAdmin(newAdmin).call()).to.be.true;
});
-
- // itEth.skip('Check adminlist', async ({helper, privateKey}) => {
- // const owner = await helper.eth.createAccountWithBalance(donor);
-
- // const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
- // const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
-
- // const admin1 = helper.eth.createAccount();
- // const admin2 = await privateKey('admin');
- // await collectionEvm.methods.addCollectionAdmin(admin1).send();
- // await collectionEvm.methods.addCollectionAdminSubstrate(admin2.addressRaw).send();
-
- // const adminListRpc = await helper.collection.getAdmins(collectionId);
- // let adminListEth = await collectionEvm.methods.collectionAdmins().call();
- // adminListEth = adminListEth.map((element: IEthCrossAccountId) => {
- // return helper.address.convertCrossAccountFromEthCrossAcoount(element);
- // });
- // expect(adminListRpc).to.be.like(adminListEth);
- // });
itEth('(!negative tests!) Add admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
@@ -146,7 +131,7 @@
expect(adminList.length).to.be.eq(0);
});
- itEth.skip('(!negative tests!) Add substrate admin by ADMIN is not allowed', async ({helper}) => {
+ itEth('(!negative tests!) Add [cross] admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
@@ -155,7 +140,8 @@
await collectionEvm.methods.addCollectionAdmin(admin).send();
const [notAdmin] = await helper.arrange.createAccounts([10n], donor);
- await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin.addressRaw).call({from: admin}))
+ const notAdminCross = helper.ethCrossAccount.fromKeyringPair(notAdmin);
+ await expect(collectionEvm.methods.addCollectionAdminCross(notAdminCross).call({from: admin}))
.to.be.rejectedWith('NoPermission');
const adminList = await helper.callRpc('api.rpc.unique.adminlist', [collectionId]);
@@ -164,14 +150,15 @@
.to.be.eq(admin.toLocaleLowerCase());
});
- itEth.skip('(!negative tests!) Add substrate admin by USER is not allowed', async ({helper}) => {
+ itEth('(!negative tests!) Add [cross] admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const notAdmin0 = await helper.eth.createAccountWithBalance(donor);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const [notAdmin1] = await helper.arrange.createAccounts([10n], donor);
- await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin1.addressRaw).call({from: notAdmin0}))
+ const notAdmin1Cross = helper.ethCrossAccount.fromKeyringPair(notAdmin1);
+ await expect(collectionEvm.methods.addCollectionAdminCross(notAdmin1Cross).call({from: notAdmin0}))
.to.be.rejectedWith('NoPermission');
const adminList = await helper.callRpc('api.rpc.unique.adminlist', [collectionId]);
@@ -208,20 +195,21 @@
expect(adminList.length).to.be.eq(0);
});
- itEth.skip('Remove substrate admin by owner', async ({helper}) => {
+ itEth('Remove [cross] admin by owner', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const [newAdmin] = await helper.arrange.createAccounts([10n], donor);
+ const newAdminCross = helper.ethCrossAccount.fromKeyringPair(newAdmin);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();
+ await collectionEvm.methods.addCollectionAdminCross(newAdminCross).send();
{
const adminList = await helper.callRpc('api.rpc.unique.adminlist', [collectionId]);
expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())
.to.be.eq(newAdmin.address.toLocaleLowerCase());
}
- await collectionEvm.methods.removeCollectionAdminSubstrate(newAdmin.addressRaw).send();
+ await collectionEvm.methods.removeCollectionAdminCross(newAdminCross).send();
const adminList = await helper.callRpc('api.rpc.unique.adminlist', [collectionId]);
expect(adminList.length).to.be.eq(0);
});
@@ -268,17 +256,18 @@
}
});
- itEth.skip('(!negative tests!) Remove substrate admin by ADMIN is not allowed', async ({helper}) => {
+ itEth('(!negative tests!) Remove [cross] admin by ADMIN is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const [adminSub] = await helper.arrange.createAccounts([10n], donor);
+ const adminSubCross = helper.ethCrossAccount.fromKeyringPair(adminSub);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();
+ await collectionEvm.methods.addCollectionAdminCross(adminSubCross).send();
const adminEth = await helper.eth.createAccountWithBalance(donor);
await collectionEvm.methods.addCollectionAdmin(adminEth).send();
- await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: adminEth}))
+ await expect(collectionEvm.methods.removeCollectionAdminCross(adminSubCross).call({from: adminEth}))
.to.be.rejectedWith('NoPermission');
const adminList = await helper.callRpc('api.rpc.unique.adminlist', [collectionId]);
@@ -288,16 +277,17 @@
.to.be.deep.contains(adminEth.toLocaleLowerCase());
});
- itEth.skip('(!negative tests!) Remove substrate admin by USER is not allowed', async ({helper}) => {
+ itEth('(!negative tests!) Remove [cross] admin by USER is not allowed', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const [adminSub] = await helper.arrange.createAccounts([10n], donor);
+ const adminSubCross = helper.ethCrossAccount.fromKeyringPair(adminSub);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();
+ await collectionEvm.methods.addCollectionAdminCross(adminSubCross).send();
const notAdminEth = await helper.eth.createAccountWithBalance(donor);
- await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: notAdminEth}))
+ await expect(collectionEvm.methods.removeCollectionAdminCross(adminSubCross).call({from: notAdminEth}))
.to.be.rejectedWith('NoPermission');
const adminList = await helper.callRpc('api.rpc.unique.adminlist', [collectionId]);
@@ -358,19 +348,20 @@
});
});
- itEth.skip('Change owner', async ({helper}) => {
+ itEth('Change owner [cross]', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const [newOwner] = await helper.arrange.createAccounts([10n], donor);
+ const newOwnerCross = helper.ethCrossAccount.fromKeyringPair(newOwner);
const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.true;
- expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;
+ expect(await collectionEvm.methods.isOwnerOrAdminCross(newOwnerCross).call()).to.be.false;
- await collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send();
+ await collectionEvm.methods.setOwnerCross(newOwnerCross).send();
expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.false;
- expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.true;
+ expect(await collectionEvm.methods.isOwnerOrAdminCross(newOwnerCross).call()).to.be.true;
});
itEth.skip('change owner call fee', async ({helper}) => {
@@ -384,14 +375,15 @@
expect(cost > 0);
});
- itEth.skip('(!negative tests!) call setOwner by non owner', async ({helper}) => {
+ itEth('(!negative tests!) call setOwner by non owner [cross]', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const otherReceiver = await helper.eth.createAccountWithBalance(donor);
const [newOwner] = await helper.arrange.createAccounts([10n], donor);
+ const newOwnerCross = helper.ethCrossAccount.fromKeyringPair(newOwner);
const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
- await expect(collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send({from: otherReceiver})).to.be.rejected;
- expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;
+ await expect(collectionEvm.methods.setOwnerCross(newOwnerCross).send({from: otherReceiver})).to.be.rejected;
+ expect(await collectionEvm.methods.isOwnerOrAdminCross(newOwnerCross).call()).to.be.false;
});
});
tests/src/eth/fungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -52,11 +52,12 @@
describe('Fungible: Plain calls', () => {
let donor: IKeyringPair;
let alice: IKeyringPair;
+ let owner: IKeyringPair;
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
donor = await privateKey({filename: __filename});
- [alice] = await helper.arrange.createAccounts([20n], donor);
+ [alice, owner] = await helper.arrange.createAccounts([20n, 20n], donor);
});
});
@@ -151,17 +152,17 @@
itEth('Can perform burnFromCross()', async ({helper}) => {
const sender = await helper.eth.createAccountWithBalance(donor, 100n);
- const collection = await helper.ft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);
+ const collection = await helper.ft.mintCollection(owner, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);
- await collection.mint(alice, 200n, {Substrate: alice.address});
- await collection.approveTokens(alice, {Ethereum: sender}, 100n);
+ await collection.mint(owner, 200n, {Substrate: owner.address});
+ await collection.approveTokens(owner, {Ethereum: sender}, 100n);
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'ft');
- const fromBalanceBefore = await collection.getBalance({Substrate: alice.address});
+ const fromBalanceBefore = await collection.getBalance({Substrate: owner.address});
- const ownerCross = helper.ethCrossAccount.fromKeyringPair(alice);
+ const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);
const result = await contract.methods.burnFromCross(ownerCross, 49).send({from: sender});
const events = result.events;
@@ -170,7 +171,7 @@
address: helper.ethAddress.fromCollectionId(collection.collectionId),
event: 'Transfer',
returnValues: {
- from: helper.address.substrateToEth(alice.address),
+ from: helper.address.substrateToEth(owner.address),
to: '0x0000000000000000000000000000000000000000',
value: '49',
},
@@ -178,7 +179,7 @@
Approval: {
address: helper.ethAddress.fromCollectionId(collection.collectionId),
returnValues: {
- owner: helper.address.substrateToEth(alice.address),
+ owner: helper.address.substrateToEth(owner.address),
spender: sender,
value: '51',
},
@@ -186,7 +187,7 @@
},
});
- const fromBalanceAfter = await collection.getBalance({Substrate: alice.address});
+ const fromBalanceAfter = await collection.getBalance({Substrate: owner.address});
expect(fromBalanceBefore - fromBalanceAfter).to.be.eq(49n);
});
@@ -262,20 +263,20 @@
itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
const sender = await helper.eth.createAccountWithBalance(donor, 100n);
- const collection = await helper.ft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);
+ const collection = await helper.ft.mintCollection(owner, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);
const receiver = helper.eth.createAccount();
- await collection.mint(alice, 200n, {Substrate: alice.address});
- await collection.approveTokens(alice, {Ethereum: sender}, 100n);
+ await collection.mint(owner, 200n, {Substrate: owner.address});
+ await collection.approveTokens(owner, {Ethereum: sender}, 100n);
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'ft');
- const from = helper.ethCrossAccount.fromKeyringPair(alice);
+ const from = helper.ethCrossAccount.fromKeyringPair(owner);
const to = helper.ethCrossAccount.fromAddress(receiver);
- const fromBalanceBefore = await collection.getBalance({Substrate: alice.address});
+ const fromBalanceBefore = await collection.getBalance({Substrate: owner.address});
const toBalanceBefore = await collection.getBalance({Ethereum: receiver});
const result = await contract.methods.transferFromCross(from, to, 51).send({from: sender});
@@ -285,7 +286,7 @@
address,
event: 'Transfer',
returnValues: {
- from: helper.address.substrateToEth(alice.address),
+ from: helper.address.substrateToEth(owner.address),
to: receiver,
value: '51',
},
@@ -294,13 +295,13 @@
address,
event: 'Approval',
returnValues: {
- owner: helper.address.substrateToEth(alice.address),
+ owner: helper.address.substrateToEth(owner.address),
spender: sender,
value: '49',
},
}});
- const fromBalanceAfter = await collection.getBalance({Substrate: alice.address});
+ const fromBalanceAfter = await collection.getBalance({Substrate: owner.address});
expect(fromBalanceBefore - fromBalanceAfter).to.be.eq(51n);
const toBalanceAfter = await collection.getBalance({Ethereum: receiver});
expect(toBalanceAfter - toBalanceBefore).to.be.eq(51n);
@@ -363,11 +364,12 @@
describe('Fungible: Substrate calls', () => {
let donor: IKeyringPair;
let alice: IKeyringPair;
+ let owner: IKeyringPair;
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
donor = await privateKey({filename: __filename});
- [alice] = await helper.arrange.createAccounts([20n], donor);
+ [alice, owner] = await helper.arrange.createAccounts([20n, 20n], donor);
});
});
@@ -455,17 +457,17 @@
itEth('Events emitted for transferFromCross()', async ({helper, privateKey}) => {
const sender = await helper.eth.createAccountWithBalance(donor, 100n);
- const collection = await helper.ft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);
+ const collection = await helper.ft.mintCollection(owner, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);
const receiver = helper.eth.createAccount();
- await collection.mint(alice, 200n, {Substrate: alice.address});
- await collection.approveTokens(alice, {Ethereum: sender}, 100n);
+ await collection.mint(owner, 200n, {Substrate: owner.address});
+ await collection.approveTokens(owner, {Ethereum: sender}, 100n);
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'ft');
- const from = helper.ethCrossAccount.fromKeyringPair(alice);
+ const from = helper.ethCrossAccount.fromKeyringPair(owner);
const to = helper.ethCrossAccount.fromAddress(receiver);
const result = await contract.methods.transferFromCross(from, to, 51).send({from: sender});
@@ -475,7 +477,7 @@
address,
event: 'Transfer',
returnValues: {
- from: helper.address.substrateToEth(alice.address),
+ from: helper.address.substrateToEth(owner.address),
to: receiver,
value: '51',
},
@@ -484,7 +486,7 @@
address,
event: 'Approval',
returnValues: {
- owner: helper.address.substrateToEth(alice.address),
+ owner: helper.address.substrateToEth(owner.address),
spender: sender,
value: '49',
},
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -62,10 +62,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "newAdmin",
"type": "tuple"
}
@@ -88,10 +88,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "user",
"type": "tuple"
}
@@ -134,10 +134,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "spender",
"type": "tuple"
},
@@ -171,10 +171,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "from",
"type": "tuple"
},
@@ -200,10 +200,10 @@
"outputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6[]",
+ "internalType": "struct EthCrossAccount[]",
"name": "",
"type": "tuple[]"
}
@@ -217,10 +217,10 @@
"outputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "",
"type": "tuple"
}
@@ -239,7 +239,7 @@
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
],
- "internalType": "struct Tuple10[]",
+ "internalType": "struct Tuple14[]",
"name": "",
"type": "tuple[]"
}
@@ -263,7 +263,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct Tuple8",
"name": "",
"type": "tuple"
}
@@ -328,10 +328,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "user",
"type": "tuple"
}
@@ -358,7 +358,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple6[]",
+ "internalType": "struct Tuple8[]",
"name": "amounts",
"type": "tuple[]"
}
@@ -388,10 +388,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "admin",
"type": "tuple"
}
@@ -421,10 +421,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "user",
"type": "tuple"
}
@@ -496,7 +496,7 @@
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
],
- "internalType": "struct Tuple10[]",
+ "internalType": "struct Tuple14[]",
"name": "properties",
"type": "tuple[]"
}
@@ -529,10 +529,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "sponsor",
"type": "tuple"
}
@@ -546,10 +546,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "newOwner",
"type": "tuple"
}
@@ -607,19 +607,19 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "from",
"type": "tuple"
},
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "to",
"type": "tuple"
},
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -138,14 +138,14 @@
describe('NFT: Plain calls', () => {
let donor: IKeyringPair;
- let alice: IKeyringPair;
+ let minter: IKeyringPair;
let bob: IKeyringPair;
let charlie: IKeyringPair;
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ [minter, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
});
});
@@ -178,8 +178,8 @@
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collection = await helper.nft.mintCollection(alice);
- await collection.addAdmin(alice, {Ethereum: caller});
+ const collection = await helper.nft.mintCollection(minter);
+ await collection.addAdmin(minter, {Ethereum: caller});
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', caller);
@@ -210,8 +210,8 @@
itEth('Can perform burn()', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {});
- const {tokenId} = await collection.mintToken(alice, {Ethereum: caller});
+ const collection = await helper.nft.mintCollection(minter, {});
+ const {tokenId} = await collection.mintToken(minter, {Ethereum: caller});
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', caller);
@@ -231,8 +231,8 @@
const owner = await helper.eth.createAccountWithBalance(donor);
const spender = helper.eth.createAccount();
- const collection = await helper.nft.mintCollection(alice, {});
- const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});
+ const collection = await helper.nft.mintCollection(minter, {});
+ const {tokenId} = await collection.mintToken(minter, {Ethereum: owner});
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -248,13 +248,13 @@
}
});
- itEth('Can perform burnFromCross()', async ({helper, privateKey}) => {
- const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+ itEth('Can perform burnFromCross()', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
const owner = bob;
const spender = await helper.eth.createAccountWithBalance(donor, 100n);
- const token = await collection.mintToken(alice, {Substrate: owner.address});
+ const token = await collection.mintToken(minter, {Substrate: owner.address});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'nft');
@@ -277,13 +277,13 @@
}
});
- itEth('Can perform approveCross()', async ({helper, privateKey}) => {
- const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+ itEth('Can perform approveCross()', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
const owner = await helper.eth.createAccountWithBalance(donor, 100n);
const receiver = charlie;
- const token = await collection.mintToken(alice, {Ethereum: owner});
+ const token = await collection.mintToken(minter, {Ethereum: owner});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'nft');
@@ -309,8 +309,8 @@
const spender = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const collection = await helper.nft.mintCollection(alice, {});
- const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});
+ const collection = await helper.nft.mintCollection(minter, {});
+ const {tokenId} = await collection.mintToken(minter, {Ethereum: owner});
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -338,12 +338,46 @@
}
});
+ itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
+ const minter = await privateKey('//Alice');
+ const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+ const owner = await privateKey('//Bob');
+ const spender = await helper.eth.createAccountWithBalance(donor);
+ const receiver = await privateKey('//Charlie');
+
+ const token = await collection.mintToken(minter, {Substrate: owner.address});
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'nft');
+
+ await token.approve(owner, {Ethereum: spender});
+
+ {
+ const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);
+ const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+ const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender});
+ const event = result.events.Transfer;
+ expect(event).to.be.like({
+ address: helper.ethAddress.fromCollectionId(collection.collectionId),
+ event: 'Transfer',
+ returnValues: {
+ from: helper.address.substrateToEth(owner.address),
+ to: helper.address.substrateToEth(receiver.address),
+ tokenId: token.tokenId.toString(),
+ },
+ });
+ }
+
+ expect(await token.getOwner()).to.be.like({Substrate: receiver.address});
+ });
+
itEth('Can perform transfer()', async ({helper}) => {
- const collection = await helper.nft.mintCollection(alice, {});
+ const collection = await helper.nft.mintCollection(minter, {});
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});
+ const {tokenId} = await collection.mintToken(minter, {Ethereum: owner});
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -93,10 +93,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "newAdmin",
"type": "tuple"
}
@@ -119,10 +119,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "user",
"type": "tuple"
}
@@ -155,10 +155,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "approved",
"type": "tuple"
},
@@ -201,10 +201,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "from",
"type": "tuple"
},
@@ -230,10 +230,10 @@
"outputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6[]",
+ "internalType": "struct EthCrossAccount[]",
"name": "",
"type": "tuple[]"
}
@@ -247,10 +247,10 @@
"outputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "",
"type": "tuple"
}
@@ -269,7 +269,7 @@
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
],
- "internalType": "struct Tuple19[]",
+ "internalType": "struct Tuple21[]",
"name": "",
"type": "tuple[]"
}
@@ -293,7 +293,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct Tuple24",
"name": "",
"type": "tuple"
}
@@ -387,10 +387,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "user",
"type": "tuple"
}
@@ -470,10 +470,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "admin",
"type": "tuple"
}
@@ -503,10 +503,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "user",
"type": "tuple"
}
@@ -611,7 +611,7 @@
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
],
- "internalType": "struct Tuple19[]",
+ "internalType": "struct Tuple21[]",
"name": "properties",
"type": "tuple[]"
}
@@ -644,10 +644,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "sponsor",
"type": "tuple"
}
@@ -661,10 +661,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "newOwner",
"type": "tuple"
}
@@ -682,7 +682,7 @@
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
],
- "internalType": "struct Tuple19[]",
+ "internalType": "struct Tuple21[]",
"name": "properties",
"type": "tuple[]"
}
@@ -791,19 +791,19 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "from",
"type": "tuple"
},
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "to",
"type": "tuple"
},
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -104,7 +104,7 @@
describe('Refungible: Plain calls', () => {
let donor: IKeyringPair;
- let alice: IKeyringPair;
+ let minter: IKeyringPair;
let bob: IKeyringPair;
let charlie: IKeyringPair;
@@ -113,7 +113,7 @@
requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ [minter, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
});
});
@@ -231,13 +231,13 @@
}
});
- itEth('Can perform burnFrom()', async ({helper, privateKey}) => {
- const collection = await helper.rft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+ itEth('Can perform burnFrom()', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
const owner = await helper.eth.createAccountWithBalance(donor, 100n);
const spender = await helper.eth.createAccountWithBalance(donor, 100n);
- const token = await collection.mintToken(alice, 100n, {Ethereum: owner});
+ const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'rft');
@@ -264,13 +264,13 @@
expect(await collection.getTokenBalance(token.tokenId, {Ethereum: owner})).to.be.eq(0n);
});
- itEth('Can perform burnFromCross()', async ({helper, privateKey}) => {
- const collection = await helper.rft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+ itEth('Can perform burnFromCross()', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
const owner = bob;
const spender = await helper.eth.createAccountWithBalance(donor, 100n);
- const token = await collection.mintToken(alice, 100n, {Substrate: owner.address});
+ const token = await collection.mintToken(minter, 100n, {Substrate: owner.address});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'rft');
@@ -296,14 +296,14 @@
expect(await collection.getTokenBalance(token.tokenId, {Substrate: owner.address})).to.be.eq(0n);
});
- itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
- const collection = await helper.rft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+ itEth('Can perform transferFromCross()', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
const owner = bob;
const spender = await helper.eth.createAccountWithBalance(donor, 100n);
const receiver = charlie;
- const token = await collection.mintToken(alice, 100n, {Substrate: owner.address});
+ const token = await collection.mintToken(minter, 100n, {Substrate: owner.address});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'rft');
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -93,10 +93,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "newAdmin",
"type": "tuple"
}
@@ -119,10 +119,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "user",
"type": "tuple"
}
@@ -183,10 +183,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "from",
"type": "tuple"
},
@@ -212,10 +212,10 @@
"outputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6[]",
+ "internalType": "struct EthCrossAccount[]",
"name": "",
"type": "tuple[]"
}
@@ -229,10 +229,10 @@
"outputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "",
"type": "tuple"
}
@@ -251,7 +251,7 @@
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
],
- "internalType": "struct Tuple19[]",
+ "internalType": "struct Tuple20[]",
"name": "",
"type": "tuple[]"
}
@@ -275,7 +275,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct Tuple23",
"name": "",
"type": "tuple"
}
@@ -369,10 +369,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "user",
"type": "tuple"
}
@@ -452,10 +452,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "admin",
"type": "tuple"
}
@@ -485,10 +485,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "user",
"type": "tuple"
}
@@ -593,7 +593,7 @@
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
],
- "internalType": "struct Tuple19[]",
+ "internalType": "struct Tuple20[]",
"name": "properties",
"type": "tuple[]"
}
@@ -626,10 +626,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "sponsor",
"type": "tuple"
}
@@ -643,10 +643,10 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "newOwner",
"type": "tuple"
}
@@ -664,7 +664,7 @@
{ "internalType": "string", "name": "field_0", "type": "string" },
{ "internalType": "bytes", "name": "field_1", "type": "bytes" }
],
- "internalType": "struct Tuple19[]",
+ "internalType": "struct Tuple20[]",
"name": "properties",
"type": "tuple[]"
}
@@ -782,19 +782,19 @@
"inputs": [
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "from",
"type": "tuple"
},
{
"components": [
- { "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" }
],
- "internalType": "struct Tuple6",
+ "internalType": "struct EthCrossAccount",
"name": "to",
"type": "tuple"
},
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,
};
}
}
@@ -387,9 +383,9 @@
eth: EthGroup;
ethAddress: EthAddressGroup;
+ ethCrossAccount: EthCrossAccountGroup;
ethNativeContract: NativeContractGroup;
ethContract: ContractGroup;
- ethCrossAccount: EthCrossAccountGroup;
ethProperty: EthPropertyGroup;
constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -73,8 +73,8 @@
export interface IEthCrossAccountId {
0: TEthereumAccount;
1: TSubstrateAccount;
- field_0: TEthereumAccount;
- field_1: TSubstrateAccount;
+ eth: TEthereumAccount;
+ sub: TSubstrateAccount;
}
export interface ICollectionLimits {
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -7,8 +7,10 @@
import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';
import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';
-import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
+import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
+import {hexToU8a} from '@polkadot/util/hex';
+import {u8aConcat} from '@polkadot/util/u8a';
import {
IApiListeners,
IBlock,
@@ -38,6 +40,7 @@
AcalaAssetMetadata,
MoonbeamAssetInfo,
DemocracyStandardAccountVote,
+ IEthCrossAccountId,
} from './types';
import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';
@@ -2368,6 +2371,73 @@
return CrossAccountId.translateSubToEth(subAddress);
}
+ /**
+ * Encode key to substrate address
+ * @param key key for encoding address
+ * @param ss58Format prefix for encoding to the address of the corresponding network
+ * @returns encoded substrate address
+ */
+ encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {
+ const u8a :Uint8Array = typeof key === 'string'
+ ? hexToU8a(key)
+ : typeof key === 'bigint'
+ ? hexToU8a(key.toString(16))
+ : key;
+
+ if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {
+ throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);
+ }
+
+ const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];
+ if (!allowedDecodedLengths.includes(u8a.length)) {
+ throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);
+ }
+
+ const u8aPrefix = ss58Format < 64
+ ? new Uint8Array([ss58Format])
+ : new Uint8Array([
+ ((ss58Format & 0xfc) >> 2) | 0x40,
+ (ss58Format >> 8) | ((ss58Format & 0x03) << 6),
+ ]);
+
+ const input = u8aConcat(u8aPrefix, u8a);
+
+ return base58Encode(u8aConcat(
+ input,
+ blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),
+ ));
+ }
+
+ /**
+ * Restore substrate address from bigint representation
+ * @param number decimal representation of substrate address
+ * @returns substrate address
+ */
+ restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {
+ if (this.helper.api === null) {
+ throw 'Not connected';
+ }
+ const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();
+ if (res === undefined || res === null) {
+ throw 'Restore address error';
+ }
+ return res.toString();
+ }
+
+ /**
+ * Convert etherium cross account id to substrate cross account id
+ * @param ethCrossAccount etherium cross account
+ * @returns substrate cross account id
+ */
+ convertCrossAccountFromEthCrossAcoount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {
+ if (ethCrossAccount.sub === '0') {
+ return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};
+ }
+
+ const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));
+ return {Substrate: ss58};
+ }
+
paraSiblingSovereignAccount(paraid: number) {
// We are getting a *sibling* parachain sovereign account,
// so we need a sibling prefix: encoded(b"sibl") == 0x7369626c