difftreelog
Merge branch 'develop' into feature/ci-refactoring
in: master
73 files changed
.docker/forkless-config/launch-config-forkless-data.j2diffbeforeafterboth--- a/.docker/forkless-config/launch-config-forkless-data.j2
+++ b/.docker/forkless-config/launch-config-forkless-data.j2
@@ -107,7 +107,7 @@
"--rpc-cors=all",
"--unsafe-rpc-external",
"--unsafe-ws-external",
- "-lxcm=trace"
+ "-lxcm=trace,parity_ws::handler=debug,jsonrpsee_core=trace,jsonrpsee-core=trace,jsonrpsee_ws_server=debug"
]
},
{
@@ -119,7 +119,7 @@
"--rpc-cors=all",
"--unsafe-rpc-external",
"--unsafe-ws-external",
- "-lxcm=trace"
+ "-lxcm=trace,parity_ws::handler=debug,jsonrpsee_core=trace,jsonrpsee-core=trace,jsonrpsee_ws_server=debug"
]
}
]
.docker/forkless-config/launch-config-forkless-nodata.j2diffbeforeafterboth--- a/.docker/forkless-config/launch-config-forkless-nodata.j2
+++ b/.docker/forkless-config/launch-config-forkless-nodata.j2
@@ -101,7 +101,7 @@
"--rpc-cors=all",
"--unsafe-rpc-external",
"--unsafe-ws-external",
- "-lxcm=trace",
+ "-lxcm=trace,parity_ws::handler=debug,jsonrpsee_core=trace,jsonrpsee-core=trace,jsonrpsee_ws_server=debug",
"--ws-max-connections=1000"
]
},
@@ -114,7 +114,7 @@
"--rpc-cors=all",
"--unsafe-rpc-external",
"--unsafe-ws-external",
- "-lxcm=trace",
+ "-lxcm=trace,parity_ws::handler=debug,jsonrpsee_core=trace,jsonrpsee-core=trace,jsonrpsee_ws_server=debug",
"--ws-max-connections=1000"
]
}
.docker/forkless-config/launch-config-node-update-only-v3.j2diffbeforeafterboth--- a/.docker/forkless-config/launch-config-node-update-only-v3.j2
+++ b/.docker/forkless-config/launch-config-node-update-only-v3.j2
@@ -101,7 +101,7 @@
"--rpc-cors=all",
"--unsafe-rpc-external",
"--unsafe-ws-external",
- "-lxcm=trace",
+ "-lxcm=trace,parity_ws::handler=debug,jsonrpsee_core=trace,jsonrpsee-core=trace,jsonrpsee_ws_server=debug",
"--ws-max-connections=1000"
]
},
@@ -114,7 +114,7 @@
"--rpc-cors=all",
"--unsafe-rpc-external",
"--unsafe-ws-external",
- "-lxcm=trace",
+ "-lxcm=trace,parity_ws::handler=debug,jsonrpsee_core=trace,jsonrpsee-core=trace,jsonrpsee_ws_server=debug",
"--ws-max-connections=1000"
]
}
.docker/xcm-config/launch-config-xcm-opal.jsondiffbeforeafterboth--- a/.docker/xcm-config/launch-config-xcm-opal.json
+++ b/.docker/xcm-config/launch-config-xcm-opal.json
@@ -91,6 +91,7 @@
"name": "alice",
"flags": [
"--unsafe-rpc-external",
+ "-lxcm=trace,parity_ws::handler=debug,jsonrpsee_core=trace,jsonrpsee-core=trace,jsonrpsee_ws_server=debug",
"--unsafe-ws-external"
]
}
.docker/xcm-config/launch-config-xcm-quartz.jsondiffbeforeafterboth--- a/.docker/xcm-config/launch-config-xcm-quartz.json
+++ b/.docker/xcm-config/launch-config-xcm-quartz.json
@@ -90,6 +90,7 @@
"rpcPort": 9933,
"name": "alice",
"flags": [
+ "-lxcm=trace,parity_ws::handler=debug,jsonrpsee_core=trace,jsonrpsee-core=trace,jsonrpsee_ws_server=debug",
"--unsafe-rpc-external",
"--unsafe-ws-external"
]
.docker/xcm-config/launch-config-xcm-unique.jsondiffbeforeafterboth--- a/.docker/xcm-config/launch-config-xcm-unique.json
+++ b/.docker/xcm-config/launch-config-xcm-unique.json
@@ -90,6 +90,7 @@
"rpcPort": 9933,
"name": "alice",
"flags": [
+ "-lxcm=trace,parity_ws::handler=debug,jsonrpsee_core=trace,jsonrpsee-core=trace,jsonrpsee_ws_server=debug",
"--unsafe-rpc-external",
"--unsafe-ws-external"
]
.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.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -20,20 +20,20 @@
// about Procedural Macros in Rust book:
// https://doc.rust-lang.org/reference/procedural-macros.html
-use quote::{quote, ToTokens};
+use proc_macro2::TokenStream;
+use quote::{quote, format_ident};
use inflector::cases;
-use std::fmt::Write;
use syn::{
- Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
- MetaNameValue, PatType, PathArguments, ReturnType, Type,
+ Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,
+ PatType, ReturnType, Type,
spanned::Spanned,
parse::{Parse, ParseStream},
parenthesized, Token, LitInt, LitStr,
};
use crate::{
- fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,
- parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,
+ parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment, parse_result_ok,
+ pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,
snake_ident_to_screaming,
};
@@ -328,155 +328,47 @@
}
}
-enum AbiType {
- // type
- Plain(Ident),
- // (type1,type2)
- Tuple(Vec<AbiType>),
- // type[]
- Vec(Box<AbiType>),
- // type[20]
- Array(Box<AbiType>, usize),
+trait AbiType {
+ fn plain(&self) -> syn::Result<&Ident>;
+ fn is_value(&self) -> bool;
+ fn is_caller(&self) -> bool;
+ fn is_special(&self) -> bool;
}
-impl AbiType {
- fn try_from(value: &Type) -> syn::Result<Self> {
- let value = Self::try_maybe_special_from(value)?;
- if value.is_special() {
- return Err(syn::Error::new(value.span(), "unexpected special type"));
+
+impl AbiType for Type {
+ fn plain(&self) -> syn::Result<&Ident> {
+ let path = parse_path(self)?;
+ let segment = parse_path_segment(path)?;
+ if !segment.arguments.is_empty() {
+ return Err(syn::Error::new(self.span(), "Not plain type"));
}
- Ok(value)
+ Ok(&segment.ident)
}
- fn try_maybe_special_from(value: &Type) -> syn::Result<Self> {
- match value {
- Type::Array(arr) => {
- let wrapped = AbiType::try_from(&arr.elem)?;
- match &arr.len {
- Expr::Lit(l) => match &l.lit {
- Lit::Int(i) => {
- let num = i.base10_parse::<usize>()?;
- Ok(AbiType::Array(Box::new(wrapped), num as usize))
- }
- _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),
- },
- _ => Err(syn::Error::new(arr.len.span(), "should be literal")),
- }
- }
- Type::Path(_) => {
- let path = parse_path(value)?;
- let segment = parse_path_segment(path)?;
- if segment.ident == "Vec" {
- let args = match &segment.arguments {
- PathArguments::AngleBracketed(e) => e,
- _ => {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "missing Vec generic",
- ))
- }
- };
- let args = &args.args;
- if args.len() != 1 {
- return Err(syn::Error::new(
- args.span(),
- "expected only one generic for vec",
- ));
- }
- let arg = args.first().expect("first arg");
-
- let ty = match arg {
- GenericArgument::Type(ty) => ty,
- _ => {
- return Err(syn::Error::new(
- arg.span(),
- "expected first generic to be type",
- ))
- }
- };
- let wrapped = AbiType::try_from(ty)?;
- Ok(Self::Vec(Box::new(wrapped)))
- } else {
- if !segment.arguments.is_empty() {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "unexpected generic arguments for non-vec type",
- ));
- }
- Ok(Self::Plain(segment.ident.clone()))
- }
- }
- Type::Tuple(t) => {
- let mut out = Vec::with_capacity(t.elems.len());
- for el in t.elems.iter() {
- out.push(AbiType::try_from(el)?)
- }
- Ok(Self::Tuple(out))
- }
- _ => Err(syn::Error::new(
- value.span(),
- "unexpected type, only arrays, plain types and tuples are supported",
- )),
- }
- }
fn is_value(&self) -> bool {
- matches!(self, Self::Plain(v) if v == "value")
+ if let Ok(ident) = self.plain() {
+ return ident == "value";
+ }
+ false
}
+
fn is_caller(&self) -> bool {
- matches!(self, Self::Plain(v) if v == "caller")
+ if let Ok(ident) = self.plain() {
+ return ident == "caller";
+ }
+ false
}
+
fn is_special(&self) -> bool {
self.is_caller() || self.is_value()
}
- fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {
- match self {
- AbiType::Plain(t) => {
- write!(buf, "{}", t)
- }
- AbiType::Tuple(t) => {
- write!(buf, "(")?;
- for (i, t) in t.iter().enumerate() {
- if i != 0 {
- write!(buf, ",")?;
- }
- t.selector_ty_buf(buf)?;
- }
- write!(buf, ")")
- }
- AbiType::Vec(v) => {
- v.selector_ty_buf(buf)?;
- write!(buf, "[]")
- }
- AbiType::Array(v, len) => {
- v.selector_ty_buf(buf)?;
- write!(buf, "[{}]", len)
- }
- }
- }
- fn selector_ty(&self) -> String {
- let mut out = String::new();
- self.selector_ty_buf(&mut out).expect("no fmt error");
- out
- }
}
-impl ToTokens for AbiType {
- fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
- match self {
- AbiType::Plain(t) => tokens.extend(quote! {#t}),
- AbiType::Tuple(t) => {
- tokens.extend(quote! {(
- #(#t),*
- )});
- }
- AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),
- AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),
- }
- }
-}
+#[derive(Debug)]
struct MethodArg {
name: Ident,
camel_name: String,
- ty: AbiType,
+ ty: Type,
}
impl MethodArg {
fn try_from(value: &PatType) -> syn::Result<Self> {
@@ -484,7 +376,7 @@
Ok(Self {
camel_name: cases::camelcase::to_camel_case(&name.to_string()),
name,
- ty: AbiType::try_maybe_special_from(&value.ty)?,
+ ty: value.ty.as_ref().clone(),
})
}
fn is_value(&self) -> bool {
@@ -496,10 +388,6 @@
fn is_special(&self) -> bool {
self.ty.is_special()
}
- fn selector_ty(&self) -> String {
- assert!(!self.is_special());
- self.ty.selector_ty()
- }
fn expand_call_def(&self) -> proc_macro2::TokenStream {
assert!(!self.is_special());
@@ -514,8 +402,9 @@
fn expand_parse(&self) -> proc_macro2::TokenStream {
assert!(!self.is_special());
let name = &self.name;
+ let ty = &self.ty;
quote! {
- #name: reader.abi_read()?
+ #name: <#ty>::abi_read(reader)?
}
}
@@ -575,8 +464,6 @@
camel_name: String,
pascal_name: Ident,
screaming_name: Ident,
- selector_str: String,
- selector: u32,
hide: bool,
args: Vec<MethodArg>,
has_normal_args: bool,
@@ -667,27 +554,14 @@
let camel_name = info
.rename_selector
.unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));
- let mut selector_str = camel_name.clone();
- selector_str.push('(');
- let mut has_normal_args = false;
- for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {
- if i != 0 {
- selector_str.push(',');
- }
- write!(selector_str, "{}", arg.selector_ty()).unwrap();
- has_normal_args = true;
- }
+ let has_normal_args = args.iter().filter(|arg| !arg.is_special()).count() != 0;
let has_value_args = args.iter().any(|a| a.is_value());
- selector_str.push(')');
- let selector = fn_selector_str(&selector_str);
Ok(Self {
name: ident.clone(),
camel_name,
pascal_name: snake_ident_to_pascal(ident),
screaming_name: snake_ident_to_screaming(ident),
- selector_str,
- selector,
hide: info.hide,
args,
has_normal_args,
@@ -728,11 +602,20 @@
fn expand_const(&self) -> proc_macro2::TokenStream {
let screaming_name = &self.screaming_name;
- let selector = u32::to_be_bytes(self.selector);
- let selector_str = &self.selector_str;
+ let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);
+ let custom_signature = self.expand_custom_signature();
quote! {
- #[doc = #selector_str]
- const #screaming_name: ::evm_coder::types::bytes4 = [#(#selector,)*];
+ const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;
+ const #screaming_name: ::evm_coder::types::bytes4 = {
+ let mut sum = ::evm_coder::sha3_const::Keccak256::new();
+ let mut pos = 0;
+ while pos < Self::#screaming_name_signature.len {
+ sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);
+ pos += 1;
+ }
+ let a = sum.finalize();
+ [a[0], a[1], a[2], a[3]]
+ };
}
}
@@ -836,6 +719,26 @@
}
}
+ fn expand_custom_signature(&self) -> proc_macro2::TokenStream {
+ let mut args = TokenStream::new();
+
+ let mut has_params = false;
+ for arg in self.args.iter().filter(|a| !a.is_special()) {
+ has_params = true;
+ let ty = &arg.ty;
+ args.extend(quote! {nameof(<#ty>::SIGNATURE)});
+ args.extend(quote! {fixed(",")})
+ }
+
+ // Remove trailing comma
+ if has_params {
+ args.extend(quote! {shift_left(1)})
+ }
+
+ let func_name = self.camel_name.clone();
+ quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }
+ }
+
fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
let camel_name = &self.camel_name;
let mutability = match self.mutability {
@@ -851,16 +754,17 @@
.filter(|a| !a.is_special())
.map(MethodArg::expand_solidity_argument);
let docs = &self.docs;
- let selector_str = &self.selector_str;
- let selector = self.selector;
+ let screaming_name = &self.screaming_name;
let hide = self.hide;
+ let custom_signature = self.expand_custom_signature();
let is_payable = self.has_value_args;
+
quote! {
SolidityFunction {
docs: &[#(#docs),*],
- selector_str: #selector_str,
- selector: #selector,
hide: #hide,
+ selector: u32::from_be_bytes(Self::#screaming_name),
+ custom_signature: #custom_signature,
name: #camel_name,
mutability: #mutability,
is_payable: #is_payable,
@@ -1027,30 +931,6 @@
let docs = &self.docs;
- if let Some(expect_selector) = &self.info.expect_selector {
- if !self.info.inline_is.0.is_empty() {
- return syn::Error::new(
- name.span(),
- "expect_selector is not compatible with inline_is",
- )
- .to_compile_error();
- }
- let selector = self
- .methods
- .iter()
- .map(|m| m.selector)
- .fold(0, |a, b| a ^ b);
-
- if *expect_selector != selector {
- let mut methods = String::new();
- for meth in self.methods.iter() {
- write!(methods, "\n- {}", meth.selector_str).expect("write to string");
- }
- 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();
- }
- }
- // let methods = self.methods.iter().map(Method::solidity_def);
-
quote! {
#[derive(Debug)]
#(#[doc = #docs])*
@@ -1076,6 +956,7 @@
u32::to_be_bytes(interface_id)
}
/// 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/procedural/src/to_log.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/to_log.rs
+++ b/crates/evm-coder/procedural/src/to_log.rs
@@ -194,7 +194,9 @@
#(
#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.
@@ -230,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)
@@ -387,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(())
}
@@ -402,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(())
}
@@ -565,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(())
}
@@ -593,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(())
}
@@ -638,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))
}
@@ -657,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()),
))
}
@@ -683,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)
}
@@ -694,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/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/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.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31 CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},37 CollectionHandle, CollectionPropertyPermissions,38 eth::convert_tuple_to_cross_account,39};40use pallet_evm::{account::CrossAccountId, PrecompileHandle};41use pallet_evm_coder_substrate::call;42use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};4344use crate::{45 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,46 SelfWeightOf, weights::WeightInfo, TokenProperties,47};4849/// @title A contract that allows to set and delete token properties and change token property permissions.50#[solidity_interface(name = TokenProperties)]51impl<T: Config> NonfungibleHandle<T> {52 /// @notice Set permissions for token property.53 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.54 /// @param key Property key.55 /// @param isMutable Permission to mutate property.56 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.57 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.58 fn set_token_property_permission(59 &mut self,60 caller: caller,61 key: string,62 is_mutable: bool,63 collection_admin: bool,64 token_owner: bool,65 ) -> Result<()> {66 let caller = T::CrossAccountId::from_eth(caller);67 <Pallet<T>>::set_property_permission(68 self,69 &caller,70 PropertyKeyPermission {71 key: <Vec<u8>>::from(key)72 .try_into()73 .map_err(|_| "too long key")?,74 permission: PropertyPermission {75 mutable: is_mutable,76 collection_admin,77 token_owner,78 },79 },80 )81 .map_err(dispatch_to_evm::<T>)82 }8384 /// @notice Set token property value.85 /// @dev Throws error if `msg.sender` has no permission to edit the property.86 /// @param tokenId ID of the token.87 /// @param key Property key.88 /// @param value Property value.89 fn set_property(90 &mut self,91 caller: caller,92 token_id: uint256,93 key: string,94 value: bytes,95 ) -> Result<()> {96 let caller = T::CrossAccountId::from_eth(caller);97 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;98 let key = <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "key too long")?;101 let value = value.0.try_into().map_err(|_| "value too long")?;102103 let nesting_budget = self104 .recorder105 .weight_calls_budget(<StructureWeight<T>>::find_parent());106107 <Pallet<T>>::set_token_property(108 self,109 &caller,110 TokenId(token_id),111 Property { key, value },112 &nesting_budget,113 )114 .map_err(dispatch_to_evm::<T>)115 }116117 /// @notice Set token properties value.118 /// @dev Throws error if `msg.sender` has no permission to edit the property.119 /// @param tokenId ID of the token.120 /// @param properties settable properties121 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]122 fn set_properties(123 &mut self,124 caller: caller,125 token_id: uint256,126 properties: Vec<(string, bytes)>,127 ) -> Result<()> {128 let caller = T::CrossAccountId::from_eth(caller);129 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;130131 let nesting_budget = self132 .recorder133 .weight_calls_budget(<StructureWeight<T>>::find_parent());134135 let properties = properties136 .into_iter()137 .map(|(key, value)| {138 let key = <Vec<u8>>::from(key)139 .try_into()140 .map_err(|_| "key too large")?;141142 let value = value.0.try_into().map_err(|_| "value too large")?;143144 Ok(Property { key, value })145 })146 .collect::<Result<Vec<_>>>()?;147148 <Pallet<T>>::set_token_properties(149 self,150 &caller,151 TokenId(token_id),152 properties.into_iter(),153 <Pallet<T>>::token_exists(&self, TokenId(token_id)),154 &nesting_budget,155 )156 .map_err(dispatch_to_evm::<T>)157 }158159 /// @notice Delete token property value.160 /// @dev Throws error if `msg.sender` has no permission to edit the property.161 /// @param tokenId ID of the token.162 /// @param key Property key.163 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {164 let caller = T::CrossAccountId::from_eth(caller);165 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;166 let key = <Vec<u8>>::from(key)167 .try_into()168 .map_err(|_| "key too long")?;169170 let nesting_budget = self171 .recorder172 .weight_calls_budget(<StructureWeight<T>>::find_parent());173174 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)175 .map_err(dispatch_to_evm::<T>)176 }177178 /// @notice Get token property value.179 /// @dev Throws error if key not found180 /// @param tokenId ID of the token.181 /// @param key Property key.182 /// @return Property value bytes183 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {184 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;185 let key = <Vec<u8>>::from(key)186 .try_into()187 .map_err(|_| "key too long")?;188189 let props = <TokenProperties<T>>::get((self.id, token_id));190 let prop = props.get(&key).ok_or("key not found")?;191192 Ok(prop.to_vec().into())193 }194}195196#[derive(ToLog)]197pub enum ERC721Events {198 /// @dev This emits when ownership of any NFT changes by any mechanism.199 /// This event emits when NFTs are created (`from` == 0) and destroyed200 /// (`to` == 0). Exception: during contract creation, any number of NFTs201 /// may be created and assigned without emitting Transfer. At the time of202 /// any transfer, the approved address for that NFT (if any) is reset to none.203 Transfer {204 #[indexed]205 from: address,206 #[indexed]207 to: address,208 #[indexed]209 token_id: uint256,210 },211 /// @dev This emits when the approved address for an NFT is changed or212 /// reaffirmed. The zero address indicates there is no approved address.213 /// When a Transfer event emits, this also indicates that the approved214 /// address for that NFT (if any) is reset to none.215 Approval {216 #[indexed]217 owner: address,218 #[indexed]219 approved: address,220 #[indexed]221 token_id: uint256,222 },223 /// @dev This emits when an operator is enabled or disabled for an owner.224 /// The operator can manage all NFTs of the owner.225 #[allow(dead_code)]226 ApprovalForAll {227 #[indexed]228 owner: address,229 #[indexed]230 operator: address,231 approved: bool,232 },233}234235#[derive(ToLog)]236pub enum ERC721UniqueMintableEvents {237 #[allow(dead_code)]238 MintingFinished {},239}240241/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension242/// @dev See https://eips.ethereum.org/EIPS/eip-721243#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]244impl<T: Config> NonfungibleHandle<T>245where246 T::AccountId: From<[u8; 32]>,247{248 /// @notice A descriptive name for a collection of NFTs in this contract249 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`250 #[solidity(hide, rename_selector = "name")]251 fn name_proxy(&self) -> Result<string> {252 self.name()253 }254255 /// @notice An abbreviated name for NFTs in this contract256 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`257 #[solidity(hide, rename_selector = "symbol")]258 fn symbol_proxy(&self) -> Result<string> {259 self.symbol()260 }261262 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.263 ///264 /// @dev If the token has a `url` property and it is not empty, it is returned.265 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.266 /// If the collection property `baseURI` is empty or absent, return "" (empty string)267 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix268 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).269 ///270 /// @return token's const_metadata271 #[solidity(rename_selector = "tokenURI")]272 fn token_uri(&self, token_id: uint256) -> Result<string> {273 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;274275 match get_token_property(self, token_id_u32, &key::url()).as_deref() {276 Err(_) | Ok("") => (),277 Ok(url) => {278 return Ok(url.into());279 }280 };281282 let base_uri =283 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())284 .map(BoundedVec::into_inner)285 .map(string::from_utf8)286 .transpose()287 .map_err(|e| {288 Error::Revert(alloc::format!(289 "Can not convert value \"baseURI\" to string with error \"{}\"",290 e291 ))292 })?;293294 let base_uri = match base_uri.as_deref() {295 None | Some("") => {296 return Ok("".into());297 }298 Some(base_uri) => base_uri.into(),299 };300301 Ok(302 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {303 Err(_) | Ok("") => base_uri,304 Ok(suffix) => base_uri + suffix,305 },306 )307 }308}309310/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension311/// @dev See https://eips.ethereum.org/EIPS/eip-721312#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]313impl<T: Config> NonfungibleHandle<T> {314 /// @notice Enumerate valid NFTs315 /// @param index A counter less than `totalSupply()`316 /// @return The token identifier for the `index`th NFT,317 /// (sort order not specified)318 fn token_by_index(&self, index: uint256) -> Result<uint256> {319 Ok(index)320 }321322 /// @dev Not implemented323 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {324 // TODO: Not implemetable325 Err("not implemented".into())326 }327328 /// @notice Count NFTs tracked by this contract329 /// @return A count of valid NFTs tracked by this contract, where each one of330 /// them has an assigned and queryable owner not equal to the zero address331 fn total_supply(&self) -> Result<uint256> {332 self.consume_store_reads(1)?;333 Ok(<Pallet<T>>::total_supply(self).into())334 }335}336337/// @title ERC-721 Non-Fungible Token Standard338/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md339#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]340impl<T: Config> NonfungibleHandle<T> {341 /// @notice Count all NFTs assigned to an owner342 /// @dev NFTs assigned to the zero address are considered invalid, and this343 /// function throws for queries about the zero address.344 /// @param owner An address for whom to query the balance345 /// @return The number of NFTs owned by `owner`, possibly zero346 fn balance_of(&self, owner: address) -> Result<uint256> {347 self.consume_store_reads(1)?;348 let owner = T::CrossAccountId::from_eth(owner);349 let balance = <AccountBalance<T>>::get((self.id, owner));350 Ok(balance.into())351 }352 /// @notice Find the owner of an NFT353 /// @dev NFTs assigned to zero address are considered invalid, and queries354 /// about them do throw.355 /// @param tokenId The identifier for an NFT356 /// @return The address of the owner of the NFT357 fn owner_of(&self, token_id: uint256) -> Result<address> {358 self.consume_store_reads(1)?;359 let token: TokenId = token_id.try_into()?;360 Ok(*<TokenData<T>>::get((self.id, token))361 .ok_or("token not found")?362 .owner363 .as_eth())364 }365 /// @dev Not implemented366 #[solidity(rename_selector = "safeTransferFrom")]367 fn safe_transfer_from_with_data(368 &mut self,369 _from: address,370 _to: address,371 _token_id: uint256,372 _data: bytes,373 ) -> Result<void> {374 // TODO: Not implemetable375 Err("not implemented".into())376 }377 /// @dev Not implemented378 fn safe_transfer_from(379 &mut self,380 _from: address,381 _to: address,382 _token_id: uint256,383 ) -> Result<void> {384 // TODO: Not implemetable385 Err("not implemented".into())386 }387388 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE389 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE390 /// THEY MAY BE PERMANENTLY LOST391 /// @dev Throws unless `msg.sender` is the current owner or an authorized392 /// operator for this NFT. Throws if `from` is not the current owner. Throws393 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.394 /// @param from The current owner of the NFT395 /// @param to The new owner396 /// @param tokenId The NFT to transfer397 #[weight(<SelfWeightOf<T>>::transfer_from())]398 fn transfer_from(399 &mut self,400 caller: caller,401 from: address,402 to: address,403 token_id: uint256,404 ) -> Result<void> {405 let caller = T::CrossAccountId::from_eth(caller);406 let from = T::CrossAccountId::from_eth(from);407 let to = T::CrossAccountId::from_eth(to);408 let token = token_id.try_into()?;409 let budget = self410 .recorder411 .weight_calls_budget(<StructureWeight<T>>::find_parent());412413 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)414 .map_err(dispatch_to_evm::<T>)?;415 Ok(())416 }417418 /// @notice Set or reaffirm the approved address for an NFT419 /// @dev The zero address indicates there is no approved address.420 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized421 /// operator of the current owner.422 /// @param approved The new approved NFT controller423 /// @param tokenId The NFT to approve424 #[weight(<SelfWeightOf<T>>::approve())]425 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {426 let caller = T::CrossAccountId::from_eth(caller);427 let approved = T::CrossAccountId::from_eth(approved);428 let token = token_id.try_into()?;429430 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))431 .map_err(dispatch_to_evm::<T>)?;432 Ok(())433 }434435 /// @dev Not implemented436 fn set_approval_for_all(437 &mut self,438 _caller: caller,439 _operator: address,440 _approved: bool,441 ) -> Result<void> {442 // TODO: Not implemetable443 Err("not implemented".into())444 }445446 /// @dev Not implemented447 fn get_approved(&self, _token_id: uint256) -> Result<address> {448 // TODO: Not implemetable449 Err("not implemented".into())450 }451452 /// @dev Not implemented453 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {454 // TODO: Not implemetable455 Err("not implemented".into())456 }457}458459/// @title ERC721 Token that can be irreversibly burned (destroyed).460#[solidity_interface(name = ERC721Burnable)]461impl<T: Config> NonfungibleHandle<T> {462 /// @notice Burns a specific ERC721 token.463 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized464 /// operator of the current owner.465 /// @param tokenId The NFT to approve466 #[weight(<SelfWeightOf<T>>::burn_item())]467 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {468 let caller = T::CrossAccountId::from_eth(caller);469 let token = token_id.try_into()?;470471 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;472 Ok(())473 }474}475476/// @title ERC721 minting logic.477#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]478impl<T: Config> NonfungibleHandle<T> {479 fn minting_finished(&self) -> Result<bool> {480 Ok(false)481 }482483 /// @notice Function to mint token.484 /// @param to The new owner485 /// @return uint256 The id of the newly minted token486 #[weight(<SelfWeightOf<T>>::create_item())]487 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {488 let token_id: uint256 = <TokensMinted<T>>::get(self.id)489 .checked_add(1)490 .ok_or("item id overflow")?491 .into();492 self.mint_check_id(caller, to, token_id)?;493 Ok(token_id)494 }495496 /// @notice Function to mint token.497 /// @dev `tokenId` should be obtained with `nextTokenId` method,498 /// unlike standard, you can't specify it manually499 /// @param to The new owner500 /// @param tokenId ID of the minted NFT501 #[solidity(hide, rename_selector = "mint")]502 #[weight(<SelfWeightOf<T>>::create_item())]503 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {504 let caller = T::CrossAccountId::from_eth(caller);505 let to = T::CrossAccountId::from_eth(to);506 let token_id: u32 = token_id.try_into()?;507 let budget = self508 .recorder509 .weight_calls_budget(<StructureWeight<T>>::find_parent());510511 if <TokensMinted<T>>::get(self.id)512 .checked_add(1)513 .ok_or("item id overflow")?514 != token_id515 {516 return Err("item id should be next".into());517 }518519 <Pallet<T>>::create_item(520 self,521 &caller,522 CreateItemData::<T> {523 properties: BoundedVec::default(),524 owner: to,525 },526 &budget,527 )528 .map_err(dispatch_to_evm::<T>)?;529530 Ok(true)531 }532533 /// @notice Function to mint token with the given tokenUri.534 /// @param to The new owner535 /// @param tokenUri Token URI that would be stored in the NFT properties536 /// @return uint256 The id of the newly minted token537 #[solidity(rename_selector = "mintWithTokenURI")]538 #[weight(<SelfWeightOf<T>>::create_item())]539 fn mint_with_token_uri(540 &mut self,541 caller: caller,542 to: address,543 token_uri: string,544 ) -> Result<uint256> {545 let token_id: uint256 = <TokensMinted<T>>::get(self.id)546 .checked_add(1)547 .ok_or("item id overflow")?548 .into();549 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;550 Ok(token_id)551 }552553 /// @notice Function to mint token with the given tokenUri.554 /// @dev `tokenId` should be obtained with `nextTokenId` method,555 /// unlike standard, you can't specify it manually556 /// @param to The new owner557 /// @param tokenId ID of the minted NFT558 /// @param tokenUri Token URI that would be stored in the NFT properties559 #[solidity(hide, rename_selector = "mintWithTokenURI")]560 #[weight(<SelfWeightOf<T>>::create_item())]561 fn mint_with_token_uri_check_id(562 &mut self,563 caller: caller,564 to: address,565 token_id: uint256,566 token_uri: string,567 ) -> Result<bool> {568 let key = key::url();569 let permission = get_token_permission::<T>(self.id, &key)?;570 if !permission.collection_admin {571 return Err("Operation is not allowed".into());572 }573574 let caller = T::CrossAccountId::from_eth(caller);575 let to = T::CrossAccountId::from_eth(to);576 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;577 let budget = self578 .recorder579 .weight_calls_budget(<StructureWeight<T>>::find_parent());580581 if <TokensMinted<T>>::get(self.id)582 .checked_add(1)583 .ok_or("item id overflow")?584 != token_id585 {586 return Err("item id should be next".into());587 }588589 let mut properties = CollectionPropertiesVec::default();590 properties591 .try_push(Property {592 key,593 value: token_uri594 .into_bytes()595 .try_into()596 .map_err(|_| "token uri is too long")?,597 })598 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;599600 <Pallet<T>>::create_item(601 self,602 &caller,603 CreateItemData::<T> {604 properties,605 owner: to,606 },607 &budget,608 )609 .map_err(dispatch_to_evm::<T>)?;610 Ok(true)611 }612613 /// @dev Not implemented614 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {615 Err("not implementable".into())616 }617}618619fn get_token_property<T: Config>(620 collection: &CollectionHandle<T>,621 token_id: u32,622 key: &up_data_structs::PropertyKey,623) -> Result<string> {624 collection.consume_store_reads(1)?;625 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))626 .map_err(|_| Error::Revert("Token properties not found".into()))?;627 if let Some(property) = properties.get(key) {628 return Ok(string::from_utf8_lossy(property).into());629 }630631 Err("Property tokenURI not found".into())632}633634fn get_token_permission<T: Config>(635 collection_id: CollectionId,636 key: &PropertyKey,637) -> Result<PropertyPermission> {638 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)639 .map_err(|_| Error::Revert("No permissions for collection".into()))?;640 let a = token_property_permissions641 .get(key)642 .map(Clone::clone)643 .ok_or_else(|| {644 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();645 Error::Revert(alloc::format!("No permission for key {}", key))646 })?;647 Ok(a)648}649650/// @title Unique extensions for ERC721.651#[solidity_interface(name = ERC721UniqueExtensions)]652impl<T: Config> NonfungibleHandle<T>653where654 T::AccountId: From<[u8; 32]>,655{656 /// @notice A descriptive name for a collection of NFTs in this contract657 fn name(&self) -> Result<string> {658 Ok(decode_utf16(self.name.iter().copied())659 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))660 .collect::<string>())661 }662663 /// @notice An abbreviated name for NFTs in this contract664 fn symbol(&self) -> Result<string> {665 Ok(string::from_utf8_lossy(&self.token_prefix).into())666 }667668 /// @notice Set or reaffirm the approved address for an NFT669 /// @dev The zero address indicates there is no approved address.670 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized671 /// operator of the current owner.672 /// @param approved The new substrate address approved NFT controller673 /// @param tokenId The NFT to approve674 #[weight(<SelfWeightOf<T>>::approve())]675 fn approve_cross(676 &mut self,677 caller: caller,678 approved: (address, uint256),679 token_id: uint256,680 ) -> Result<void> {681 let caller = T::CrossAccountId::from_eth(caller);682 let approved = convert_tuple_to_cross_account::<T>(approved)?;683 let token = token_id.try_into()?;684685 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))686 .map_err(dispatch_to_evm::<T>)?;687 Ok(())688 }689690 /// @notice Transfer ownership of an NFT691 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`692 /// is the zero address. Throws if `tokenId` is not a valid NFT.693 /// @param to The new owner694 /// @param tokenId The NFT to transfer695 #[weight(<SelfWeightOf<T>>::transfer())]696 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {697 let caller = T::CrossAccountId::from_eth(caller);698 let to = T::CrossAccountId::from_eth(to);699 let token = token_id.try_into()?;700 let budget = self701 .recorder702 .weight_calls_budget(<StructureWeight<T>>::find_parent());703704 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;705 Ok(())706 }707708 /// @notice Transfer ownership of an NFT from cross account address to cross account address709 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`710 /// is the zero address. Throws if `tokenId` is not a valid NFT.711 /// @param from Cross acccount address of current owner712 /// @param to Cross acccount address of new owner713 /// @param tokenId The NFT to transfer714 #[weight(<SelfWeightOf<T>>::transfer())]715 fn transfer_from_cross(716 &mut self,717 caller: caller,718 from: (address, uint256),719 to: (address, uint256),720 token_id: uint256,721 ) -> Result<void> {722 let caller = T::CrossAccountId::from_eth(caller);723 let from = convert_tuple_to_cross_account::<T>(from)?;724 let to = convert_tuple_to_cross_account::<T>(to)?;725 let token_id = token_id.try_into()?;726 let budget = self727 .recorder728 .weight_calls_budget(<StructureWeight<T>>::find_parent());729 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)730 .map_err(dispatch_to_evm::<T>)?;731 Ok(())732 }733734 /// @notice Burns a specific ERC721 token.735 /// @dev Throws unless `msg.sender` is the current owner or an authorized736 /// operator for this NFT. Throws if `from` is not the current owner. Throws737 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.738 /// @param from The current owner of the NFT739 /// @param tokenId The NFT to transfer740 #[weight(<SelfWeightOf<T>>::burn_from())]741 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {742 let caller = T::CrossAccountId::from_eth(caller);743 let from = T::CrossAccountId::from_eth(from);744 let token = token_id.try_into()?;745 let budget = self746 .recorder747 .weight_calls_budget(<StructureWeight<T>>::find_parent());748749 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)750 .map_err(dispatch_to_evm::<T>)?;751 Ok(())752 }753754 /// @notice Burns a specific ERC721 token.755 /// @dev Throws unless `msg.sender` is the current owner or an authorized756 /// operator for this NFT. Throws if `from` is not the current owner. Throws757 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.758 /// @param from The current owner of the NFT759 /// @param tokenId The NFT to transfer760 #[weight(<SelfWeightOf<T>>::burn_from())]761 fn burn_from_cross(762 &mut self,763 caller: caller,764 from: (address, uint256),765 token_id: uint256,766 ) -> Result<void> {767 let caller = T::CrossAccountId::from_eth(caller);768 let from = convert_tuple_to_cross_account::<T>(from)?;769 let token = token_id.try_into()?;770 let budget = self771 .recorder772 .weight_calls_budget(<StructureWeight<T>>::find_parent());773774 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)775 .map_err(dispatch_to_evm::<T>)?;776 Ok(())777 }778779 /// @notice Returns next free NFT ID.780 fn next_token_id(&self) -> Result<uint256> {781 self.consume_store_reads(1)?;782 Ok(<TokensMinted<T>>::get(self.id)783 .checked_add(1)784 .ok_or("item id overflow")?785 .into())786 }787788 /// @notice Function to mint multiple tokens.789 /// @dev `tokenIds` should be an array of consecutive numbers and first number790 /// should be obtained with `nextTokenId` method791 /// @param to The new owner792 /// @param tokenIds IDs of the minted NFTs793 #[solidity(hide)]794 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]795 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {796 let caller = T::CrossAccountId::from_eth(caller);797 let to = T::CrossAccountId::from_eth(to);798 let mut expected_index = <TokensMinted<T>>::get(self.id)799 .checked_add(1)800 .ok_or("item id overflow")?;801 let budget = self802 .recorder803 .weight_calls_budget(<StructureWeight<T>>::find_parent());804805 let total_tokens = token_ids.len();806 for id in token_ids.into_iter() {807 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;808 if id != expected_index {809 return Err("item id should be next".into());810 }811 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;812 }813 let data = (0..total_tokens)814 .map(|_| CreateItemData::<T> {815 properties: BoundedVec::default(),816 owner: to.clone(),817 })818 .collect();819820 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)821 .map_err(dispatch_to_evm::<T>)?;822 Ok(true)823 }824825 /// @notice Function to mint multiple tokens with the given tokenUris.826 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive827 /// numbers and first number should be obtained with `nextTokenId` method828 /// @param to The new owner829 /// @param tokens array of pairs of token ID and token URI for minted tokens830 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]831 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]832 fn mint_bulk_with_token_uri(833 &mut self,834 caller: caller,835 to: address,836 tokens: Vec<(uint256, string)>,837 ) -> Result<bool> {838 let key = key::url();839 let caller = T::CrossAccountId::from_eth(caller);840 let to = T::CrossAccountId::from_eth(to);841 let mut expected_index = <TokensMinted<T>>::get(self.id)842 .checked_add(1)843 .ok_or("item id overflow")?;844 let budget = self845 .recorder846 .weight_calls_budget(<StructureWeight<T>>::find_parent());847848 let mut data = Vec::with_capacity(tokens.len());849 for (id, token_uri) in tokens {850 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;851 if id != expected_index {852 return Err("item id should be next".into());853 }854 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;855856 let mut properties = CollectionPropertiesVec::default();857 properties858 .try_push(Property {859 key: key.clone(),860 value: token_uri861 .into_bytes()862 .try_into()863 .map_err(|_| "token uri is too long")?,864 })865 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;866867 data.push(CreateItemData::<T> {868 properties,869 owner: to.clone(),870 });871 }872873 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)874 .map_err(dispatch_to_evm::<T>)?;875 Ok(true)876 }877}878879#[solidity_interface(880 name = UniqueNFT,881 is(882 ERC721,883 ERC721Enumerable,884 ERC721UniqueExtensions,885 ERC721UniqueMintable,886 ERC721Burnable,887 ERC721Metadata(if(this.flags.erc721metadata)),888 Collection(via(common_mut returns CollectionHandle<T>)),889 TokenProperties,890 )891)]892impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}893894// Not a tests, but code generators895generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);896generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);897898impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>899where900 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,901{902 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");903904 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {905 call::<T, UniqueNFTCall<T>, _, _>(handle, self)906 }907}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31 CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},37 CollectionHandle, CollectionPropertyPermissions,38};39use pallet_evm::{account::CrossAccountId, PrecompileHandle};40use pallet_evm_coder_substrate::call;41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};4243use crate::{44 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,45 SelfWeightOf, weights::WeightInfo, TokenProperties,46};4748/// @title A contract that allows to set and delete token properties and change token property permissions.49#[solidity_interface(name = TokenProperties)]50impl<T: Config> NonfungibleHandle<T> {51 /// @notice Set permissions for token property.52 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.53 /// @param key Property key.54 /// @param isMutable Permission to mutate property.55 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.56 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.57 fn set_token_property_permission(58 &mut self,59 caller: caller,60 key: string,61 is_mutable: bool,62 collection_admin: bool,63 token_owner: bool,64 ) -> Result<()> {65 let caller = T::CrossAccountId::from_eth(caller);66 <Pallet<T>>::set_property_permission(67 self,68 &caller,69 PropertyKeyPermission {70 key: <Vec<u8>>::from(key)71 .try_into()72 .map_err(|_| "too long key")?,73 permission: PropertyPermission {74 mutable: is_mutable,75 collection_admin,76 token_owner,77 },78 },79 )80 .map_err(dispatch_to_evm::<T>)81 }8283 /// @notice Set token property value.84 /// @dev Throws error if `msg.sender` has no permission to edit the property.85 /// @param tokenId ID of the token.86 /// @param key Property key.87 /// @param value Property value.88 fn set_property(89 &mut self,90 caller: caller,91 token_id: uint256,92 key: string,93 value: bytes,94 ) -> Result<()> {95 let caller = T::CrossAccountId::from_eth(caller);96 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;97 let key = <Vec<u8>>::from(key)98 .try_into()99 .map_err(|_| "key too long")?;100 let value = value.0.try_into().map_err(|_| "value too long")?;101102 let nesting_budget = self103 .recorder104 .weight_calls_budget(<StructureWeight<T>>::find_parent());105106 <Pallet<T>>::set_token_property(107 self,108 &caller,109 TokenId(token_id),110 Property { key, value },111 &nesting_budget,112 )113 .map_err(dispatch_to_evm::<T>)114 }115116 /// @notice Set token properties value.117 /// @dev Throws error if `msg.sender` has no permission to edit the property.118 /// @param tokenId ID of the token.119 /// @param properties settable properties120 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]121 fn set_properties(122 &mut self,123 caller: caller,124 token_id: uint256,125 properties: Vec<(string, bytes)>,126 ) -> Result<()> {127 let caller = T::CrossAccountId::from_eth(caller);128 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;129130 let nesting_budget = self131 .recorder132 .weight_calls_budget(<StructureWeight<T>>::find_parent());133134 let properties = properties135 .into_iter()136 .map(|(key, value)| {137 let key = <Vec<u8>>::from(key)138 .try_into()139 .map_err(|_| "key too large")?;140141 let value = value.0.try_into().map_err(|_| "value too large")?;142143 Ok(Property { key, value })144 })145 .collect::<Result<Vec<_>>>()?;146147 <Pallet<T>>::set_token_properties(148 self,149 &caller,150 TokenId(token_id),151 properties.into_iter(),152 <Pallet<T>>::token_exists(&self, TokenId(token_id)),153 &nesting_budget,154 )155 .map_err(dispatch_to_evm::<T>)156 }157158 /// @notice Delete token property value.159 /// @dev Throws error if `msg.sender` has no permission to edit the property.160 /// @param tokenId ID of the token.161 /// @param key Property key.162 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {163 let caller = T::CrossAccountId::from_eth(caller);164 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;165 let key = <Vec<u8>>::from(key)166 .try_into()167 .map_err(|_| "key too long")?;168169 let nesting_budget = self170 .recorder171 .weight_calls_budget(<StructureWeight<T>>::find_parent());172173 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)174 .map_err(dispatch_to_evm::<T>)175 }176177 /// @notice Get token property value.178 /// @dev Throws error if key not found179 /// @param tokenId ID of the token.180 /// @param key Property key.181 /// @return Property value bytes182 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {183 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;184 let key = <Vec<u8>>::from(key)185 .try_into()186 .map_err(|_| "key too long")?;187188 let props = <TokenProperties<T>>::get((self.id, token_id));189 let prop = props.get(&key).ok_or("key not found")?;190191 Ok(prop.to_vec().into())192 }193}194195#[derive(ToLog)]196pub enum ERC721Events {197 /// @dev This emits when ownership of any NFT changes by any mechanism.198 /// This event emits when NFTs are created (`from` == 0) and destroyed199 /// (`to` == 0). Exception: during contract creation, any number of NFTs200 /// may be created and assigned without emitting Transfer. At the time of201 /// any transfer, the approved address for that NFT (if any) is reset to none.202 Transfer {203 #[indexed]204 from: address,205 #[indexed]206 to: address,207 #[indexed]208 token_id: uint256,209 },210 /// @dev This emits when the approved address for an NFT is changed or211 /// reaffirmed. The zero address indicates there is no approved address.212 /// When a Transfer event emits, this also indicates that the approved213 /// address for that NFT (if any) is reset to none.214 Approval {215 #[indexed]216 owner: address,217 #[indexed]218 approved: address,219 #[indexed]220 token_id: uint256,221 },222 /// @dev This emits when an operator is enabled or disabled for an owner.223 /// The operator can manage all NFTs of the owner.224 #[allow(dead_code)]225 ApprovalForAll {226 #[indexed]227 owner: address,228 #[indexed]229 operator: address,230 approved: bool,231 },232}233234#[derive(ToLog)]235pub enum ERC721UniqueMintableEvents {236 #[allow(dead_code)]237 MintingFinished {},238}239240/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension241/// @dev See https://eips.ethereum.org/EIPS/eip-721242#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]243impl<T: Config> NonfungibleHandle<T>244where245 T::AccountId: From<[u8; 32]>,246{247 /// @notice A descriptive name for a collection of NFTs in this contract248 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`249 #[solidity(hide, rename_selector = "name")]250 fn name_proxy(&self) -> Result<string> {251 self.name()252 }253254 /// @notice An abbreviated name for NFTs in this contract255 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`256 #[solidity(hide, rename_selector = "symbol")]257 fn symbol_proxy(&self) -> Result<string> {258 self.symbol()259 }260261 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.262 ///263 /// @dev If the token has a `url` property and it is not empty, it is returned.264 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.265 /// If the collection property `baseURI` is empty or absent, return "" (empty string)266 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix267 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).268 ///269 /// @return token's const_metadata270 #[solidity(rename_selector = "tokenURI")]271 fn token_uri(&self, token_id: uint256) -> Result<string> {272 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;273274 match get_token_property(self, token_id_u32, &key::url()).as_deref() {275 Err(_) | Ok("") => (),276 Ok(url) => {277 return Ok(url.into());278 }279 };280281 let base_uri =282 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())283 .map(BoundedVec::into_inner)284 .map(string::from_utf8)285 .transpose()286 .map_err(|e| {287 Error::Revert(alloc::format!(288 "Can not convert value \"baseURI\" to string with error \"{}\"",289 e290 ))291 })?;292293 let base_uri = match base_uri.as_deref() {294 None | Some("") => {295 return Ok("".into());296 }297 Some(base_uri) => base_uri.into(),298 };299300 Ok(301 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {302 Err(_) | Ok("") => base_uri,303 Ok(suffix) => base_uri + suffix,304 },305 )306 }307}308309/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension310/// @dev See https://eips.ethereum.org/EIPS/eip-721311#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]312impl<T: Config> NonfungibleHandle<T> {313 /// @notice Enumerate valid NFTs314 /// @param index A counter less than `totalSupply()`315 /// @return The token identifier for the `index`th NFT,316 /// (sort order not specified)317 fn token_by_index(&self, index: uint256) -> Result<uint256> {318 Ok(index)319 }320321 /// @dev Not implemented322 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {323 // TODO: Not implemetable324 Err("not implemented".into())325 }326327 /// @notice Count NFTs tracked by this contract328 /// @return A count of valid NFTs tracked by this contract, where each one of329 /// them has an assigned and queryable owner not equal to the zero address330 fn total_supply(&self) -> Result<uint256> {331 self.consume_store_reads(1)?;332 Ok(<Pallet<T>>::total_supply(self).into())333 }334}335336/// @title ERC-721 Non-Fungible Token Standard337/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md338#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]339impl<T: Config> NonfungibleHandle<T> {340 /// @notice Count all NFTs assigned to an owner341 /// @dev NFTs assigned to the zero address are considered invalid, and this342 /// function throws for queries about the zero address.343 /// @param owner An address for whom to query the balance344 /// @return The number of NFTs owned by `owner`, possibly zero345 fn balance_of(&self, owner: address) -> Result<uint256> {346 self.consume_store_reads(1)?;347 let owner = T::CrossAccountId::from_eth(owner);348 let balance = <AccountBalance<T>>::get((self.id, owner));349 Ok(balance.into())350 }351 /// @notice Find the owner of an NFT352 /// @dev NFTs assigned to zero address are considered invalid, and queries353 /// about them do throw.354 /// @param tokenId The identifier for an NFT355 /// @return The address of the owner of the NFT356 fn owner_of(&self, token_id: uint256) -> Result<address> {357 self.consume_store_reads(1)?;358 let token: TokenId = token_id.try_into()?;359 Ok(*<TokenData<T>>::get((self.id, token))360 .ok_or("token not found")?361 .owner362 .as_eth())363 }364 /// @dev Not implemented365 #[solidity(rename_selector = "safeTransferFrom")]366 fn safe_transfer_from_with_data(367 &mut self,368 _from: address,369 _to: address,370 _token_id: uint256,371 _data: bytes,372 ) -> Result<void> {373 // TODO: Not implemetable374 Err("not implemented".into())375 }376 /// @dev Not implemented377 fn safe_transfer_from(378 &mut self,379 _from: address,380 _to: address,381 _token_id: uint256,382 ) -> Result<void> {383 // TODO: Not implemetable384 Err("not implemented".into())385 }386387 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE388 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE389 /// THEY MAY BE PERMANENTLY LOST390 /// @dev Throws unless `msg.sender` is the current owner or an authorized391 /// operator for this NFT. Throws if `from` is not the current owner. Throws392 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.393 /// @param from The current owner of the NFT394 /// @param to The new owner395 /// @param tokenId The NFT to transfer396 #[weight(<SelfWeightOf<T>>::transfer_from())]397 fn transfer_from(398 &mut self,399 caller: caller,400 from: address,401 to: address,402 token_id: uint256,403 ) -> Result<void> {404 let caller = T::CrossAccountId::from_eth(caller);405 let from = T::CrossAccountId::from_eth(from);406 let to = T::CrossAccountId::from_eth(to);407 let token = token_id.try_into()?;408 let budget = self409 .recorder410 .weight_calls_budget(<StructureWeight<T>>::find_parent());411412 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)413 .map_err(dispatch_to_evm::<T>)?;414 Ok(())415 }416417 /// @notice Set or reaffirm the approved address for an NFT418 /// @dev The zero address indicates there is no approved address.419 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized420 /// operator of the current owner.421 /// @param approved The new approved NFT controller422 /// @param tokenId The NFT to approve423 #[weight(<SelfWeightOf<T>>::approve())]424 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {425 let caller = T::CrossAccountId::from_eth(caller);426 let approved = T::CrossAccountId::from_eth(approved);427 let token = token_id.try_into()?;428429 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))430 .map_err(dispatch_to_evm::<T>)?;431 Ok(())432 }433434 /// @dev Not implemented435 fn set_approval_for_all(436 &mut self,437 _caller: caller,438 _operator: address,439 _approved: bool,440 ) -> Result<void> {441 // TODO: Not implemetable442 Err("not implemented".into())443 }444445 /// @dev Not implemented446 fn get_approved(&self, _token_id: uint256) -> Result<address> {447 // TODO: Not implemetable448 Err("not implemented".into())449 }450451 /// @dev Not implemented452 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {453 // TODO: Not implemetable454 Err("not implemented".into())455 }456}457458/// @title ERC721 Token that can be irreversibly burned (destroyed).459#[solidity_interface(name = ERC721Burnable)]460impl<T: Config> NonfungibleHandle<T> {461 /// @notice Burns a specific ERC721 token.462 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized463 /// operator of the current owner.464 /// @param tokenId The NFT to approve465 #[weight(<SelfWeightOf<T>>::burn_item())]466 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {467 let caller = T::CrossAccountId::from_eth(caller);468 let token = token_id.try_into()?;469470 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;471 Ok(())472 }473}474475/// @title ERC721 minting logic.476#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]477impl<T: Config> NonfungibleHandle<T> {478 fn minting_finished(&self) -> Result<bool> {479 Ok(false)480 }481482 /// @notice Function to mint token.483 /// @param to The new owner484 /// @return uint256 The id of the newly minted token485 #[weight(<SelfWeightOf<T>>::create_item())]486 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {487 let token_id: uint256 = <TokensMinted<T>>::get(self.id)488 .checked_add(1)489 .ok_or("item id overflow")?490 .into();491 self.mint_check_id(caller, to, token_id)?;492 Ok(token_id)493 }494495 /// @notice Function to mint token.496 /// @dev `tokenId` should be obtained with `nextTokenId` method,497 /// unlike standard, you can't specify it manually498 /// @param to The new owner499 /// @param tokenId ID of the minted NFT500 #[solidity(hide, rename_selector = "mint")]501 #[weight(<SelfWeightOf<T>>::create_item())]502 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {503 let caller = T::CrossAccountId::from_eth(caller);504 let to = T::CrossAccountId::from_eth(to);505 let token_id: u32 = token_id.try_into()?;506 let budget = self507 .recorder508 .weight_calls_budget(<StructureWeight<T>>::find_parent());509510 if <TokensMinted<T>>::get(self.id)511 .checked_add(1)512 .ok_or("item id overflow")?513 != token_id514 {515 return Err("item id should be next".into());516 }517518 <Pallet<T>>::create_item(519 self,520 &caller,521 CreateItemData::<T> {522 properties: BoundedVec::default(),523 owner: to,524 },525 &budget,526 )527 .map_err(dispatch_to_evm::<T>)?;528529 Ok(true)530 }531532 /// @notice Function to mint token with the given tokenUri.533 /// @param to The new owner534 /// @param tokenUri Token URI that would be stored in the NFT properties535 /// @return uint256 The id of the newly minted token536 #[solidity(rename_selector = "mintWithTokenURI")]537 #[weight(<SelfWeightOf<T>>::create_item())]538 fn mint_with_token_uri(539 &mut self,540 caller: caller,541 to: address,542 token_uri: string,543 ) -> Result<uint256> {544 let token_id: uint256 = <TokensMinted<T>>::get(self.id)545 .checked_add(1)546 .ok_or("item id overflow")?547 .into();548 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;549 Ok(token_id)550 }551552 /// @notice Function to mint token with the given tokenUri.553 /// @dev `tokenId` should be obtained with `nextTokenId` method,554 /// unlike standard, you can't specify it manually555 /// @param to The new owner556 /// @param tokenId ID of the minted NFT557 /// @param tokenUri Token URI that would be stored in the NFT properties558 #[solidity(hide, rename_selector = "mintWithTokenURI")]559 #[weight(<SelfWeightOf<T>>::create_item())]560 fn mint_with_token_uri_check_id(561 &mut self,562 caller: caller,563 to: address,564 token_id: uint256,565 token_uri: string,566 ) -> Result<bool> {567 let key = key::url();568 let permission = get_token_permission::<T>(self.id, &key)?;569 if !permission.collection_admin {570 return Err("Operation is not allowed".into());571 }572573 let caller = T::CrossAccountId::from_eth(caller);574 let to = T::CrossAccountId::from_eth(to);575 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;576 let budget = self577 .recorder578 .weight_calls_budget(<StructureWeight<T>>::find_parent());579580 if <TokensMinted<T>>::get(self.id)581 .checked_add(1)582 .ok_or("item id overflow")?583 != token_id584 {585 return Err("item id should be next".into());586 }587588 let mut properties = CollectionPropertiesVec::default();589 properties590 .try_push(Property {591 key,592 value: token_uri593 .into_bytes()594 .try_into()595 .map_err(|_| "token uri is too long")?,596 })597 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;598599 <Pallet<T>>::create_item(600 self,601 &caller,602 CreateItemData::<T> {603 properties,604 owner: to,605 },606 &budget,607 )608 .map_err(dispatch_to_evm::<T>)?;609 Ok(true)610 }611612 /// @dev Not implemented613 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {614 Err("not implementable".into())615 }616}617618fn get_token_property<T: Config>(619 collection: &CollectionHandle<T>,620 token_id: u32,621 key: &up_data_structs::PropertyKey,622) -> Result<string> {623 collection.consume_store_reads(1)?;624 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))625 .map_err(|_| Error::Revert("Token properties not found".into()))?;626 if let Some(property) = properties.get(key) {627 return Ok(string::from_utf8_lossy(property).into());628 }629630 Err("Property tokenURI not found".into())631}632633fn get_token_permission<T: Config>(634 collection_id: CollectionId,635 key: &PropertyKey,636) -> Result<PropertyPermission> {637 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)638 .map_err(|_| Error::Revert("No permissions for collection".into()))?;639 let a = token_property_permissions640 .get(key)641 .map(Clone::clone)642 .ok_or_else(|| {643 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();644 Error::Revert(alloc::format!("No permission for key {}", key))645 })?;646 Ok(a)647}648649/// @title Unique extensions for ERC721.650#[solidity_interface(name = ERC721UniqueExtensions)]651impl<T: Config> NonfungibleHandle<T>652where653 T::AccountId: From<[u8; 32]>,654{655 /// @notice A descriptive name for a collection of NFTs in this contract656 fn name(&self) -> Result<string> {657 Ok(decode_utf16(self.name.iter().copied())658 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))659 .collect::<string>())660 }661662 /// @notice An abbreviated name for NFTs in this contract663 fn symbol(&self) -> Result<string> {664 Ok(string::from_utf8_lossy(&self.token_prefix).into())665 }666667 /// @notice Set or reaffirm the approved address for an NFT668 /// @dev The zero address indicates there is no approved address.669 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized670 /// operator of the current owner.671 /// @param approved The new substrate address approved NFT controller672 /// @param tokenId The NFT to approve673 #[weight(<SelfWeightOf<T>>::approve())]674 fn approve_cross(675 &mut self,676 caller: caller,677 approved: EthCrossAccount,678 token_id: uint256,679 ) -> Result<void> {680 let caller = T::CrossAccountId::from_eth(caller);681 let approved = approved.into_sub_cross_account::<T>()?;682 let token = token_id.try_into()?;683684 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))685 .map_err(dispatch_to_evm::<T>)?;686 Ok(())687 }688689 /// @notice Transfer ownership of an NFT690 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`691 /// is the zero address. Throws if `tokenId` is not a valid NFT.692 /// @param to The new owner693 /// @param tokenId The NFT to transfer694 #[weight(<SelfWeightOf<T>>::transfer())]695 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {696 let caller = T::CrossAccountId::from_eth(caller);697 let to = T::CrossAccountId::from_eth(to);698 let token = token_id.try_into()?;699 let budget = self700 .recorder701 .weight_calls_budget(<StructureWeight<T>>::find_parent());702703 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;704 Ok(())705 }706707 /// @notice Transfer ownership of an NFT from cross account address to cross account address708 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`709 /// is the zero address. Throws if `tokenId` is not a valid NFT.710 /// @param from Cross acccount address of current owner711 /// @param to Cross acccount address of new owner712 /// @param tokenId The NFT to transfer713 #[weight(<SelfWeightOf<T>>::transfer())]714 fn transfer_from_cross(715 &mut self,716 caller: caller,717 from: EthCrossAccount,718 to: EthCrossAccount,719 token_id: uint256,720 ) -> Result<void> {721 let caller = T::CrossAccountId::from_eth(caller);722 let from = from.into_sub_cross_account::<T>()?;723 let to = to.into_sub_cross_account::<T>()?;724 let token_id = token_id.try_into()?;725 let budget = self726 .recorder727 .weight_calls_budget(<StructureWeight<T>>::find_parent());728 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)729 .map_err(dispatch_to_evm::<T>)?;730 Ok(())731 }732733 /// @notice Burns a specific ERC721 token.734 /// @dev Throws unless `msg.sender` is the current owner or an authorized735 /// operator for this NFT. Throws if `from` is not the current owner. Throws736 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.737 /// @param from The current owner of the NFT738 /// @param tokenId The NFT to transfer739 #[weight(<SelfWeightOf<T>>::burn_from())]740 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {741 let caller = T::CrossAccountId::from_eth(caller);742 let from = T::CrossAccountId::from_eth(from);743 let token = token_id.try_into()?;744 let budget = self745 .recorder746 .weight_calls_budget(<StructureWeight<T>>::find_parent());747748 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)749 .map_err(dispatch_to_evm::<T>)?;750 Ok(())751 }752753 /// @notice Burns a specific ERC721 token.754 /// @dev Throws unless `msg.sender` is the current owner or an authorized755 /// operator for this NFT. Throws if `from` is not the current owner. Throws756 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.757 /// @param from The current owner of the NFT758 /// @param tokenId The NFT to transfer759 #[weight(<SelfWeightOf<T>>::burn_from())]760 fn burn_from_cross(761 &mut self,762 caller: caller,763 from: EthCrossAccount,764 token_id: uint256,765 ) -> Result<void> {766 let caller = T::CrossAccountId::from_eth(caller);767 let from = from.into_sub_cross_account::<T>()?;768 let token = token_id.try_into()?;769 let budget = self770 .recorder771 .weight_calls_budget(<StructureWeight<T>>::find_parent());772773 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)774 .map_err(dispatch_to_evm::<T>)?;775 Ok(())776 }777778 /// @notice Returns next free NFT ID.779 fn next_token_id(&self) -> Result<uint256> {780 self.consume_store_reads(1)?;781 Ok(<TokensMinted<T>>::get(self.id)782 .checked_add(1)783 .ok_or("item id overflow")?784 .into())785 }786787 /// @notice Function to mint multiple tokens.788 /// @dev `tokenIds` should be an array of consecutive numbers and first number789 /// should be obtained with `nextTokenId` method790 /// @param to The new owner791 /// @param tokenIds IDs of the minted NFTs792 #[solidity(hide)]793 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]794 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {795 let caller = T::CrossAccountId::from_eth(caller);796 let to = T::CrossAccountId::from_eth(to);797 let mut expected_index = <TokensMinted<T>>::get(self.id)798 .checked_add(1)799 .ok_or("item id overflow")?;800 let budget = self801 .recorder802 .weight_calls_budget(<StructureWeight<T>>::find_parent());803804 let total_tokens = token_ids.len();805 for id in token_ids.into_iter() {806 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;807 if id != expected_index {808 return Err("item id should be next".into());809 }810 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;811 }812 let data = (0..total_tokens)813 .map(|_| CreateItemData::<T> {814 properties: BoundedVec::default(),815 owner: to.clone(),816 })817 .collect();818819 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)820 .map_err(dispatch_to_evm::<T>)?;821 Ok(true)822 }823824 /// @notice Function to mint multiple tokens with the given tokenUris.825 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive826 /// numbers and first number should be obtained with `nextTokenId` method827 /// @param to The new owner828 /// @param tokens array of pairs of token ID and token URI for minted tokens829 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]830 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]831 fn mint_bulk_with_token_uri(832 &mut self,833 caller: caller,834 to: address,835 tokens: Vec<(uint256, string)>,836 ) -> Result<bool> {837 let key = key::url();838 let caller = T::CrossAccountId::from_eth(caller);839 let to = T::CrossAccountId::from_eth(to);840 let mut expected_index = <TokensMinted<T>>::get(self.id)841 .checked_add(1)842 .ok_or("item id overflow")?;843 let budget = self844 .recorder845 .weight_calls_budget(<StructureWeight<T>>::find_parent());846847 let mut data = Vec::with_capacity(tokens.len());848 for (id, token_uri) in tokens {849 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;850 if id != expected_index {851 return Err("item id should be next".into());852 }853 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;854855 let mut properties = CollectionPropertiesVec::default();856 properties857 .try_push(Property {858 key: key.clone(),859 value: token_uri860 .into_bytes()861 .try_into()862 .map_err(|_| "token uri is too long")?,863 })864 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;865866 data.push(CreateItemData::<T> {867 properties,868 owner: to.clone(),869 });870 }871872 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)873 .map_err(dispatch_to_evm::<T>)?;874 Ok(true)875 }876}877878#[solidity_interface(879 name = UniqueNFT,880 is(881 ERC721,882 ERC721Enumerable,883 ERC721UniqueExtensions,884 ERC721UniqueMintable,885 ERC721Burnable,886 ERC721Metadata(if(this.flags.erc721metadata)),887 Collection(via(common_mut returns CollectionHandle<T>)),888 TokenProperties,889 )890)]891impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}892893// Not a tests, but code generators894generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);895generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);896897impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>898where899 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,900{901 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");902903 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {904 call::<T, UniqueNFTCall<T>, _, _>(handle, self)905 }906}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/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,14 +20,10 @@
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::{
- CollectionById,
- dispatch::CollectionDispatch,
- erc::{static_property::key, CollectionHelpersEvents},
- Pallet as PalletCommon,
+ CollectionById, dispatch::CollectionDispatch, erc::static_property::key, Pallet as PalletCommon,
};
use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};
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/createFTCollection.seqtest.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/createFTCollection.seqtest.ts
@@ -0,0 +1,76 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {Pallets, requirePalletsOrSkip} from '../util';
+import {expect, itEth, usingEthPlaygrounds} from './util';
+
+const DECIMALS = 18;
+
+describe('Create FT collection from EVM', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.Fungible]);
+ donor = await privateKey({filename: __filename});
+ });
+ });
+
+ itEth('Create collection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+
+ // todo:playgrounds this might fail when in async environment.
+ const collectionCountBefore = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+
+ const {collectionId} = await helper.eth.createFungibleCollection(owner, name, DECIMALS, description, prefix);
+
+ const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+ const data = (await helper.ft.getData(collectionId))!;
+
+ expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
+ expect(collectionId).to.be.eq(collectionCountAfter);
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.deep.eq({Fungible: DECIMALS.toString()});
+ });
+
+ // todo:playgrounds this test will fail when in async environment.
+ itEth('Check collection address exist', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const expectedCollectionId = +(await helper.callRpc('api.rpc.unique.collectionStats')).created + 1;
+ const expectedCollectionAddress = helper.ethAddress.fromCollectionId(expectedCollectionId);
+ const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
+
+ expect(await collectionHelpers.methods
+ .isCollectionExist(expectedCollectionAddress)
+ .call()).to.be.false;
+
+
+ await helper.eth.createFungibleCollection(owner, 'A', DECIMALS, 'A', 'A');
+
+
+ expect(await collectionHelpers.methods
+ .isCollectionExist(expectedCollectionAddress)
+ .call()).to.be.true;
+ });
+});
tests/src/eth/createFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createFTCollection.test.ts
+++ b/tests/src/eth/createFTCollection.test.ts
@@ -30,50 +30,6 @@
donor = await privateKey({filename: __filename});
});
});
-
- itEth('Create collection', async ({helper}) => {
- const owner = await helper.eth.createAccountWithBalance(donor);
-
- const name = 'CollectionEVM';
- const description = 'Some description';
- const prefix = 'token prefix';
-
- // todo:playgrounds this might fail when in async environment.
- const collectionCountBefore = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
-
- const {collectionId} = await helper.eth.createFungibleCollection(owner, name, DECIMALS, description, prefix);
-
- const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
- const data = (await helper.ft.getData(collectionId))!;
-
- expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
- expect(collectionId).to.be.eq(collectionCountAfter);
- expect(data.name).to.be.eq(name);
- expect(data.description).to.be.eq(description);
- expect(data.raw.tokenPrefix).to.be.eq(prefix);
- expect(data.raw.mode).to.be.deep.eq({Fungible: DECIMALS.toString()});
- });
-
- // todo:playgrounds this test will fail when in async environment.
- itEth('Check collection address exist', async ({helper}) => {
- const owner = await helper.eth.createAccountWithBalance(donor);
-
- const expectedCollectionId = +(await helper.callRpc('api.rpc.unique.collectionStats')).created + 1;
- const expectedCollectionAddress = helper.ethAddress.fromCollectionId(expectedCollectionId);
- const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
-
- expect(await collectionHelpers.methods
- .isCollectionExist(expectedCollectionAddress)
- .call()).to.be.false;
-
-
- await helper.eth.createFungibleCollection(owner, 'A', DECIMALS, 'A', 'A');
-
-
- expect(await collectionHelpers.methods
- .isCollectionExist(expectedCollectionAddress)
- .call()).to.be.true;
- });
itEth('Set sponsorship', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
tests/src/eth/createNFTCollection.seqtest.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/createNFTCollection.seqtest.ts
@@ -0,0 +1,89 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itEth, usingEthPlaygrounds} from './util';
+
+
+describe('Create NFT collection from EVM', () => {
+ let donor: IKeyringPair;
+
+ before(async function () {
+ await usingEthPlaygrounds(async (_helper, privateKey) => {
+ donor = await privateKey({filename: __filename});
+ });
+ });
+
+ itEth('Create collection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const name = 'CollectionEVM';
+ const description = 'Some description';
+ const prefix = 'token prefix';
+
+ // todo:playgrounds this might fail when in async environment.
+ const collectionCountBefore = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+ const {collectionId, collectionAddress, events} = await helper.eth.createNFTCollection(owner, name, description, prefix);
+
+ expect(events).to.be.deep.equal([
+ {
+ address: '0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F',
+ event: 'CollectionCreated',
+ args: {
+ owner: owner,
+ collectionId: collectionAddress,
+ },
+ },
+ ]);
+
+ const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
+
+ const collection = helper.nft.getCollectionObject(collectionId);
+ const data = (await collection.getData())!;
+
+ expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
+ expect(collectionId).to.be.eq(collectionCountAfter);
+ expect(data.name).to.be.eq(name);
+ expect(data.description).to.be.eq(description);
+ expect(data.raw.tokenPrefix).to.be.eq(prefix);
+ expect(data.raw.mode).to.be.eq('NFT');
+
+ const options = await collection.getOptions();
+
+ expect(options.tokenPropertyPermissions).to.be.empty;
+ });
+
+ // this test will occasionally fail when in async environment.
+ itEth('Check collection address exist', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const expectedCollectionId = +(await helper.callRpc('api.rpc.unique.collectionStats')).created + 1;
+ const expectedCollectionAddress = helper.ethAddress.fromCollectionId(expectedCollectionId);
+ const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
+
+ expect(await collectionHelpers.methods
+ .isCollectionExist(expectedCollectionAddress)
+ .call()).to.be.false;
+
+ await collectionHelpers.methods
+ .createNFTCollection('A', 'A', 'A')
+ .send({value: Number(2n * helper.balance.getOneTokenNominal())});
+
+ expect(await collectionHelpers.methods
+ .isCollectionExist(expectedCollectionAddress)
+ .call()).to.be.true;
+ });
+});
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -28,45 +28,6 @@
});
});
- itEth('Create collection', async ({helper}) => {
- const owner = await helper.eth.createAccountWithBalance(donor);
-
- const name = 'CollectionEVM';
- const description = 'Some description';
- const prefix = 'token prefix';
-
- // todo:playgrounds this might fail when in async environment.
- const collectionCountBefore = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
- const {collectionId, collectionAddress, events} = await helper.eth.createNFTCollection(owner, name, description, prefix);
-
- expect(events).to.be.deep.equal([
- {
- address: '0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F',
- event: 'CollectionCreated',
- args: {
- owner: owner,
- collectionId: collectionAddress,
- },
- },
- ]);
-
- const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;
-
- const collection = helper.nft.getCollectionObject(collectionId);
- const data = (await collection.getData())!;
-
- expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
- expect(collectionId).to.be.eq(collectionCountAfter);
- expect(data.name).to.be.eq(name);
- expect(data.description).to.be.eq(description);
- expect(data.raw.tokenPrefix).to.be.eq(prefix);
- expect(data.raw.mode).to.be.eq('NFT');
-
- const options = await collection.getOptions();
-
- expect(options.tokenPropertyPermissions).to.be.empty;
- });
-
itEth('Create collection with properties', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
@@ -107,27 +68,6 @@
permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
},
]);
- });
-
- // this test will occasionally fail when in async environment.
- itEth.skip('Check collection address exist', async ({helper}) => {
- const owner = await helper.eth.createAccountWithBalance(donor);
-
- const expectedCollectionId = +(await helper.callRpc('api.rpc.unique.collectionStats')).created + 1;
- const expectedCollectionAddress = helper.ethAddress.fromCollectionId(expectedCollectionId);
- const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
-
- expect(await collectionHelpers.methods
- .isCollectionExist(expectedCollectionAddress)
- .call()).to.be.false;
-
- await collectionHelpers.methods
- .createNFTCollection('A', 'A', 'A')
- .send({value: Number(2n * helper.balance.getOneTokenNominal())});
-
- expect(await collectionHelpers.methods
- .isCollectionExist(expectedCollectionAddress)
- .call()).to.be.true;
});
itEth('Set sponsorship', async ({helper}) => {
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);
});
});
@@ -148,21 +149,20 @@
}
});
- itEth('Can perform burnFromCross()', async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
- const sender = await helper.eth.createAccountWithBalance(alice, 100n);
+ 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;
@@ -171,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',
},
@@ -179,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',
},
@@ -187,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);
});
@@ -261,23 +261,22 @@
});
itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
- const sender = await helper.eth.createAccountWithBalance(alice, 100n);
+ 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});
@@ -287,7 +286,7 @@
address,
event: 'Transfer',
returnValues: {
- from: helper.address.substrateToEth(alice.address),
+ from: helper.address.substrateToEth(owner.address),
to: receiver,
value: '51',
},
@@ -296,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);
@@ -365,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,20 +455,19 @@
});
itEth('Events emitted for transferFromCross()', async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
- const sender = await helper.eth.createAccountWithBalance(alice, 100n);
+ 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});
@@ -478,7 +477,7 @@
address,
event: 'Transfer',
returnValues: {
- from: helper.address.substrateToEth(alice.address),
+ from: helper.address.substrateToEth(owner.address),
to: receiver,
value: '51',
},
@@ -487,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/migration.seqtest.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/migration.seqtest.ts
@@ -0,0 +1,108 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {expect, itEth, usingEthPlaygrounds} from './util';
+import {IKeyringPair} from '@polkadot/types/types';
+
+describe('EVM Migrations', () => {
+ let superuser: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_helper, privateKey) => {
+ superuser = await privateKey('//Alice');
+ });
+ });
+
+ // todo:playgrounds requires sudo, look into later
+ itEth('Deploy contract saved state', async ({helper}) => {
+ /*
+ contract StatefulContract {
+ uint counter;
+ mapping (uint => uint) kv;
+
+ function inc() public {
+ counter = counter + 1;
+ }
+ function counterValue() public view returns (uint) {
+ return counter;
+ }
+
+ function set(uint key, uint value) public {
+ kv[key] = value;
+ }
+
+ function get(uint key) public view returns (uint) {
+ return kv[key];
+ }
+ }
+ */
+ const ADDRESS = '0x4956bf52ef9ed8789f21bc600e915e0d961079f6';
+ const CODE = '0x608060405234801561001057600080fd5b506004361061004c5760003560e01c80631ab06ee514610051578063371303c01461006d5780637bfdec3b146100775780639507d39a14610095575b600080fd5b61006b60048036038101906100669190610160565b6100c5565b005b6100756100e1565b005b61007f6100f8565b60405161008c91906101af565b60405180910390f35b6100af60048036038101906100aa9190610133565b610101565b6040516100bc91906101af565b60405180910390f35b8060016000848152602001908152602001600020819055505050565b60016000546100f091906101ca565b600081905550565b60008054905090565b600060016000838152602001908152602001600020549050919050565b60008135905061012d8161025e565b92915050565b60006020828403121561014957610148610259565b5b60006101578482850161011e565b91505092915050565b6000806040838503121561017757610176610259565b5b60006101858582860161011e565b92505060206101968582860161011e565b9150509250929050565b6101a981610220565b82525050565b60006020820190506101c460008301846101a0565b92915050565b60006101d582610220565b91506101e083610220565b9250827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff038211156102155761021461022a565b5b828201905092915050565b6000819050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600080fd5b61026781610220565b811461027257600080fd5b5056fea26469706673582212206a02d2fb5c244105ab884961479c1aee3b4c1011e4b5530ab483eb22344a865664736f6c63430008060033';
+ const DATA = [
+ // counter = 10
+ ['0x0000000000000000000000000000000000000000000000000000000000000000', '0x000000000000000000000000000000000000000000000000000000000000000a'],
+ // kv = {1: 1, 2: 2, 3: 3, 4: 4},
+ ['0xcc69885fda6bcc1a4ace058b4a62bf5e179ea78fd58a1ccd71c22cc9b688792f', '0x0000000000000000000000000000000000000000000000000000000000000001'],
+ ['0xd9d16d34ffb15ba3a3d852f0d403e2ce1d691fb54de27ac87cd2f993f3ec330f', '0x0000000000000000000000000000000000000000000000000000000000000002'],
+ ['0x7dfe757ecd65cbd7922a9c0161e935dd7fdbcc0e999689c7d31633896b1fc60b', '0x0000000000000000000000000000000000000000000000000000000000000003'],
+ ['0xedc95719e9a3b28dd8e80877cb5880a9be7de1a13fc8b05e7999683b6b567643', '0x0000000000000000000000000000000000000000000000000000000000000004'],
+ ];
+
+ const caller = await helper.eth.createAccountWithBalance(superuser);
+
+ const txBegin = helper.constructApiCall('api.tx.evmMigration.begin', [ADDRESS]);
+ const txSetData = helper.constructApiCall('api.tx.evmMigration.setData', [ADDRESS, DATA]);
+ const txFinish = helper.constructApiCall('api.tx.evmMigration.finish', [ADDRESS, CODE]);
+ await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txBegin])).to.be.fulfilled;
+ await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txSetData])).to.be.fulfilled;
+ await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txFinish])).to.be.fulfilled;
+
+ const web3 = helper.getWeb3();
+ const contract = new web3.eth.Contract([
+ {
+ inputs: [],
+ name: 'counterValue',
+ outputs: [{
+ internalType: 'uint256',
+ name: '',
+ type: 'uint256',
+ }],
+ stateMutability: 'view',
+ type: 'function',
+ },
+ {
+ inputs: [{
+ internalType: 'uint256',
+ name: 'key',
+ type: 'uint256',
+ }],
+ name: 'get',
+ outputs: [{
+ internalType: 'uint256',
+ name: '',
+ type: 'uint256',
+ }],
+ stateMutability: 'view',
+ type: 'function',
+ },
+ ], ADDRESS, {from: caller, gas: helper.eth.DEFAULT_GAS});
+
+ expect(await contract.methods.counterValue().call()).to.be.equal('10');
+ for (let i = 1; i <= 4; i++) {
+ expect(await contract.methods.get(i).call()).to.be.equal(i.toString());
+ }
+ });
+});
tests/src/eth/migration.test.tsdiffbeforeafterboth--- a/tests/src/eth/migration.test.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {expect, itEth, usingEthPlaygrounds} from './util';
-import {IKeyringPair} from '@polkadot/types/types';
-
-describe('EVM Migrations', () => {
- let superuser: IKeyringPair;
-
- before(async function() {
- await usingEthPlaygrounds(async (_helper, privateKey) => {
- superuser = await privateKey('//Alice');
- });
- });
-
- // todo:playgrounds requires sudo, look into later
- itEth('Deploy contract saved state', async ({helper}) => {
- /*
- contract StatefulContract {
- uint counter;
- mapping (uint => uint) kv;
-
- function inc() public {
- counter = counter + 1;
- }
- function counterValue() public view returns (uint) {
- return counter;
- }
-
- function set(uint key, uint value) public {
- kv[key] = value;
- }
-
- function get(uint key) public view returns (uint) {
- return kv[key];
- }
- }
- */
- const ADDRESS = '0x4956bf52ef9ed8789f21bc600e915e0d961079f6';
- const CODE = '0x608060405234801561001057600080fd5b506004361061004c5760003560e01c80631ab06ee514610051578063371303c01461006d5780637bfdec3b146100775780639507d39a14610095575b600080fd5b61006b60048036038101906100669190610160565b6100c5565b005b6100756100e1565b005b61007f6100f8565b60405161008c91906101af565b60405180910390f35b6100af60048036038101906100aa9190610133565b610101565b6040516100bc91906101af565b60405180910390f35b8060016000848152602001908152602001600020819055505050565b60016000546100f091906101ca565b600081905550565b60008054905090565b600060016000838152602001908152602001600020549050919050565b60008135905061012d8161025e565b92915050565b60006020828403121561014957610148610259565b5b60006101578482850161011e565b91505092915050565b6000806040838503121561017757610176610259565b5b60006101858582860161011e565b92505060206101968582860161011e565b9150509250929050565b6101a981610220565b82525050565b60006020820190506101c460008301846101a0565b92915050565b60006101d582610220565b91506101e083610220565b9250827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff038211156102155761021461022a565b5b828201905092915050565b6000819050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600080fd5b61026781610220565b811461027257600080fd5b5056fea26469706673582212206a02d2fb5c244105ab884961479c1aee3b4c1011e4b5530ab483eb22344a865664736f6c63430008060033';
- const DATA = [
- // counter = 10
- ['0x0000000000000000000000000000000000000000000000000000000000000000', '0x000000000000000000000000000000000000000000000000000000000000000a'],
- // kv = {1: 1, 2: 2, 3: 3, 4: 4},
- ['0xcc69885fda6bcc1a4ace058b4a62bf5e179ea78fd58a1ccd71c22cc9b688792f', '0x0000000000000000000000000000000000000000000000000000000000000001'],
- ['0xd9d16d34ffb15ba3a3d852f0d403e2ce1d691fb54de27ac87cd2f993f3ec330f', '0x0000000000000000000000000000000000000000000000000000000000000002'],
- ['0x7dfe757ecd65cbd7922a9c0161e935dd7fdbcc0e999689c7d31633896b1fc60b', '0x0000000000000000000000000000000000000000000000000000000000000003'],
- ['0xedc95719e9a3b28dd8e80877cb5880a9be7de1a13fc8b05e7999683b6b567643', '0x0000000000000000000000000000000000000000000000000000000000000004'],
- ];
-
- const caller = await helper.eth.createAccountWithBalance(superuser);
-
- const txBegin = helper.constructApiCall('api.tx.evmMigration.begin', [ADDRESS]);
- const txSetData = helper.constructApiCall('api.tx.evmMigration.setData', [ADDRESS, DATA]);
- const txFinish = helper.constructApiCall('api.tx.evmMigration.finish', [ADDRESS, CODE]);
- await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txBegin])).to.be.fulfilled;
- await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txSetData])).to.be.fulfilled;
- await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [txFinish])).to.be.fulfilled;
-
- const web3 = helper.getWeb3();
- const contract = new web3.eth.Contract([
- {
- inputs: [],
- name: 'counterValue',
- outputs: [{
- internalType: 'uint256',
- name: '',
- type: 'uint256',
- }],
- stateMutability: 'view',
- type: 'function',
- },
- {
- inputs: [{
- internalType: 'uint256',
- name: 'key',
- type: 'uint256',
- }],
- name: 'get',
- outputs: [{
- internalType: 'uint256',
- name: '',
- type: 'uint256',
- }],
- stateMutability: 'view',
- type: 'function',
- },
- ], ADDRESS, {from: caller, gas: helper.eth.DEFAULT_GAS});
-
- expect(await contract.methods.counterValue().call()).to.be.equal('10');
- for (let i = 1; i <= 4; i++) {
- expect(await contract.methods.get(i).call()).to.be.equal(i.toString());
- }
- });
-});
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -138,12 +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] = await helper.arrange.createAccounts([10n], donor);
+ [minter, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
});
});
@@ -176,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);
@@ -208,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);
@@ -229,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);
@@ -246,14 +248,13 @@
}
});
- itEth('Can perform burnFromCross()', async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
- 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 = await privateKey('//Bob');
- const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+ 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');
@@ -276,14 +277,13 @@
}
});
- itEth('Can perform approveCross()', async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
- 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(alice, 100n);
- const receiver = await privateKey('//Charlie');
+ 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);
@@ -373,11 +407,13 @@
describe('NFT: Fees', () => {
let donor: IKeyringPair;
let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
donor = await privateKey({filename: __filename});
- [alice] = await helper.arrange.createAccounts([10n], donor);
+ [alice, bob, charlie] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
});
});
@@ -410,14 +446,14 @@
});
itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
- const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+ const collectionMinter = alice;
+ const owner = bob;
+ const receiver = charlie;
+ const collection = await helper.nft.mintCollection(collectionMinter, {name: 'A', description: 'B', tokenPrefix: 'C'});
- const owner = await privateKey('//Bob');
- const spender = await helper.eth.createAccountWithBalance(alice, 100n);
- const receiver = await privateKey('//Charlie');
+ const spender = await helper.eth.createAccountWithBalance(donor, 100n);
- const token = await collection.mintToken(alice, {Substrate: owner.address});
+ const token = await collection.mintToken(collectionMinter, {Substrate: owner.address});
const address = helper.ethAddress.fromCollectionId(collection.collectionId);
const contract = helper.ethNativeContract.collection(address, 'nft');
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,12 +104,16 @@
describe('Refungible: Plain calls', () => {
let donor: IKeyringPair;
+ let minter: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
donor = await privateKey({filename: __filename});
+ [minter, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
});
});
@@ -227,14 +231,13 @@
}
});
- itEth('Can perform burnFrom()', async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
- 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(alice, 100n);
- const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+ 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');
@@ -260,15 +263,14 @@
expect(await collection.getTokenBalance(token.tokenId, {Ethereum: owner})).to.be.eq(0n);
});
-
- itEth('Can perform burnFromCross()', async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
- const collection = await helper.rft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
- const owner = await privateKey('//Bob');
- const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+ 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');
@@ -294,15 +296,14 @@
expect(await collection.getTokenBalance(token.tokenId, {Substrate: owner.address})).to.be.eq(0n);
});
- itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
- 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 = await privateKey('//Bob');
- const spender = await helper.eth.createAccountWithBalance(alice, 100n);
- const receiver = await privateKey('//Charlie');
+ 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/scheduling.test.tsdiffbeforeafterboth--- a/tests/src/eth/scheduling.test.ts
+++ b/tests/src/eth/scheduling.test.ts
@@ -27,7 +27,8 @@
});
itEth.ifWithPallets('Successfully schedules and periodically executes an EVM contract', [Pallets.Scheduler], async ({helper, privateKey}) => {
- const alice = await privateKey('//Alice');
+ const donor = await privateKey({filename: __filename});
+ const [alice] = await helper.arrange.createAccounts([1000n], donor);
const scheduledId = await helper.arrange.makeScheduledId();
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/inflation.seqtest.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/inflation.seqtest.ts
@@ -0,0 +1,58 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itSub, usingPlaygrounds} from './util';
+
+// todo:playgrounds requires sudo, look into on the later stage
+describe('integration test: Inflation', () => {
+ let superuser: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (_, privateKey) => {
+ superuser = await privateKey('//Alice');
+ });
+ });
+
+ itSub('First year inflation is 10%', async ({helper}) => {
+ // Make sure non-sudo can't start inflation
+ const [bob] = await helper.arrange.createAccounts([10n], superuser);
+
+ await expect(helper.executeExtrinsic(bob, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
+
+ // Make sure superuser can't start inflation without explicit sudo
+ await expect(helper.executeExtrinsic(superuser, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
+
+ // Start inflation on relay block 1 (Alice is sudo)
+ const tx = helper.constructApiCall('api.tx.inflation.startInflation', [1]);
+ await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [tx])).to.not.be.rejected;
+
+ const blockInterval = (helper.getApi().consts.inflation.inflationBlockInterval as any).toBigInt();
+ const totalIssuanceStart = ((await helper.callRpc('api.query.inflation.startingYearTotalIssuance', [])) as any).toBigInt();
+ const blockInflation = (await helper.callRpc('api.query.inflation.blockInflation', []) as any).toBigInt();
+
+ const YEAR = 5259600n; // 6-second block. Blocks in one year
+ // const YEAR = 2629800n; // 12-second block. Blocks in one year
+
+ const totalExpectedInflation = totalIssuanceStart / 10n;
+ const totalActualInflation = blockInflation * YEAR / blockInterval;
+
+ const tolerance = 0.00001; // Relative difference per year between theoretical and actual inflation
+ const expectedInflation = totalExpectedInflation / totalActualInflation - 1n;
+
+ expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);
+ });
+});
tests/src/inflation.test.tsdiffbeforeafterboth--- a/tests/src/inflation.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {IKeyringPair} from '@polkadot/types/types';
-import {expect, itSub, usingPlaygrounds} from './util';
-
-// todo:playgrounds requires sudo, look into on the later stage
-describe('integration test: Inflation', () => {
- let superuser: IKeyringPair;
-
- before(async () => {
- await usingPlaygrounds(async (_, privateKey) => {
- superuser = await privateKey('//Alice');
- });
- });
-
- itSub('First year inflation is 10%', async ({helper}) => {
- // Make sure non-sudo can't start inflation
- const [bob] = await helper.arrange.createAccounts([10n], superuser);
-
- await expect(helper.executeExtrinsic(bob, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
-
- // Make sure superuser can't start inflation without explicit sudo
- await expect(helper.executeExtrinsic(superuser, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
-
- // Start inflation on relay block 1 (Alice is sudo)
- const tx = helper.constructApiCall('api.tx.inflation.startInflation', [1]);
- await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [tx])).to.not.be.rejected;
-
- const blockInterval = (helper.getApi().consts.inflation.inflationBlockInterval as any).toBigInt();
- const totalIssuanceStart = ((await helper.callRpc('api.query.inflation.startingYearTotalIssuance', [])) as any).toBigInt();
- const blockInflation = (await helper.callRpc('api.query.inflation.blockInflation', []) as any).toBigInt();
-
- const YEAR = 5259600n; // 6-second block. Blocks in one year
- // const YEAR = 2629800n; // 12-second block. Blocks in one year
-
- const totalExpectedInflation = totalIssuanceStart / 10n;
- const totalActualInflation = blockInflation * YEAR / blockInterval;
-
- const tolerance = 0.00001; // Relative difference per year between theoretical and actual inflation
- const expectedInflation = totalExpectedInflation / totalActualInflation - 1n;
-
- expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);
- });
-});
tests/src/scheduler.seqtest.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/scheduler.seqtest.ts
@@ -0,0 +1,647 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {expect, itSub, Pallets, usingPlaygrounds} from './util';
+import {IKeyringPair} from '@polkadot/types/types';
+import {DevUniqueHelper} from './util/playgrounds/unique.dev';
+
+describe('Scheduling token and balance transfers', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKeyWrapper) => {
+ alice = await privateKeyWrapper('//Alice');
+ bob = await privateKeyWrapper('//Bob');
+ charlie = await privateKeyWrapper('//Charlie');
+
+ await helper.testUtils.enable();
+ });
+ });
+
+ itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
+ const token = await collection.mintToken(alice);
+ const schedulerId = await helper.arrange.makeScheduledId();
+ const blocksBeforeExecution = 4;
+
+ await token.scheduleAfter(schedulerId, blocksBeforeExecution)
+ .transfer(alice, {Substrate: bob.address});
+
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
+
+ await helper.wait.newBlocks(blocksBeforeExecution + 1);
+
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
+ });
+
+ itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 1;
+
+ const amount = 1n * helper.balance.getOneTokenNominal();
+ const periodic = {
+ period: 2,
+ repetitions: 2,
+ };
+
+ const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
+
+ await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
+ .balance.transferToSubstrate(alice, bob.address, amount);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);
+ expect(bobsBalanceAfterFirst)
+ .to.be.equal(
+ bobsBalanceBefore + 1n * amount,
+ '#1 Balance of the recipient should be increased by 1 * amount',
+ );
+
+ await helper.wait.newBlocks(periodic.period);
+
+ const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);
+ expect(bobsBalanceAfterSecond)
+ .to.be.equal(
+ bobsBalanceBefore + 2n * amount,
+ '#2 Balance of the recipient should be increased by 2 * amount',
+ );
+ });
+
+ itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
+ const token = await collection.mintToken(alice);
+
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
+
+ await token.scheduleAfter(scheduledId, waitForBlocks)
+ .transfer(alice, {Substrate: bob.address});
+
+ await helper.scheduler.cancelScheduled(alice, scheduledId);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
+ });
+
+ itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {
+ const waitForBlocks = 1;
+ const periodic = {
+ period: 3,
+ repetitions: 2,
+ };
+
+ const scheduledId = await helper.arrange.makeScheduledId();
+
+ const amount = 1n * helper.balance.getOneTokenNominal();
+
+ const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
+
+ await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
+ .balance.transferToSubstrate(alice, bob.address, amount);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);
+
+ expect(bobsBalanceAfterFirst)
+ .to.be.equal(
+ bobsBalanceBefore + 1n * amount,
+ '#1 Balance of the recipient should be increased by 1 * amount',
+ );
+
+ await helper.scheduler.cancelScheduled(alice, scheduledId);
+ await helper.wait.newBlocks(periodic.period);
+
+ const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);
+ expect(bobsBalanceAfterSecond)
+ .to.be.equal(
+ bobsBalanceAfterFirst,
+ '#2 Balance of the recipient should not be changed',
+ );
+ });
+
+ itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+
+ const initTestVal = 42;
+ const changedTestVal = 111;
+
+ await helper.testUtils.setTestValue(alice, initTestVal);
+
+ await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks)
+ .testUtils.setTestValueAndRollback(alice, changedTestVal);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ const testVal = await helper.testUtils.testValue();
+ expect(testVal, 'The test value should NOT be commited')
+ .to.be.equal(initTestVal);
+ });
+
+ itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+ const periodic = {
+ period: 2,
+ repetitions: 2,
+ };
+
+ const dummyTx = helper.constructApiCall('api.tx.testUtils.justTakeFee', []);
+ const scheduledLen = dummyTx.callIndex.length;
+
+ const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))
+ .partialFee.toBigInt();
+
+ await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+ .testUtils.justTakeFee(alice);
+
+ await helper.wait.newBlocks(1);
+
+ const aliceInitBalance = await helper.balance.getSubstrate(alice.address);
+ let diff;
+
+ await helper.wait.newBlocks(waitForBlocks);
+
+ const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);
+ expect(
+ aliceBalanceAfterFirst < aliceInitBalance,
+ '[after execution #1] Scheduled task should take a fee',
+ ).to.be.true;
+
+ diff = aliceInitBalance - aliceBalanceAfterFirst;
+ expect(diff).to.be.equal(
+ expectedScheduledFee,
+ 'Scheduled task should take the right amount of fees',
+ );
+
+ await helper.wait.newBlocks(periodic.period);
+
+ const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);
+ expect(
+ aliceBalanceAfterSecond < aliceBalanceAfterFirst,
+ '[after execution #2] Scheduled task should take a fee',
+ ).to.be.true;
+
+ diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;
+ expect(diff).to.be.equal(
+ expectedScheduledFee,
+ 'Scheduled task should take the right amount of fees',
+ );
+ });
+
+ // Check if we can cancel a scheduled periodic operation
+ // in the same block in which it is running
+ itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
+ const currentBlockNumber = await helper.chain.getLatestBlockNumber();
+ const blocksBeforeExecution = 10;
+ const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;
+
+ const [
+ scheduledId,
+ scheduledCancelId,
+ ] = await helper.arrange.makeScheduledIds(2);
+
+ const periodic = {
+ period: 5,
+ repetitions: 5,
+ };
+
+ const initTestVal = 0;
+ const incTestVal = initTestVal + 1;
+ const finalTestVal = initTestVal + 2;
+
+ await helper.testUtils.setTestValue(alice, initTestVal);
+
+ await helper.scheduler.scheduleAt<DevUniqueHelper>(scheduledId, firstExecutionBlockNumber, {periodic})
+ .testUtils.incTestValue(alice);
+
+ // Cancel the inc tx after 2 executions
+ // *in the same block* in which the second execution is scheduled
+ await helper.scheduler.scheduleAt(
+ scheduledCancelId,
+ firstExecutionBlockNumber + periodic.period,
+ ).scheduler.cancelScheduled(alice, scheduledId);
+
+ await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
+
+ // execution #0
+ expect(await helper.testUtils.testValue())
+ .to.be.equal(incTestVal);
+
+ await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber + periodic.period);
+
+ // execution #1
+ expect(await helper.testUtils.testValue())
+ .to.be.equal(finalTestVal);
+
+ for (let i = 1; i < periodic.repetitions; i++) {
+ await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber + periodic.period * (i + 1));
+ expect(await helper.testUtils.testValue())
+ .to.be.equal(finalTestVal);
+ }
+ });
+
+ itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+ const periodic = {
+ period: 2,
+ repetitions: 5,
+ };
+
+ const initTestVal = 0;
+ const maxTestVal = 2;
+
+ await helper.testUtils.setTestValue(alice, initTestVal);
+
+ await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+ .testUtils.selfCancelingInc(alice, scheduledId, maxTestVal);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ // execution #0
+ expect(await helper.testUtils.testValue())
+ .to.be.equal(initTestVal + 1);
+
+ await helper.wait.newBlocks(periodic.period);
+
+ // execution #1
+ expect(await helper.testUtils.testValue())
+ .to.be.equal(initTestVal + 2);
+
+ await helper.wait.newBlocks(periodic.period);
+
+ // <canceled>
+ expect(await helper.testUtils.testValue())
+ .to.be.equal(initTestVal + 2);
+ });
+
+ itSub.ifWithPallets('Root can cancel any scheduled operation', [Pallets.Scheduler], async ({helper}) => {
+ const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
+ const token = await collection.mintToken(bob);
+
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+
+ await token.scheduleAfter(scheduledId, waitForBlocks)
+ .transfer(bob, {Substrate: alice.address});
+
+ await helper.getSudo().scheduler.cancelScheduled(alice, scheduledId);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
+ });
+
+ itSub.ifWithPallets('Root can set prioritized scheduled operation', [Pallets.Scheduler], async ({helper}) => {
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+
+ const amount = 42n * helper.balance.getOneTokenNominal();
+
+ const balanceBefore = await helper.balance.getSubstrate(charlie.address);
+
+ await helper.getSudo()
+ .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})
+ .balance.forceTransferToSubstrate(alice, bob.address, charlie.address, amount);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ const balanceAfter = await helper.balance.getSubstrate(charlie.address);
+
+ expect(balanceAfter > balanceBefore).to.be.true;
+
+ const diff = balanceAfter - balanceBefore;
+ expect(diff).to.be.equal(amount);
+ });
+
+ itSub.ifWithPallets("Root can change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {
+ const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
+ const token = await collection.mintToken(bob);
+
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 6;
+
+ await token.scheduleAfter(scheduledId, waitForBlocks)
+ .transfer(bob, {Substrate: alice.address});
+
+ const priority = 112;
+ await helper.getSudo().scheduler.changePriority(alice, scheduledId, priority);
+
+ const priorityChanged = await helper.wait.event(
+ waitForBlocks,
+ 'scheduler',
+ 'PriorityChanged',
+ );
+
+ expect(priorityChanged !== null).to.be.true;
+ expect(priorityChanged!.event.data[2].toString()).to.be.equal(priority.toString());
+ });
+
+ itSub.ifWithPallets('Prioritized operations executes in valid order', [Pallets.Scheduler], async ({helper}) => {
+ const [
+ scheduledFirstId,
+ scheduledSecondId,
+ ] = await helper.arrange.makeScheduledIds(2);
+
+ const currentBlockNumber = await helper.chain.getLatestBlockNumber();
+ const blocksBeforeExecution = 6;
+ const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;
+
+ const prioHigh = 0;
+ const prioLow = 255;
+
+ const periodic = {
+ period: 6,
+ repetitions: 2,
+ };
+
+ const amount = 1n * helper.balance.getOneTokenNominal();
+
+ // Scheduler a task with a lower priority first, then with a higher priority
+ await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})
+ .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);
+
+ await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})
+ .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);
+
+ const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');
+
+ await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
+
+ // Flip priorities
+ await helper.getSudo().scheduler.changePriority(alice, scheduledFirstId, prioHigh);
+ await helper.getSudo().scheduler.changePriority(alice, scheduledSecondId, prioLow);
+
+ await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber + periodic.period);
+
+ const dispatchEvents = capture.extractCapturedEvents();
+ expect(dispatchEvents.length).to.be.equal(4);
+
+ const dispatchedIds = dispatchEvents.map(r => r.event.data[1].toString());
+
+ const firstExecuctionIds = [dispatchedIds[0], dispatchedIds[1]];
+ const secondExecuctionIds = [dispatchedIds[2], dispatchedIds[3]];
+
+ expect(firstExecuctionIds[0]).to.be.equal(scheduledSecondId);
+ expect(firstExecuctionIds[1]).to.be.equal(scheduledFirstId);
+
+ expect(secondExecuctionIds[0]).to.be.equal(scheduledFirstId);
+ expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);
+ });
+});
+
+describe('Negative Test: Scheduling', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKeyWrapper) => {
+ alice = await privateKeyWrapper('//Alice');
+ bob = await privateKeyWrapper('//Bob');
+
+ await helper.testUtils.enable();
+ });
+ });
+
+ itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler], async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
+ const token = await collection.mintToken(alice);
+
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+
+ await token.scheduleAfter(scheduledId, waitForBlocks)
+ .transfer(alice, {Substrate: bob.address});
+
+ const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);
+ await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * helper.balance.getOneTokenNominal()))
+ .to.be.rejectedWith(/scheduler\.FailedToSchedule/);
+
+ const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);
+
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
+ expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);
+ });
+
+ itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler], async ({helper}) => {
+ const scheduledId = await helper.arrange.makeScheduledId();
+ await expect(helper.scheduler.cancelScheduled(alice, scheduledId))
+ .to.be.rejectedWith(/scheduler\.NotFound/);
+ });
+
+ itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler], async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
+ const token = await collection.mintToken(alice);
+
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+
+ await token.scheduleAfter(scheduledId, waitForBlocks)
+ .transfer(alice, {Substrate: bob.address});
+
+ await expect(helper.scheduler.cancelScheduled(bob, scheduledId))
+ .to.be.rejectedWith(/BadOrigin/);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
+ });
+
+ itSub.ifWithPallets("Regular user can't set prioritized scheduled operation", [Pallets.Scheduler], async ({helper}) => {
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+
+ const amount = 42n * helper.balance.getOneTokenNominal();
+
+ const balanceBefore = await helper.balance.getSubstrate(bob.address);
+
+ const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});
+
+ await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))
+ .to.be.rejectedWith(/BadOrigin/);
+
+ await helper.wait.newBlocks(waitForBlocks + 1);
+
+ const balanceAfter = await helper.balance.getSubstrate(bob.address);
+
+ expect(balanceAfter).to.be.equal(balanceBefore);
+ });
+
+ itSub.ifWithPallets("Regular user can't change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {
+ const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
+ const token = await collection.mintToken(bob);
+
+ const scheduledId = await helper.arrange.makeScheduledId();
+ const waitForBlocks = 4;
+
+ await token.scheduleAfter(scheduledId, waitForBlocks)
+ .transfer(bob, {Substrate: alice.address});
+
+ const priority = 112;
+ await expect(helper.scheduler.changePriority(alice, scheduledId, priority))
+ .to.be.rejectedWith(/BadOrigin/);
+
+ const priorityChanged = await helper.wait.event(
+ waitForBlocks,
+ 'scheduler',
+ 'PriorityChanged',
+ );
+
+ expect(priorityChanged === null).to.be.true;
+ });
+});
+
+// Implementation of the functionality tested here was postponed/shelved
+describe.skip('Sponsoring scheduling', () => {
+ // let alice: IKeyringPair;
+ // let bob: IKeyringPair;
+
+ // before(async() => {
+ // await usingApi(async (_, privateKeyWrapper) => {
+ // alice = privateKeyWrapper('//Alice');
+ // bob = privateKeyWrapper('//Bob');
+ // });
+ // });
+
+ it('Can sponsor scheduling a transaction', async () => {
+ // const collectionId = await createCollectionExpectSuccess();
+ // await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ // await usingApi(async api => {
+ // const scheduledId = await makeScheduledId();
+ // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ // const bobBalanceBefore = await getFreeBalance(bob);
+ // const waitForBlocks = 4;
+ // // no need to wait to check, fees must be deducted on scheduling, immediately
+ // await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);
+ // const bobBalanceAfter = await getFreeBalance(bob);
+ // // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+ // expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
+ // // wait for sequentiality matters
+ // await waitNewBlocks(waitForBlocks - 1);
+ // });
+ });
+
+ it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
+ // await usingApi(async (api, privateKeyWrapper) => {
+ // // Find an empty, unused account
+ // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+
+ // const collectionId = await createCollectionExpectSuccess();
+
+ // // Add zeroBalance address to allow list
+ // await enablePublicMintingExpectSuccess(alice, collectionId);
+ // await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // // Grace zeroBalance with money, enough to cover future transactions
+ // const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ // await submitTransactionAsync(alice, balanceTx);
+
+ // // Mint a fresh NFT
+ // const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+ // const scheduledId = await makeScheduledId();
+
+ // // Schedule transfer of the NFT a few blocks ahead
+ // const waitForBlocks = 5;
+ // await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);
+
+ // // Get rid of the account's funds before the scheduled transaction takes place
+ // const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
+ // const events = await submitTransactionAsync(zeroBalance, balanceTx2);
+ // expect(getGenericResult(events).success).to.be.true;
+ // /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
+ // const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
+ // const events = await submitTransactionAsync(alice, sudoTx);
+ // expect(getGenericResult(events).success).to.be.true;*/
+
+ // // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
+ // await waitNewBlocks(waitForBlocks - 3);
+
+ // expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+ // });
+ });
+
+ it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
+ // const collectionId = await createCollectionExpectSuccess();
+
+ // await usingApi(async (api, privateKeyWrapper) => {
+ // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+ // const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ // await submitTransactionAsync(alice, balanceTx);
+
+ // await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
+ // await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
+
+ // const scheduledId = await makeScheduledId();
+ // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ // const waitForBlocks = 5;
+ // await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);
+
+ // const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
+ // const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+ // const events = await submitTransactionAsync(alice, sudoTx);
+ // expect(getGenericResult(events).success).to.be.true;
+
+ // // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+ // await waitNewBlocks(waitForBlocks - 3);
+
+ // expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
+ // });
+ });
+
+ it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {
+ // const collectionId = await createCollectionExpectSuccess();
+ // await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ // await usingApi(async (api, privateKeyWrapper) => {
+ // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+
+ // await enablePublicMintingExpectSuccess(alice, collectionId);
+ // await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // const bobBalanceBefore = await getFreeBalance(bob);
+
+ // const createData = {nft: {const_data: [], variable_data: []}};
+ // const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
+ // const scheduledId = await makeScheduledId();
+
+ // /*const badTransaction = async function () {
+ // await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+ // };
+ // await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
+
+ // await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);
+
+ // expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
+ // });
+ });
+});
tests/src/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/scheduler.test.ts
+++ /dev/null
@@ -1,647 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {expect, itSub, Pallets, usingPlaygrounds} from './util';
-import {IKeyringPair} from '@polkadot/types/types';
-import {DevUniqueHelper} from './util/playgrounds/unique.dev';
-
-describe('Scheduling token and balance transfers', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
-
- before(async () => {
- await usingPlaygrounds(async (helper, privateKeyWrapper) => {
- alice = await privateKeyWrapper('//Alice');
- bob = await privateKeyWrapper('//Bob');
- charlie = await privateKeyWrapper('//Charlie');
-
- await helper.testUtils.enable();
- });
- });
-
- itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {
- const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
- const token = await collection.mintToken(alice);
- const schedulerId = await helper.arrange.makeScheduledId();
- const blocksBeforeExecution = 4;
-
- await token.scheduleAfter(schedulerId, blocksBeforeExecution)
- .transfer(alice, {Substrate: bob.address});
-
- expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
-
- await helper.wait.newBlocks(blocksBeforeExecution + 1);
-
- expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
- });
-
- itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 1;
-
- const amount = 1n * helper.balance.getOneTokenNominal();
- const periodic = {
- period: 2,
- repetitions: 2,
- };
-
- const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
-
- await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
- .balance.transferToSubstrate(alice, bob.address, amount);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);
- expect(bobsBalanceAfterFirst)
- .to.be.equal(
- bobsBalanceBefore + 1n * amount,
- '#1 Balance of the recipient should be increased by 1 * amount',
- );
-
- await helper.wait.newBlocks(periodic.period);
-
- const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);
- expect(bobsBalanceAfterSecond)
- .to.be.equal(
- bobsBalanceBefore + 2n * amount,
- '#2 Balance of the recipient should be increased by 2 * amount',
- );
- });
-
- itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {
- const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
- const token = await collection.mintToken(alice);
-
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
-
- expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
-
- await token.scheduleAfter(scheduledId, waitForBlocks)
- .transfer(alice, {Substrate: bob.address});
-
- await helper.scheduler.cancelScheduled(alice, scheduledId);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
- });
-
- itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {
- const waitForBlocks = 1;
- const periodic = {
- period: 3,
- repetitions: 2,
- };
-
- const scheduledId = await helper.arrange.makeScheduledId();
-
- const amount = 1n * helper.balance.getOneTokenNominal();
-
- const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
-
- await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
- .balance.transferToSubstrate(alice, bob.address, amount);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);
-
- expect(bobsBalanceAfterFirst)
- .to.be.equal(
- bobsBalanceBefore + 1n * amount,
- '#1 Balance of the recipient should be increased by 1 * amount',
- );
-
- await helper.scheduler.cancelScheduled(alice, scheduledId);
- await helper.wait.newBlocks(periodic.period);
-
- const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);
- expect(bobsBalanceAfterSecond)
- .to.be.equal(
- bobsBalanceAfterFirst,
- '#2 Balance of the recipient should not be changed',
- );
- });
-
- itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
-
- const initTestVal = 42;
- const changedTestVal = 111;
-
- await helper.testUtils.setTestValue(alice, initTestVal);
-
- await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks)
- .testUtils.setTestValueAndRollback(alice, changedTestVal);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- const testVal = await helper.testUtils.testValue();
- expect(testVal, 'The test value should NOT be commited')
- .to.be.equal(initTestVal);
- });
-
- itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
- const periodic = {
- period: 2,
- repetitions: 2,
- };
-
- const dummyTx = helper.constructApiCall('api.tx.testUtils.justTakeFee', []);
- const scheduledLen = dummyTx.callIndex.length;
-
- const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))
- .partialFee.toBigInt();
-
- await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
- .testUtils.justTakeFee(alice);
-
- await helper.wait.newBlocks(1);
-
- const aliceInitBalance = await helper.balance.getSubstrate(alice.address);
- let diff;
-
- await helper.wait.newBlocks(waitForBlocks);
-
- const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);
- expect(
- aliceBalanceAfterFirst < aliceInitBalance,
- '[after execution #1] Scheduled task should take a fee',
- ).to.be.true;
-
- diff = aliceInitBalance - aliceBalanceAfterFirst;
- expect(diff).to.be.equal(
- expectedScheduledFee,
- 'Scheduled task should take the right amount of fees',
- );
-
- await helper.wait.newBlocks(periodic.period);
-
- const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);
- expect(
- aliceBalanceAfterSecond < aliceBalanceAfterFirst,
- '[after execution #2] Scheduled task should take a fee',
- ).to.be.true;
-
- diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;
- expect(diff).to.be.equal(
- expectedScheduledFee,
- 'Scheduled task should take the right amount of fees',
- );
- });
-
- // Check if we can cancel a scheduled periodic operation
- // in the same block in which it is running
- itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
- const currentBlockNumber = await helper.chain.getLatestBlockNumber();
- const blocksBeforeExecution = 10;
- const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;
-
- const [
- scheduledId,
- scheduledCancelId,
- ] = await helper.arrange.makeScheduledIds(2);
-
- const periodic = {
- period: 5,
- repetitions: 5,
- };
-
- const initTestVal = 0;
- const incTestVal = initTestVal + 1;
- const finalTestVal = initTestVal + 2;
-
- await helper.testUtils.setTestValue(alice, initTestVal);
-
- await helper.scheduler.scheduleAt<DevUniqueHelper>(scheduledId, firstExecutionBlockNumber, {periodic})
- .testUtils.incTestValue(alice);
-
- // Cancel the inc tx after 2 executions
- // *in the same block* in which the second execution is scheduled
- await helper.scheduler.scheduleAt(
- scheduledCancelId,
- firstExecutionBlockNumber + periodic.period,
- ).scheduler.cancelScheduled(alice, scheduledId);
-
- await helper.wait.newBlocks(blocksBeforeExecution);
-
- // execution #0
- expect(await helper.testUtils.testValue())
- .to.be.equal(incTestVal);
-
- await helper.wait.newBlocks(periodic.period);
-
- // execution #1
- expect(await helper.testUtils.testValue())
- .to.be.equal(finalTestVal);
-
- for (let i = 1; i < periodic.repetitions; i++) {
- await helper.wait.newBlocks(periodic.period);
- expect(await helper.testUtils.testValue())
- .to.be.equal(finalTestVal);
- }
- });
-
- itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
- const periodic = {
- period: 2,
- repetitions: 5,
- };
-
- const initTestVal = 0;
- const maxTestVal = 2;
-
- await helper.testUtils.setTestValue(alice, initTestVal);
-
- await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
- .testUtils.selfCancelingInc(alice, scheduledId, maxTestVal);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- // execution #0
- expect(await helper.testUtils.testValue())
- .to.be.equal(initTestVal + 1);
-
- await helper.wait.newBlocks(periodic.period);
-
- // execution #1
- expect(await helper.testUtils.testValue())
- .to.be.equal(initTestVal + 2);
-
- await helper.wait.newBlocks(periodic.period);
-
- // <canceled>
- expect(await helper.testUtils.testValue())
- .to.be.equal(initTestVal + 2);
- });
-
- itSub.ifWithPallets('Root can cancel any scheduled operation', [Pallets.Scheduler], async ({helper}) => {
- const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
- const token = await collection.mintToken(bob);
-
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
-
- await token.scheduleAfter(scheduledId, waitForBlocks)
- .transfer(bob, {Substrate: alice.address});
-
- await helper.getSudo().scheduler.cancelScheduled(alice, scheduledId);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
- });
-
- itSub.ifWithPallets('Root can set prioritized scheduled operation', [Pallets.Scheduler], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
-
- const amount = 42n * helper.balance.getOneTokenNominal();
-
- const balanceBefore = await helper.balance.getSubstrate(charlie.address);
-
- await helper.getSudo()
- .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})
- .balance.forceTransferToSubstrate(alice, bob.address, charlie.address, amount);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- const balanceAfter = await helper.balance.getSubstrate(charlie.address);
-
- expect(balanceAfter > balanceBefore).to.be.true;
-
- const diff = balanceAfter - balanceBefore;
- expect(diff).to.be.equal(amount);
- });
-
- itSub.ifWithPallets("Root can change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {
- const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
- const token = await collection.mintToken(bob);
-
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 6;
-
- await token.scheduleAfter(scheduledId, waitForBlocks)
- .transfer(bob, {Substrate: alice.address});
-
- const priority = 112;
- await helper.getSudo().scheduler.changePriority(alice, scheduledId, priority);
-
- const priorityChanged = await helper.wait.event(
- waitForBlocks,
- 'scheduler',
- 'PriorityChanged',
- );
-
- expect(priorityChanged !== null).to.be.true;
- expect(priorityChanged!.event.data[2].toString()).to.be.equal(priority.toString());
- });
-
- itSub.ifWithPallets('Prioritized operations executes in valid order', [Pallets.Scheduler], async ({helper}) => {
- const [
- scheduledFirstId,
- scheduledSecondId,
- ] = await helper.arrange.makeScheduledIds(2);
-
- const currentBlockNumber = await helper.chain.getLatestBlockNumber();
- const blocksBeforeExecution = 4;
- const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;
-
- const prioHigh = 0;
- const prioLow = 255;
-
- const periodic = {
- period: 6,
- repetitions: 2,
- };
-
- const amount = 1n * helper.balance.getOneTokenNominal();
-
- // Scheduler a task with a lower priority first, then with a higher priority
- await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})
- .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);
-
- await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})
- .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);
-
- const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');
-
- await helper.wait.newBlocks(blocksBeforeExecution);
-
- // Flip priorities
- await helper.getSudo().scheduler.changePriority(alice, scheduledFirstId, prioHigh);
- await helper.getSudo().scheduler.changePriority(alice, scheduledSecondId, prioLow);
-
- await helper.wait.newBlocks(periodic.period);
-
- const dispatchEvents = capture.extractCapturedEvents();
- expect(dispatchEvents.length).to.be.equal(4);
-
- const dispatchedIds = dispatchEvents.map(r => r.event.data[1].toString());
-
- const firstExecuctionIds = [dispatchedIds[0], dispatchedIds[1]];
- const secondExecuctionIds = [dispatchedIds[2], dispatchedIds[3]];
-
- expect(firstExecuctionIds[0]).to.be.equal(scheduledSecondId);
- expect(firstExecuctionIds[1]).to.be.equal(scheduledFirstId);
-
- expect(secondExecuctionIds[0]).to.be.equal(scheduledFirstId);
- expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);
- });
-});
-
-describe('Negative Test: Scheduling', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
-
- before(async () => {
- await usingPlaygrounds(async (helper, privateKeyWrapper) => {
- alice = await privateKeyWrapper('//Alice');
- bob = await privateKeyWrapper('//Bob');
-
- await helper.testUtils.enable();
- });
- });
-
- itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler], async ({helper}) => {
- const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
- const token = await collection.mintToken(alice);
-
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
-
- await token.scheduleAfter(scheduledId, waitForBlocks)
- .transfer(alice, {Substrate: bob.address});
-
- const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);
- await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * helper.balance.getOneTokenNominal()))
- .to.be.rejectedWith(/scheduler\.FailedToSchedule/);
-
- const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);
-
- expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
- expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);
- });
-
- itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
- await expect(helper.scheduler.cancelScheduled(alice, scheduledId))
- .to.be.rejectedWith(/scheduler\.NotFound/);
- });
-
- itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler], async ({helper}) => {
- const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
- const token = await collection.mintToken(alice);
-
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
-
- await token.scheduleAfter(scheduledId, waitForBlocks)
- .transfer(alice, {Substrate: bob.address});
-
- await expect(helper.scheduler.cancelScheduled(bob, scheduledId))
- .to.be.rejectedWith(/BadOrigin/);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
- });
-
- itSub.ifWithPallets("Regular user can't set prioritized scheduled operation", [Pallets.Scheduler], async ({helper}) => {
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
-
- const amount = 42n * helper.balance.getOneTokenNominal();
-
- const balanceBefore = await helper.balance.getSubstrate(bob.address);
-
- const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});
-
- await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))
- .to.be.rejectedWith(/BadOrigin/);
-
- await helper.wait.newBlocks(waitForBlocks + 1);
-
- const balanceAfter = await helper.balance.getSubstrate(bob.address);
-
- expect(balanceAfter).to.be.equal(balanceBefore);
- });
-
- itSub.ifWithPallets("Regular user can't change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {
- const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
- const token = await collection.mintToken(bob);
-
- const scheduledId = await helper.arrange.makeScheduledId();
- const waitForBlocks = 4;
-
- await token.scheduleAfter(scheduledId, waitForBlocks)
- .transfer(bob, {Substrate: alice.address});
-
- const priority = 112;
- await expect(helper.scheduler.changePriority(alice, scheduledId, priority))
- .to.be.rejectedWith(/BadOrigin/);
-
- const priorityChanged = await helper.wait.event(
- waitForBlocks,
- 'scheduler',
- 'PriorityChanged',
- );
-
- expect(priorityChanged === null).to.be.true;
- });
-});
-
-// Implementation of the functionality tested here was postponed/shelved
-describe.skip('Sponsoring scheduling', () => {
- // let alice: IKeyringPair;
- // let bob: IKeyringPair;
-
- // before(async() => {
- // await usingApi(async (_, privateKeyWrapper) => {
- // alice = privateKeyWrapper('//Alice');
- // bob = privateKeyWrapper('//Bob');
- // });
- // });
-
- it('Can sponsor scheduling a transaction', async () => {
- // const collectionId = await createCollectionExpectSuccess();
- // await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
-
- // await usingApi(async api => {
- // const scheduledId = await makeScheduledId();
- // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
-
- // const bobBalanceBefore = await getFreeBalance(bob);
- // const waitForBlocks = 4;
- // // no need to wait to check, fees must be deducted on scheduling, immediately
- // await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);
- // const bobBalanceAfter = await getFreeBalance(bob);
- // // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
- // expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
- // // wait for sequentiality matters
- // await waitNewBlocks(waitForBlocks - 1);
- // });
- });
-
- it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
- // await usingApi(async (api, privateKeyWrapper) => {
- // // Find an empty, unused account
- // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
-
- // const collectionId = await createCollectionExpectSuccess();
-
- // // Add zeroBalance address to allow list
- // await enablePublicMintingExpectSuccess(alice, collectionId);
- // await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
-
- // // Grace zeroBalance with money, enough to cover future transactions
- // const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
- // await submitTransactionAsync(alice, balanceTx);
-
- // // Mint a fresh NFT
- // const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
- // const scheduledId = await makeScheduledId();
-
- // // Schedule transfer of the NFT a few blocks ahead
- // const waitForBlocks = 5;
- // await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);
-
- // // Get rid of the account's funds before the scheduled transaction takes place
- // const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
- // const events = await submitTransactionAsync(zeroBalance, balanceTx2);
- // expect(getGenericResult(events).success).to.be.true;
- // /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
- // const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
- // const events = await submitTransactionAsync(alice, sudoTx);
- // expect(getGenericResult(events).success).to.be.true;*/
-
- // // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
- // await waitNewBlocks(waitForBlocks - 3);
-
- // expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
- // });
- });
-
- it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
- // const collectionId = await createCollectionExpectSuccess();
-
- // await usingApi(async (api, privateKeyWrapper) => {
- // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
- // const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
- // await submitTransactionAsync(alice, balanceTx);
-
- // await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
- // await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
-
- // const scheduledId = await makeScheduledId();
- // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
-
- // const waitForBlocks = 5;
- // await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);
-
- // const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
- // const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
- // const events = await submitTransactionAsync(alice, sudoTx);
- // expect(getGenericResult(events).success).to.be.true;
-
- // // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
- // await waitNewBlocks(waitForBlocks - 3);
-
- // expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
- // });
- });
-
- it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {
- // const collectionId = await createCollectionExpectSuccess();
- // await setCollectionSponsorExpectSuccess(collectionId, bob.address);
- // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
-
- // await usingApi(async (api, privateKeyWrapper) => {
- // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
-
- // await enablePublicMintingExpectSuccess(alice, collectionId);
- // await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
-
- // const bobBalanceBefore = await getFreeBalance(bob);
-
- // const createData = {nft: {const_data: [], variable_data: []}};
- // const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
- // const scheduledId = await makeScheduledId();
-
- // /*const badTransaction = async function () {
- // await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
- // };
- // await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
-
- // await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);
-
- // expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
- // });
- });
-});
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.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -422,8 +422,8 @@
return promise;
}
- async forParachainBlockNumber(blockNumber: bigint, timeout?: number) {
- timeout = timeout ?? 300_000;
+ async forParachainBlockNumber(blockNumber: bigint | number, timeout?: number) {
+ timeout = timeout ?? 30 * 60 * 1000;
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<void>(async (resolve) => {
const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads((data: any) => {
@@ -437,8 +437,8 @@
return promise;
}
- async forRelayBlockNumber(blockNumber: bigint, timeout?: number) {
- timeout = timeout ?? 300_000;
+ async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {
+ timeout = timeout ?? 30 * 60 * 1000;
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<void>(async (resolve) => {
const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {
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