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.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -35,7 +35,6 @@
use pallet_common::{
erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
CollectionHandle, CollectionPropertyPermissions,
- eth::convert_tuple_to_cross_account,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
@@ -675,11 +674,11 @@
fn approve_cross(
&mut self,
caller: caller,
- approved: (address, uint256),
+ approved: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let approved = convert_tuple_to_cross_account::<T>(approved)?;
+ let approved = approved.into_sub_cross_account::<T>()?;
let token = token_id.try_into()?;
<Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))
@@ -715,13 +714,13 @@
fn transfer_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
- to: (address, uint256),
+ from: EthCrossAccount,
+ to: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
- let to = convert_tuple_to_cross_account::<T>(to)?;
+ let from = from.into_sub_cross_account::<T>()?;
+ let to = to.into_sub_cross_account::<T>()?;
let token_id = token_id.try_into()?;
let budget = self
.recorder
@@ -761,11 +760,11 @@
fn burn_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
+ from: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
+ let from = from.into_sub_cross_account::<T>()?;
let token = token_id.try_into()?;
let budget = self
.recorder
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -67,7 +67,7 @@
/// @param properties settable properties
/// @dev EVM selector for this function is: 0x14ed3a6e,
/// or in textual repr: setProperties(uint256,(string,bytes)[])
- function setProperties(uint256 tokenId, Tuple19[] memory properties) public {
+ function setProperties(uint256 tokenId, Tuple21[] memory properties) public {
require(false, stub_error);
tokenId;
properties;
@@ -124,7 +124,7 @@
/// @param properties Vector of properties key/value pair.
/// @dev EVM selector for this function is: 0x50b26b2a,
/// or in textual repr: setCollectionProperties((string,bytes)[])
- function setCollectionProperties(Tuple19[] memory properties) public {
+ function setCollectionProperties(Tuple21[] memory properties) public {
require(false, stub_error);
properties;
dummy = 0;
@@ -173,11 +173,11 @@
/// @return Vector of properties key/value pairs.
/// @dev EVM selector for this function is: 0x285fb8e6,
/// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) public view returns (Tuple19[] memory) {
+ function collectionProperties(string[] memory keys) public view returns (Tuple21[] memory) {
require(false, stub_error);
keys;
dummy;
- return new Tuple19[](0);
+ return new Tuple21[](0);
}
/// Set the sponsor of the collection.
@@ -200,7 +200,7 @@
/// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
/// @dev EVM selector for this function is: 0x84a1d5a8,
/// or in textual repr: setCollectionSponsorCross((address,uint256))
- function setCollectionSponsorCross(Tuple6 memory sponsor) public {
+ function setCollectionSponsorCross(EthCrossAccount memory sponsor) public {
require(false, stub_error);
sponsor;
dummy = 0;
@@ -238,10 +238,10 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() public view returns (Tuple6 memory) {
+ function collectionSponsor() public view returns (Tuple24 memory) {
require(false, stub_error);
dummy;
- return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ return Tuple24(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -292,7 +292,7 @@
/// @param newAdmin Cross account administrator address.
/// @dev EVM selector for this function is: 0x859aa7d6,
/// or in textual repr: addCollectionAdminCross((address,uint256))
- function addCollectionAdminCross(Tuple6 memory newAdmin) public {
+ function addCollectionAdminCross(EthCrossAccount memory newAdmin) public {
require(false, stub_error);
newAdmin;
dummy = 0;
@@ -302,7 +302,7 @@
/// @param admin Cross account administrator address.
/// @dev EVM selector for this function is: 0x6c0cd173,
/// or in textual repr: removeCollectionAdminCross((address,uint256))
- function removeCollectionAdminCross(Tuple6 memory admin) public {
+ function removeCollectionAdminCross(EthCrossAccount memory admin) public {
require(false, stub_error);
admin;
dummy = 0;
@@ -393,7 +393,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0xa0184a3a,
/// or in textual repr: addToCollectionAllowListCross((address,uint256))
- function addToCollectionAllowListCross(Tuple6 memory user) public {
+ function addToCollectionAllowListCross(EthCrossAccount memory user) public {
require(false, stub_error);
user;
dummy = 0;
@@ -415,7 +415,7 @@
/// @param user User cross account address.
/// @dev EVM selector for this function is: 0x09ba452a,
/// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
- function removeFromCollectionAllowListCross(Tuple6 memory user) public {
+ function removeFromCollectionAllowListCross(EthCrossAccount memory user) public {
require(false, stub_error);
user;
dummy = 0;
@@ -451,7 +451,7 @@
/// @return "true" if account is the owner or admin
/// @dev EVM selector for this function is: 0x3e75a905,
/// or in textual repr: isOwnerOrAdminCross((address,uint256))
- function isOwnerOrAdminCross(Tuple6 memory user) public view returns (bool) {
+ function isOwnerOrAdminCross(EthCrossAccount memory user) public view returns (bool) {
require(false, stub_error);
user;
dummy;
@@ -471,14 +471,14 @@
/// Get collection owner.
///
- /// @return Tuple with sponsor address and his substrate mirror.
+ /// @return Tuble with sponsor address and his substrate mirror.
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() public view returns (Tuple6 memory) {
+ function collectionOwner() public view returns (EthCrossAccount memory) {
require(false, stub_error);
dummy;
- return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ return EthCrossAccount(0x0000000000000000000000000000000000000000, 0);
}
/// Changes collection owner to another account
@@ -499,10 +499,10 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0x5813216b,
/// or in textual repr: collectionAdmins()
- function collectionAdmins() public view returns (Tuple6[] memory) {
+ function collectionAdmins() public view returns (EthCrossAccount[] memory) {
require(false, stub_error);
dummy;
- return new Tuple6[](0);
+ return new EthCrossAccount[](0);
}
/// Changes collection owner to another account
@@ -511,15 +511,27 @@
/// @param newOwner new owner cross account
/// @dev EVM selector for this function is: 0xe5c9913f,
/// or in textual repr: setOwnerCross((address,uint256))
- function setOwnerCross(Tuple6 memory newOwner) public {
+ function setOwnerCross(EthCrossAccount memory newOwner) public {
require(false, stub_error);
newOwner;
dummy = 0;
}
}
+/// @dev Cross account struct
+struct EthCrossAccount {
+ address eth;
+ uint256 sub;
+}
+
/// @dev anonymous struct
-struct Tuple19 {
+struct Tuple24 {
+ address field_0;
+ uint256 field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple21 {
string field_0;
bytes field_1;
}
@@ -696,7 +708,7 @@
/// @param tokenId The NFT to approve
/// @dev EVM selector for this function is: 0x0ecd0ab0,
/// or in textual repr: approveCross((address,uint256),uint256)
- function approveCross(Tuple6 memory approved, uint256 tokenId) public {
+ function approveCross(EthCrossAccount memory approved, uint256 tokenId) public {
require(false, stub_error);
approved;
tokenId;
@@ -726,8 +738,8 @@
/// @dev EVM selector for this function is: 0xd5cf430b,
/// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
function transferFromCross(
- Tuple6 memory from,
- Tuple6 memory to,
+ EthCrossAccount memory from,
+ EthCrossAccount memory to,
uint256 tokenId
) public {
require(false, stub_error);
@@ -760,7 +772,7 @@
/// @param tokenId The NFT to transfer
/// @dev EVM selector for this function is: 0xbb2f5a58,
/// or in textual repr: burnFromCross((address,uint256),uint256)
- function burnFromCross(Tuple6 memory from, uint256 tokenId) public {
+ function burnFromCross(EthCrossAccount memory from, uint256 tokenId) public {
require(false, stub_error);
from;
tokenId;
@@ -797,7 +809,7 @@
// /// @param tokens array of pairs of token ID and token URI for minted tokens
// /// @dev EVM selector for this function is: 0x36543006,
// /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- // function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+ // function mintBulkWithTokenURI(address to, Tuple10[] memory tokens) public returns (bool) {
// require(false, stub_error);
// to;
// tokens;
@@ -808,15 +820,9 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple10 {
uint256 field_0;
string field_1;
-}
-
-/// @dev anonymous struct
-struct Tuple6 {
- address field_0;
- uint256 field_1;
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -2,6 +2,10 @@
All notable changes to this project will be documented in this file.
+## [v0.2.6] - 2022-11-02
+### Changed
+ - Use named structure `EthCrossAccount` in eth functions.
+
## [v0.2.5] - 2022-20-10
### Change
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-refungible"
-version = "0.2.5"
+version = "0.2.6"
license = "GPLv3"
edition = "2021"
@@ -26,7 +26,9 @@
struct-versioning = { path = "../../crates/struct-versioning" }
up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
ethereum = { version = "0.12.0", default-features = false }
-scale-info = { version = "2.0.1", default-features = false, features = ["derive",] }
+scale-info = { version = "2.0.1", default-features = false, features = [
+ "derive",
+] }
derivative = { version = "2.2.0", features = ["use_core"] }
[features]
@@ -52,3 +54,4 @@
'up-data-structs/runtime-benchmarks',
]
try-runtime = ["frame-support/try-runtime"]
+stubgen = ["evm-coder/stubgen", "pallet-common/stubgen"]
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -30,7 +30,6 @@
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions,
erc::{CommonEvmHandler, CollectionCall, static_property::key},
- eth::convert_tuple_to_cross_account,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -725,13 +724,13 @@
fn transfer_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
- to: (address, uint256),
+ from: EthCrossAccount,
+ to: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
- let to = convert_tuple_to_cross_account::<T>(to)?;
+ let from = from.into_sub_cross_account::<T>()?;
+ let to = to.into_sub_cross_account::<T>()?;
let token_id = token_id.try_into()?;
let budget = self
.recorder
@@ -780,11 +779,11 @@
fn burn_from_cross(
&mut self,
caller: caller,
- from: (address, uint256),
+ from: EthCrossAccount,
token_id: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let from = convert_tuple_to_cross_account::<T>(from)?;
+ let from = from.into_sub_cross_account::<T>()?;
let token = token_id.try_into()?;
let budget = self
.recorder
pallets/refungible/src/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.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {13 IApiListeners,14 IBlock,15 IEvent,16 IChainProperties,17 ICollectionCreationOptions,18 ICollectionLimits,19 ICollectionPermissions,20 ICrossAccountId,21 ICrossAccountIdLower,22 ILogger,23 INestingPermissions,24 IProperty,25 IStakingInfo,26 ISchedulerOptions,27 ISubstrateBalance,28 IToken,29 ITokenPropertyPermission,30 ITransactionResult,31 IUniqueHelperLog,32 TApiAllowedListeners,33 TEthereumAccount,34 TSigner,35 TSubstrateAccount,36 TNetworks,37 IForeignAssetMetadata,38 AcalaAssetMetadata,39 MoonbeamAssetInfo,40 DemocracyStandardAccountVote,41} from './types';42import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';4344export class CrossAccountId implements ICrossAccountId {45 Substrate?: TSubstrateAccount;46 Ethereum?: TEthereumAccount;4748 constructor(account: ICrossAccountId) {49 if (account.Substrate) this.Substrate = account.Substrate;50 if (account.Ethereum) this.Ethereum = account.Ethereum;51 }5253 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {54 switch (domain) {55 case 'Substrate': return new CrossAccountId({Substrate: account.address});56 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();57 }58 }5960 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {61 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});62 }6364 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {65 return encodeAddress(decodeAddress(address), ss58Format);66 }6768 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {69 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});70 }7172 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {73 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);74 return this;75 }7677 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {78 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));79 }8081 toEthereum(): CrossAccountId {82 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});83 return this;84 }8586 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {87 return evmToAddress(address, ss58Format);88 }8990 toSubstrate(ss58Format?: number): CrossAccountId {91 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});92 return this;93 }9495 toLowerCase(): CrossAccountId {96 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();97 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();98 return this;99 }100}101102const nesting = {103 toChecksumAddress(address: string): string {104 if (typeof address === 'undefined') return '';105106 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);107108 address = address.toLowerCase().replace(/^0x/i,'');109 const addressHash = keccakAsHex(address).replace(/^0x/i,'');110 const checksumAddress = ['0x'];111112 for (let i = 0; i < address.length; i++) {113 // If ith character is 8 to f then make it uppercase114 if (parseInt(addressHash[i], 16) > 7) {115 checksumAddress.push(address[i].toUpperCase());116 } else {117 checksumAddress.push(address[i]);118 }119 }120 return checksumAddress.join('');121 },122 tokenIdToAddress(collectionId: number, tokenId: number) {123 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);124 },125};126127class UniqueUtil {128 static transactionStatus = {129 NOT_READY: 'NotReady',130 FAIL: 'Fail',131 SUCCESS: 'Success',132 };133134 static chainLogType = {135 EXTRINSIC: 'extrinsic',136 RPC: 'rpc',137 };138139 static getTokenAccount(token: IToken): CrossAccountId {140 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});141 }142143 static getTokenAddress(token: IToken): string {144 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);145 }146147 static getDefaultLogger(): ILogger {148 return {149 log(msg: any, level = 'INFO') {150 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));151 },152 level: {153 ERROR: 'ERROR',154 WARNING: 'WARNING',155 INFO: 'INFO',156 },157 };158 }159160 static vec2str(arr: string[] | number[]) {161 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');162 }163164 static str2vec(string: string) {165 if (typeof string !== 'string') return string;166 return Array.from(string).map(x => x.charCodeAt(0));167 }168169 static fromSeed(seed: string, ss58Format = 42) {170 const keyring = new Keyring({type: 'sr25519', ss58Format});171 return keyring.addFromUri(seed);172 }173174 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {175 if (creationResult.status !== this.transactionStatus.SUCCESS) {176 throw Error('Unable to create collection!');177 }178179 let collectionId = null;180 creationResult.result.events.forEach(({event: {data, method, section}}) => {181 if ((section === 'common') && (method === 'CollectionCreated')) {182 collectionId = parseInt(data[0].toString(), 10);183 }184 });185186 if (collectionId === null) {187 throw Error('No CollectionCreated event was found!');188 }189190 return collectionId;191 }192193 static extractTokensFromCreationResult(creationResult: ITransactionResult): {194 success: boolean,195 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],196 } {197 if (creationResult.status !== this.transactionStatus.SUCCESS) {198 throw Error('Unable to create tokens!');199 }200 let success = false;201 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];202 creationResult.result.events.forEach(({event: {data, method, section}}) => {203 if (method === 'ExtrinsicSuccess') {204 success = true;205 } else if ((section === 'common') && (method === 'ItemCreated')) {206 tokens.push({207 collectionId: parseInt(data[0].toString(), 10),208 tokenId: parseInt(data[1].toString(), 10),209 owner: data[2].toHuman(),210 amount: data[3].toBigInt(),211 });212 }213 });214 return {success, tokens};215 }216217 static extractTokensFromBurnResult(burnResult: ITransactionResult): {218 success: boolean,219 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],220 } {221 if (burnResult.status !== this.transactionStatus.SUCCESS) {222 throw Error('Unable to burn tokens!');223 }224 let success = false;225 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];226 burnResult.result.events.forEach(({event: {data, method, section}}) => {227 if (method === 'ExtrinsicSuccess') {228 success = true;229 } else if ((section === 'common') && (method === 'ItemDestroyed')) {230 tokens.push({231 collectionId: parseInt(data[0].toString(), 10),232 tokenId: parseInt(data[1].toString(), 10),233 owner: data[2].toHuman(),234 amount: data[3].toBigInt(),235 });236 }237 });238 return {success, tokens};239 }240241 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {242 let eventId = null;243 events.forEach(({event: {data, method, section}}) => {244 if ((section === expectedSection) && (method === expectedMethod)) {245 eventId = parseInt(data[0].toString(), 10);246 }247 });248249 if (eventId === null) {250 throw Error(`No ${expectedMethod} event was found!`);251 }252 return eventId === collectionId;253 }254255 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {256 const normalizeAddress = (address: string | ICrossAccountId) => {257 if(typeof address === 'string') return address;258 const obj = {} as any;259 Object.keys(address).forEach(k => {260 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];261 });262 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);263 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();264 return address;265 };266 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;267 events.forEach(({event: {data, method, section}}) => {268 if ((section === 'common') && (method === 'Transfer')) {269 const hData = (data as any).toJSON();270 transfer = {271 collectionId: hData[0],272 tokenId: hData[1],273 from: normalizeAddress(hData[2]),274 to: normalizeAddress(hData[3]),275 amount: BigInt(hData[4]),276 };277 }278 });279 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;280 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);281 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);282 isSuccess = isSuccess && amount === transfer.amount;283 return isSuccess;284 }285286 static bigIntToDecimals(number: bigint, decimals = 18) {287 const numberStr = number.toString();288 const dotPos = numberStr.length - decimals;289290 if (dotPos <= 0) {291 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;292 } else {293 const intPart = numberStr.substring(0, dotPos);294 const fractPart = numberStr.substring(dotPos);295 return intPart + '.' + fractPart;296 }297 }298}299300class UniqueEventHelper {301 private static extractIndex(index: any): [number, number] | string {302 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];303 return index.toJSON();304 }305306 private static extractSub(data: any, subTypes: any): {[key: string]: any} {307 let obj: any = {};308 let index = 0;309310 if (data.entries) {311 for(const [key, value] of data.entries()) {312 obj[key] = this.extractData(value, subTypes[index]);313 index++;314 }315 } else obj = data.toJSON();316317 return obj;318 }319320 private static extractData(data: any, type: any): any {321 if(!type) return data.toHuman();322 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();323 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();324 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);325 return data.toHuman();326 }327328 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {329 const parsedEvents: IEvent[] = [];330331 events.forEach((record) => {332 const {event, phase} = record;333 const types = event.typeDef;334335 const eventData: IEvent = {336 section: event.section.toString(),337 method: event.method.toString(),338 index: this.extractIndex(event.index),339 data: [],340 phase: phase.toJSON(),341 };342343 event.data.forEach((val: any, index: number) => {344 eventData.data.push(this.extractData(val, types[index]));345 });346347 parsedEvents.push(eventData);348 });349350 return parsedEvents;351 }352}353354export class ChainHelperBase {355 helperBase: any;356357 transactionStatus = UniqueUtil.transactionStatus;358 chainLogType = UniqueUtil.chainLogType;359 util: typeof UniqueUtil;360 eventHelper: typeof UniqueEventHelper;361 logger: ILogger;362 api: ApiPromise | null;363 forcedNetwork: TNetworks | null;364 network: TNetworks | null;365 chainLog: IUniqueHelperLog[];366 children: ChainHelperBase[];367 address: AddressGroup;368 chain: ChainGroup;369370 constructor(logger?: ILogger, helperBase?: any) {371 this.helperBase = helperBase;372373 this.util = UniqueUtil;374 this.eventHelper = UniqueEventHelper;375 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();376 this.logger = logger;377 this.api = null;378 this.forcedNetwork = null;379 this.network = null;380 this.chainLog = [];381 this.children = [];382 this.address = new AddressGroup(this);383 this.chain = new ChainGroup(this);384 }385386 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {387 Object.setPrototypeOf(helperCls.prototype, this);388 const newHelper = new helperCls(this.logger, options);389390 newHelper.api = this.api;391 newHelper.network = this.network;392 newHelper.forceNetwork = this.forceNetwork;393394 this.children.push(newHelper);395396 return newHelper;397 }398399 getApi(): ApiPromise {400 if(this.api === null) throw Error('API not initialized');401 return this.api;402 }403404 clearChainLog(): void {405 this.chainLog = [];406 }407408 forceNetwork(value: TNetworks): void {409 this.forcedNetwork = value;410 }411412 async connect(wsEndpoint: string, listeners?: IApiListeners) {413 if (this.api !== null) throw Error('Already connected');414 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);415 this.api = api;416 this.network = network;417 }418419 async disconnect() {420 for (const child of this.children) {421 child.clearApi();422 }423424 if (this.api === null) return;425 await this.api.disconnect();426 this.clearApi();427 }428429 clearApi() {430 this.api = null;431 this.network = null;432 }433434 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {435 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;436 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];437438 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;439440 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;441 return 'opal';442 }443444 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {445 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});446 await api.isReady;447448 const network = await this.detectNetwork(api);449450 await api.disconnect();451452 return network;453 }454455 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{456 api: ApiPromise;457 network: TNetworks;458 }> {459 if(typeof network === 'undefined' || network === null) network = 'opal';460 const supportedRPC = {461 opal: {462 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,463 },464 quartz: {465 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,466 },467 unique: {468 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,469 },470 rococo: {},471 westend: {},472 moonbeam: {},473 moonriver: {},474 acala: {},475 karura: {},476 westmint: {},477 };478 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);479 const rpc = supportedRPC[network];480481 // TODO: investigate how to replace rpc in runtime482 // api._rpcCore.addUserInterfaces(rpc);483484 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});485486 await api.isReadyOrError;487488 if (typeof listeners === 'undefined') listeners = {};489 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {490 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;491 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);492 }493494 return {api, network};495 }496497 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {498 const {events, status} = data;499 if (status.isReady) {500 return this.transactionStatus.NOT_READY;501 }502 if (status.isBroadcast) {503 return this.transactionStatus.NOT_READY;504 }505 if (status.isInBlock || status.isFinalized) {506 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');507 if (errors.length > 0) {508 return this.transactionStatus.FAIL;509 }510 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {511 return this.transactionStatus.SUCCESS;512 }513 }514515 return this.transactionStatus.FAIL;516 }517518 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {519 const sign = (callback: any) => {520 if(options !== null) return transaction.signAndSend(sender, options, callback);521 return transaction.signAndSend(sender, callback);522 };523 // eslint-disable-next-line no-async-promise-executor524 return new Promise(async (resolve, reject) => {525 try {526 const unsub = await sign((result: any) => {527 const status = this.getTransactionStatus(result);528529 if (status === this.transactionStatus.SUCCESS) {530 this.logger.log(`${label} successful`);531 unsub();532 resolve({result, status});533 } else if (status === this.transactionStatus.FAIL) {534 let moduleError = null;535536 if (result.hasOwnProperty('dispatchError')) {537 const dispatchError = result['dispatchError'];538539 if (dispatchError) {540 if (dispatchError.isModule) {541 const modErr = dispatchError.asModule;542 const errorMeta = dispatchError.registry.findMetaError(modErr);543544 moduleError = `${errorMeta.section}.${errorMeta.name}`;545 } else {546 moduleError = dispatchError.toHuman();547 }548 } else {549 this.logger.log(result, this.logger.level.ERROR);550 }551 }552553 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);554 unsub();555 reject({status, moduleError, result});556 }557 });558 } catch (e) {559 this.logger.log(e, this.logger.level.ERROR);560 reject(e);561 }562 });563 }564565 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {566 const api = this.getApi();567 const signingInfo = await api.derive.tx.signingInfo(signer.address);568569 // We need to sign the tx because570 // unsigned transactions does not have an inclusion fee571 tx.sign(signer, {572 blockHash: api.genesisHash,573 genesisHash: api.genesisHash,574 runtimeVersion: api.runtimeVersion,575 nonce: signingInfo.nonce,576 });577578 if (len === null) {579 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;580 } else {581 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;582 }583 }584585 constructApiCall(apiCall: string, params: any[]) {586 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);587 let call = this.getApi() as any;588 for(const part of apiCall.slice(4).split('.')) {589 call = call[part];590 }591 return call(...params);592 }593594 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {595 if(this.api === null) throw Error('API not initialized');596 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);597598 const startTime = (new Date()).getTime();599 let result: ITransactionResult;600 let events: IEvent[] = [];601 try {602 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;603 events = this.eventHelper.extractEvents(result.result.events);604 }605 catch(e) {606 if(!(e as object).hasOwnProperty('status')) throw e;607 result = e as ITransactionResult;608 }609610 const endTime = (new Date()).getTime();611612 const log = {613 executedAt: endTime,614 executionTime: endTime - startTime,615 type: this.chainLogType.EXTRINSIC,616 status: result.status,617 call: extrinsic,618 signer: this.getSignerAddress(sender),619 params,620 } as IUniqueHelperLog;621622 if(result.status !== this.transactionStatus.SUCCESS) {623 if (result.moduleError) log.moduleError = result.moduleError;624 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;625 }626 if(events.length > 0) log.events = events;627628 this.chainLog.push(log);629630 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {631 if (result.moduleError) throw Error(`${result.moduleError}`);632 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));633 }634 return result;635 }636637 async callRpc(rpc: string, params?: any[]) {638 if(typeof params === 'undefined') params = [];639 if(this.api === null) throw Error('API not initialized');640 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);641642 const startTime = (new Date()).getTime();643 let result;644 let error = null;645 const log = {646 type: this.chainLogType.RPC,647 call: rpc,648 params,649 } as IUniqueHelperLog;650651 try {652 result = await this.constructApiCall(rpc, params);653 }654 catch(e) {655 error = e;656 }657658 const endTime = (new Date()).getTime();659660 log.executedAt = endTime;661 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';662 log.executionTime = endTime - startTime;663664 this.chainLog.push(log);665666 if(error !== null) throw error;667668 return result;669 }670671 getSignerAddress(signer: IKeyringPair | string): string {672 if(typeof signer === 'string') return signer;673 return signer.address;674 }675676 fetchAllPalletNames(): string[] {677 if(this.api === null) throw Error('API not initialized');678 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());679 }680681 fetchMissingPalletNames(requiredPallets: string[]): string[] {682 const palletNames = this.fetchAllPalletNames();683 return requiredPallets.filter(p => !palletNames.includes(p));684 }685}686687688class HelperGroup<T extends ChainHelperBase> {689 helper: T;690691 constructor(uniqueHelper: T) {692 this.helper = uniqueHelper;693 }694}695696697class CollectionGroup extends HelperGroup<UniqueHelper> {698 /**699 * Get number of blocks when sponsored transaction is available.700 *701 * @param collectionId ID of collection702 * @param tokenId ID of token703 * @param addressObj address for which the sponsorship is checked704 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});705 * @returns number of blocks or null if sponsorship hasn't been set706 */707 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {708 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();709 }710711 /**712 * Get the number of created collections.713 *714 * @returns number of created collections715 */716 async getTotalCount(): Promise<number> {717 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();718 }719720 /**721 * Get information about the collection with additional data,722 * including the number of tokens it contains, its administrators,723 * the normalized address of the collection's owner, and decoded name and description.724 *725 * @param collectionId ID of collection726 * @example await getData(2)727 * @returns collection information object728 */729 async getData(collectionId: number): Promise<{730 id: number;731 name: string;732 description: string;733 tokensCount: number;734 admins: CrossAccountId[];735 normalizedOwner: TSubstrateAccount;736 raw: any737 } | null> {738 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);739 const humanCollection = collection.toHuman(), collectionData = {740 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],741 raw: humanCollection,742 } as any, jsonCollection = collection.toJSON();743 if (humanCollection === null) return null;744 collectionData.raw.limits = jsonCollection.limits;745 collectionData.raw.permissions = jsonCollection.permissions;746 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);747 for (const key of ['name', 'description']) {748 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);749 }750751 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))752 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)753 : 0;754 collectionData.admins = await this.getAdmins(collectionId);755756 return collectionData;757 }758759 /**760 * Get the addresses of the collection's administrators, optionally normalized.761 *762 * @param collectionId ID of collection763 * @param normalize whether to normalize the addresses to the default ss58 format764 * @example await getAdmins(1)765 * @returns array of administrators766 */767 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {768 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();769770 return normalize771 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())772 : admins;773 }774775 /**776 * Get the addresses added to the collection allow-list, optionally normalized.777 * @param collectionId ID of collection778 * @param normalize whether to normalize the addresses to the default ss58 format779 * @example await getAllowList(1)780 * @returns array of allow-listed addresses781 */782 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {783 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();784 return normalize785 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())786 : allowListed;787 }788789 /**790 * Get the effective limits of the collection instead of null for default values791 *792 * @param collectionId ID of collection793 * @example await getEffectiveLimits(2)794 * @returns object of collection limits795 */796 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {797 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();798 }799800 /**801 * Burns the collection if the signer has sufficient permissions and collection is empty.802 *803 * @param signer keyring of signer804 * @param collectionId ID of collection805 * @example await helper.collection.burn(aliceKeyring, 3);806 * @returns ```true``` if extrinsic success, otherwise ```false```807 */808 async burn(signer: TSigner, collectionId: number): Promise<boolean> {809 const result = await this.helper.executeExtrinsic(810 signer,811 'api.tx.unique.destroyCollection', [collectionId],812 true,813 );814815 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');816 }817818 /**819 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.820 *821 * @param signer keyring of signer822 * @param collectionId ID of collection823 * @param sponsorAddress Sponsor substrate address824 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")825 * @returns ```true``` if extrinsic success, otherwise ```false```826 */827 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {828 const result = await this.helper.executeExtrinsic(829 signer,830 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],831 true,832 );833834 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');835 }836837 /**838 * Confirms consent to sponsor the collection on behalf of the signer.839 *840 * @param signer keyring of signer841 * @param collectionId ID of collection842 * @example confirmSponsorship(aliceKeyring, 10)843 * @returns ```true``` if extrinsic success, otherwise ```false```844 */845 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {846 const result = await this.helper.executeExtrinsic(847 signer,848 'api.tx.unique.confirmSponsorship', [collectionId],849 true,850 );851852 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');853 }854855 /**856 * Removes the sponsor of a collection, regardless if it consented or not.857 *858 * @param signer keyring of signer859 * @param collectionId ID of collection860 * @example removeSponsor(aliceKeyring, 10)861 * @returns ```true``` if extrinsic success, otherwise ```false```862 */863 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {864 const result = await this.helper.executeExtrinsic(865 signer,866 'api.tx.unique.removeCollectionSponsor', [collectionId],867 true,868 );869870 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');871 }872873 /**874 * Sets the limits of the collection. At least one limit must be specified for a correct call.875 *876 * @param signer keyring of signer877 * @param collectionId ID of collection878 * @param limits collection limits object879 * @example880 * await setLimits(881 * aliceKeyring,882 * 10,883 * {884 * sponsorTransferTimeout: 0,885 * ownerCanDestroy: false886 * }887 * )888 * @returns ```true``` if extrinsic success, otherwise ```false```889 */890 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {891 const result = await this.helper.executeExtrinsic(892 signer,893 'api.tx.unique.setCollectionLimits', [collectionId, limits],894 true,895 );896897 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');898 }899900 /**901 * Changes the owner of the collection to the new Substrate address.902 *903 * @param signer keyring of signer904 * @param collectionId ID of collection905 * @param ownerAddress substrate address of new owner906 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")907 * @returns ```true``` if extrinsic success, otherwise ```false```908 */909 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {910 const result = await this.helper.executeExtrinsic(911 signer,912 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],913 true,914 );915916 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');917 }918919 /**920 * Adds a collection administrator.921 *922 * @param signer keyring of signer923 * @param collectionId ID of collection924 * @param adminAddressObj Administrator address (substrate or ethereum)925 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})926 * @returns ```true``` if extrinsic success, otherwise ```false```927 */928 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {929 const result = await this.helper.executeExtrinsic(930 signer,931 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],932 true,933 );934935 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');936 }937938 /**939 * Removes a collection administrator.940 *941 * @param signer keyring of signer942 * @param collectionId ID of collection943 * @param adminAddressObj Administrator address (substrate or ethereum)944 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})945 * @returns ```true``` if extrinsic success, otherwise ```false```946 */947 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {948 const result = await this.helper.executeExtrinsic(949 signer,950 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],951 true,952 );953954 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');955 }956957 /**958 * Check if user is in allow list.959 *960 * @param collectionId ID of collection961 * @param user Account to check962 * @example await getAdmins(1)963 * @returns is user in allow list964 */965 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {966 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();967 }968969 /**970 * Adds an address to allow list971 * @param signer keyring of signer972 * @param collectionId ID of collection973 * @param addressObj address to add to the allow list974 * @returns ```true``` if extrinsic success, otherwise ```false```975 */976 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {977 const result = await this.helper.executeExtrinsic(978 signer,979 'api.tx.unique.addToAllowList', [collectionId, addressObj],980 true,981 );982983 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');984 }985986 /**987 * Removes an address from allow list988 *989 * @param signer keyring of signer990 * @param collectionId ID of collection991 * @param addressObj address to remove from the allow list992 * @returns ```true``` if extrinsic success, otherwise ```false```993 */994 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {995 const result = await this.helper.executeExtrinsic(996 signer,997 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],998 true,999 );10001001 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');1002 }10031004 /**1005 * Sets onchain permissions for selected collection.1006 *1007 * @param signer keyring of signer1008 * @param collectionId ID of collection1009 * @param permissions collection permissions object1010 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1011 * @returns ```true``` if extrinsic success, otherwise ```false```1012 */1013 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1014 const result = await this.helper.executeExtrinsic(1015 signer,1016 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1017 true,1018 );10191020 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1021 }10221023 /**1024 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1025 *1026 * @param signer keyring of signer1027 * @param collectionId ID of collection1028 * @param permissions nesting permissions object1029 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1030 * @returns ```true``` if extrinsic success, otherwise ```false```1031 */1032 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1033 return await this.setPermissions(signer, collectionId, {nesting: permissions});1034 }10351036 /**1037 * Disables nesting for selected collection.1038 *1039 * @param signer keyring of signer1040 * @param collectionId ID of collection1041 * @example disableNesting(aliceKeyring, 10);1042 * @returns ```true``` if extrinsic success, otherwise ```false```1043 */1044 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1045 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1046 }10471048 /**1049 * Sets onchain properties to the collection.1050 *1051 * @param signer keyring of signer1052 * @param collectionId ID of collection1053 * @param properties array of property objects1054 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1055 * @returns ```true``` if extrinsic success, otherwise ```false```1056 */1057 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1058 const result = await this.helper.executeExtrinsic(1059 signer,1060 'api.tx.unique.setCollectionProperties', [collectionId, properties],1061 true,1062 );10631064 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1065 }10661067 /**1068 * Get collection properties.1069 *1070 * @param collectionId ID of collection1071 * @param propertyKeys optionally filter the returned properties to only these keys1072 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1073 * @returns array of key-value pairs1074 */1075 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1076 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1077 }10781079 async getCollectionOptions(collectionId: number) {1080 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1081 }10821083 /**1084 * Deletes onchain properties from the collection.1085 *1086 * @param signer keyring of signer1087 * @param collectionId ID of collection1088 * @param propertyKeys array of property keys to delete1089 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1090 * @returns ```true``` if extrinsic success, otherwise ```false```1091 */1092 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1093 const result = await this.helper.executeExtrinsic(1094 signer,1095 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1096 true,1097 );10981099 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1100 }11011102 /**1103 * Changes the owner of the token.1104 *1105 * @param signer keyring of signer1106 * @param collectionId ID of collection1107 * @param tokenId ID of token1108 * @param addressObj address of a new owner1109 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1110 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1111 * @returns true if the token success, otherwise false1112 */1113 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1114 const result = await this.helper.executeExtrinsic(1115 signer,1116 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1117 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1118 );11191120 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1121 }11221123 /**1124 *1125 * Change ownership of a token(s) on behalf of the owner.1126 *1127 * @param signer keyring of signer1128 * @param collectionId ID of collection1129 * @param tokenId ID of token1130 * @param fromAddressObj address on behalf of which the token will be sent1131 * @param toAddressObj new token owner1132 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1133 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1134 * @returns true if the token success, otherwise false1135 */1136 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1137 const result = await this.helper.executeExtrinsic(1138 signer,1139 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1140 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1141 );1142 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1143 }11441145 /**1146 *1147 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1148 *1149 * @param signer keyring of signer1150 * @param collectionId ID of collection1151 * @param tokenId ID of token1152 * @param amount amount of tokens to be burned. For NFT must be set to 1n1153 * @example burnToken(aliceKeyring, 10, 5);1154 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1155 */1156 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1157 const burnResult = await this.helper.executeExtrinsic(1158 signer,1159 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1160 true, // `Unable to burn token for ${label}`,1161 );1162 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1163 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1164 return burnedTokens.success;1165 }11661167 /**1168 * Destroys a concrete instance of NFT on behalf of the owner1169 *1170 * @param signer keyring of signer1171 * @param collectionId ID of collection1172 * @param tokenId ID of token1173 * @param fromAddressObj address on behalf of which the token will be burnt1174 * @param amount amount of tokens to be burned. For NFT must be set to 1n1175 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1176 * @returns ```true``` if extrinsic success, otherwise ```false```1177 */1178 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1179 const burnResult = await this.helper.executeExtrinsic(1180 signer,1181 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1182 true, // `Unable to burn token from for ${label}`,1183 );1184 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1185 return burnedTokens.success && burnedTokens.tokens.length > 0;1186 }11871188 /**1189 * Set, change, or remove approved address to transfer the ownership of the NFT.1190 *1191 * @param signer keyring of signer1192 * @param collectionId ID of collection1193 * @param tokenId ID of token1194 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1195 * @param amount amount of token to be approved. For NFT must be set to 1n1196 * @returns ```true``` if extrinsic success, otherwise ```false```1197 */1198 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1199 const approveResult = await this.helper.executeExtrinsic(1200 signer,1201 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1202 true, // `Unable to approve token for ${label}`,1203 );12041205 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1206 }12071208 /**1209 * Get the amount of token pieces approved to transfer or burn. Normally 0.1210 *1211 * @param collectionId ID of collection1212 * @param tokenId ID of token1213 * @param toAccountObj address which is approved to use token pieces1214 * @param fromAccountObj address which may have allowed the use of its owned tokens1215 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1216 * @returns number of approved to transfer pieces1217 */1218 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1219 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1220 }12211222 /**1223 * Get the last created token ID in a collection1224 *1225 * @param collectionId ID of collection1226 * @example getLastTokenId(10);1227 * @returns id of the last created token1228 */1229 async getLastTokenId(collectionId: number): Promise<number> {1230 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1231 }12321233 /**1234 * Check if token exists1235 *1236 * @param collectionId ID of collection1237 * @param tokenId ID of token1238 * @example doesTokenExist(10, 20);1239 * @returns true if the token exists, otherwise false1240 */1241 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1242 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1243 }1244}12451246class NFTnRFT extends CollectionGroup {1247 /**1248 * Get tokens owned by account1249 *1250 * @param collectionId ID of collection1251 * @param addressObj tokens owner1252 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1253 * @returns array of token ids owned by account1254 */1255 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1256 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1257 }12581259 /**1260 * Get token data1261 *1262 * @param collectionId ID of collection1263 * @param tokenId ID of token1264 * @param propertyKeys optionally filter the token properties to only these keys1265 * @param blockHashAt optionally query the data at some block with this hash1266 * @example getToken(10, 5);1267 * @returns human readable token data1268 */1269 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1270 properties: IProperty[];1271 owner: CrossAccountId;1272 normalizedOwner: CrossAccountId;1273 }| null> {1274 let tokenData;1275 if(typeof blockHashAt === 'undefined') {1276 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1277 }1278 else {1279 if(propertyKeys.length == 0) {1280 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1281 if(!collection) return null;1282 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1283 }1284 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1285 }1286 tokenData = tokenData.toHuman();1287 if (tokenData === null || tokenData.owner === null) return null;1288 const owner = {} as any;1289 for (const key of Object.keys(tokenData.owner)) {1290 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1291 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1292 : tokenData.owner[key];1293 }1294 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1295 return tokenData;1296 }12971298 /**1299 * Set permissions to change token properties1300 *1301 * @param signer keyring of signer1302 * @param collectionId ID of collection1303 * @param permissions permissions to change a property by the collection admin or token owner1304 * @example setTokenPropertyPermissions(1305 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1306 * )1307 * @returns true if extrinsic success otherwise false1308 */1309 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1310 const result = await this.helper.executeExtrinsic(1311 signer,1312 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1313 true,1314 );13151316 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1317 }13181319 /**1320 * Get token property permissions.1321 *1322 * @param collectionId ID of collection1323 * @param propertyKeys optionally filter the returned property permissions to only these keys1324 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1325 * @returns array of key-permission pairs1326 */1327 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1328 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1329 }13301331 /**1332 * Set token properties1333 *1334 * @param signer keyring of signer1335 * @param collectionId ID of collection1336 * @param tokenId ID of token1337 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1338 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1339 * @returns ```true``` if extrinsic success, otherwise ```false```1340 */1341 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1342 const result = await this.helper.executeExtrinsic(1343 signer,1344 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1345 true,1346 );13471348 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1349 }13501351 /**1352 * Get properties, metadata assigned to a token.1353 *1354 * @param collectionId ID of collection1355 * @param tokenId ID of token1356 * @param propertyKeys optionally filter the returned properties to only these keys1357 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1358 * @returns array of key-value pairs1359 */1360 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1361 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1362 }13631364 /**1365 * Delete the provided properties of a token1366 * @param signer keyring of signer1367 * @param collectionId ID of collection1368 * @param tokenId ID of token1369 * @param propertyKeys property keys to be deleted1370 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1371 * @returns ```true``` if extrinsic success, otherwise ```false```1372 */1373 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1374 const result = await this.helper.executeExtrinsic(1375 signer,1376 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1377 true,1378 );13791380 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1381 }13821383 /**1384 * Mint new collection1385 *1386 * @param signer keyring of signer1387 * @param collectionOptions basic collection options and properties1388 * @param mode NFT or RFT type of a collection1389 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1390 * @returns object of the created collection1391 */1392 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1393 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1394 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1395 for (const key of ['name', 'description', 'tokenPrefix']) {1396 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1397 }1398 const creationResult = await this.helper.executeExtrinsic(1399 signer,1400 'api.tx.unique.createCollectionEx', [collectionOptions],1401 true, // errorLabel,1402 );1403 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1404 }14051406 getCollectionObject(_collectionId: number): any {1407 return null;1408 }14091410 getTokenObject(_collectionId: number, _tokenId: number): any {1411 return null;1412 }1413}141414151416class NFTGroup extends NFTnRFT {1417 /**1418 * Get collection object1419 * @param collectionId ID of collection1420 * @example getCollectionObject(2);1421 * @returns instance of UniqueNFTCollection1422 */1423 getCollectionObject(collectionId: number): UniqueNFTCollection {1424 return new UniqueNFTCollection(collectionId, this.helper);1425 }14261427 /**1428 * Get token object1429 * @param collectionId ID of collection1430 * @param tokenId ID of token1431 * @example getTokenObject(10, 5);1432 * @returns instance of UniqueNFTToken1433 */1434 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1435 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1436 }14371438 /**1439 * Get token's owner1440 * @param collectionId ID of collection1441 * @param tokenId ID of token1442 * @param blockHashAt optionally query the data at the block with this hash1443 * @example getTokenOwner(10, 5);1444 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1445 */1446 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1447 let owner;1448 if (typeof blockHashAt === 'undefined') {1449 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1450 } else {1451 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1452 }1453 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1454 }14551456 /**1457 * Is token approved to transfer1458 * @param collectionId ID of collection1459 * @param tokenId ID of token1460 * @param toAccountObj address to be approved1461 * @returns ```true``` if extrinsic success, otherwise ```false```1462 */1463 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1464 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1465 }14661467 /**1468 * Changes the owner of the token.1469 *1470 * @param signer keyring of signer1471 * @param collectionId ID of collection1472 * @param tokenId ID of token1473 * @param addressObj address of a new owner1474 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1475 * @returns ```true``` if extrinsic success, otherwise ```false```1476 */1477 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1478 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1479 }14801481 /**1482 *1483 * Change ownership of a NFT on behalf of the owner.1484 *1485 * @param signer keyring of signer1486 * @param collectionId ID of collection1487 * @param tokenId ID of token1488 * @param fromAddressObj address on behalf of which the token will be sent1489 * @param toAddressObj new token owner1490 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1491 * @returns ```true``` if extrinsic success, otherwise ```false```1492 */1493 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1494 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1495 }14961497 /**1498 * Recursively find the address that owns the token1499 * @param collectionId ID of collection1500 * @param tokenId ID of token1501 * @param blockHashAt1502 * @example getTokenTopmostOwner(10, 5);1503 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1504 */1505 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1506 let owner;1507 if (typeof blockHashAt === 'undefined') {1508 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1509 } else {1510 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1511 }15121513 if (owner === null) return null;15141515 return owner.toHuman();1516 }15171518 /**1519 * Get tokens nested in the provided token1520 * @param collectionId ID of collection1521 * @param tokenId ID of token1522 * @param blockHashAt optionally query the data at the block with this hash1523 * @example getTokenChildren(10, 5);1524 * @returns tokens whose depth of nesting is <= 51525 */1526 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1527 let children;1528 if(typeof blockHashAt === 'undefined') {1529 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1530 } else {1531 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1532 }15331534 return children.toJSON().map((x: any) => {1535 return {collectionId: x.collection, tokenId: x.token};1536 });1537 }15381539 /**1540 * Nest one token into another1541 * @param signer keyring of signer1542 * @param tokenObj token to be nested1543 * @param rootTokenObj token to be parent1544 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1545 * @returns ```true``` if extrinsic success, otherwise ```false```1546 */1547 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1548 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1549 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1550 if(!result) {1551 throw Error('Unable to nest token!');1552 }1553 return result;1554 }15551556 /**1557 * Remove token from nested state1558 * @param signer keyring of signer1559 * @param tokenObj token to unnest1560 * @param rootTokenObj parent of a token1561 * @param toAddressObj address of a new token owner1562 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1563 * @returns ```true``` if extrinsic success, otherwise ```false```1564 */1565 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1566 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1567 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1568 if(!result) {1569 throw Error('Unable to unnest token!');1570 }1571 return result;1572 }15731574 /**1575 * Mint new collection1576 * @param signer keyring of signer1577 * @param collectionOptions Collection options1578 * @example1579 * mintCollection(aliceKeyring, {1580 * name: 'New',1581 * description: 'New collection',1582 * tokenPrefix: 'NEW',1583 * })1584 * @returns object of the created collection1585 */1586 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1587 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1588 }15891590 /**1591 * Mint new token1592 * @param signer keyring of signer1593 * @param data token data1594 * @returns created token object1595 */1596 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1597 const creationResult = await this.helper.executeExtrinsic(1598 signer,1599 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1600 nft: {1601 properties: data.properties,1602 },1603 }],1604 true,1605 );1606 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1607 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1608 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1609 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1610 }16111612 /**1613 * Mint multiple NFT tokens1614 * @param signer keyring of signer1615 * @param collectionId ID of collection1616 * @param tokens array of tokens with owner and properties1617 * @example1618 * mintMultipleTokens(aliceKeyring, 10, [{1619 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1620 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1621 * },{1622 * owner: {Ethereum: "0x9F0583DbB855d..."},1623 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1624 * }]);1625 * @returns ```true``` if extrinsic success, otherwise ```false```1626 */1627 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1628 const creationResult = await this.helper.executeExtrinsic(1629 signer,1630 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1631 true,1632 );1633 const collection = this.getCollectionObject(collectionId);1634 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1635 }16361637 /**1638 * Mint multiple NFT tokens with one owner1639 * @param signer keyring of signer1640 * @param collectionId ID of collection1641 * @param owner tokens owner1642 * @param tokens array of tokens with owner and properties1643 * @example1644 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1645 * properties: [{1646 * key: "gender",1647 * value: "female",1648 * },{1649 * key: "age",1650 * value: "33",1651 * }],1652 * }]);1653 * @returns array of newly created tokens1654 */1655 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1656 const rawTokens = [];1657 for (const token of tokens) {1658 const raw = {NFT: {properties: token.properties}};1659 rawTokens.push(raw);1660 }1661 const creationResult = await this.helper.executeExtrinsic(1662 signer,1663 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1664 true,1665 );1666 const collection = this.getCollectionObject(collectionId);1667 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1668 }16691670 /**1671 * Set, change, or remove approved address to transfer the ownership of the NFT.1672 *1673 * @param signer keyring of signer1674 * @param collectionId ID of collection1675 * @param tokenId ID of token1676 * @param toAddressObj address to approve1677 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1678 * @returns ```true``` if extrinsic success, otherwise ```false```1679 */1680 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1681 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1682 }1683}168416851686class RFTGroup extends NFTnRFT {1687 /**1688 * Get collection object1689 * @param collectionId ID of collection1690 * @example getCollectionObject(2);1691 * @returns instance of UniqueRFTCollection1692 */1693 getCollectionObject(collectionId: number): UniqueRFTCollection {1694 return new UniqueRFTCollection(collectionId, this.helper);1695 }16961697 /**1698 * Get token object1699 * @param collectionId ID of collection1700 * @param tokenId ID of token1701 * @example getTokenObject(10, 5);1702 * @returns instance of UniqueNFTToken1703 */1704 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1705 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1706 }17071708 /**1709 * Get top 10 token owners with the largest number of pieces1710 * @param collectionId ID of collection1711 * @param tokenId ID of token1712 * @example getTokenTop10Owners(10, 5);1713 * @returns array of top 10 owners1714 */1715 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1716 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1717 }17181719 /**1720 * Get number of pieces owned by address1721 * @param collectionId ID of collection1722 * @param tokenId ID of token1723 * @param addressObj address token owner1724 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1725 * @returns number of pieces ownerd by address1726 */1727 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1728 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1729 }17301731 /**1732 * Transfer pieces of token to another address1733 * @param signer keyring of signer1734 * @param collectionId ID of collection1735 * @param tokenId ID of token1736 * @param addressObj address of a new owner1737 * @param amount number of pieces to be transfered1738 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1739 * @returns ```true``` if extrinsic success, otherwise ```false```1740 */1741 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1742 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1743 }17441745 /**1746 * Change ownership of some pieces of RFT on behalf of the owner.1747 * @param signer keyring of signer1748 * @param collectionId ID of collection1749 * @param tokenId ID of token1750 * @param fromAddressObj address on behalf of which the token will be sent1751 * @param toAddressObj new token owner1752 * @param amount number of pieces to be transfered1753 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1754 * @returns ```true``` if extrinsic success, otherwise ```false```1755 */1756 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1757 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1758 }17591760 /**1761 * Mint new collection1762 * @param signer keyring of signer1763 * @param collectionOptions Collection options1764 * @example1765 * mintCollection(aliceKeyring, {1766 * name: 'New',1767 * description: 'New collection',1768 * tokenPrefix: 'NEW',1769 * })1770 * @returns object of the created collection1771 */1772 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1773 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1774 }17751776 /**1777 * Mint new token1778 * @param signer keyring of signer1779 * @param data token data1780 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1781 * @returns created token object1782 */1783 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1784 const creationResult = await this.helper.executeExtrinsic(1785 signer,1786 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1787 refungible: {1788 pieces: data.pieces,1789 properties: data.properties,1790 },1791 }],1792 true,1793 );1794 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1795 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1796 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1797 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1798 }17991800 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1801 throw Error('Not implemented');1802 const creationResult = await this.helper.executeExtrinsic(1803 signer,1804 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1805 true, // `Unable to mint RFT tokens for ${label}`,1806 );1807 const collection = this.getCollectionObject(collectionId);1808 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1809 }18101811 /**1812 * Mint multiple RFT tokens with one owner1813 * @param signer keyring of signer1814 * @param collectionId ID of collection1815 * @param owner tokens owner1816 * @param tokens array of tokens with properties and pieces1817 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1818 * @returns array of newly created RFT tokens1819 */1820 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1821 const rawTokens = [];1822 for (const token of tokens) {1823 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1824 rawTokens.push(raw);1825 }1826 const creationResult = await this.helper.executeExtrinsic(1827 signer,1828 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1829 true,1830 );1831 const collection = this.getCollectionObject(collectionId);1832 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1833 }18341835 /**1836 * Destroys a concrete instance of RFT.1837 * @param signer keyring of signer1838 * @param collectionId ID of collection1839 * @param tokenId ID of token1840 * @param amount number of pieces to be burnt1841 * @example burnToken(aliceKeyring, 10, 5);1842 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1843 */1844 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1845 return await super.burnToken(signer, collectionId, tokenId, amount);1846 }18471848 /**1849 * Destroys a concrete instance of RFT on behalf of the owner.1850 * @param signer keyring of signer1851 * @param collectionId ID of collection1852 * @param tokenId ID of token1853 * @param fromAddressObj address on behalf of which the token will be burnt1854 * @param amount number of pieces to be burnt1855 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1856 * @returns ```true``` if extrinsic success, otherwise ```false```1857 */1858 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1859 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1860 }18611862 /**1863 * Set, change, or remove approved address to transfer the ownership of the RFT.1864 *1865 * @param signer keyring of signer1866 * @param collectionId ID of collection1867 * @param tokenId ID of token1868 * @param toAddressObj address to approve1869 * @param amount number of pieces to be approved1870 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1871 * @returns true if the token success, otherwise false1872 */1873 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1874 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1875 }18761877 /**1878 * Get total number of pieces1879 * @param collectionId ID of collection1880 * @param tokenId ID of token1881 * @example getTokenTotalPieces(10, 5);1882 * @returns number of pieces1883 */1884 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1885 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1886 }18871888 /**1889 * Change number of token pieces. Signer must be the owner of all token pieces.1890 * @param signer keyring of signer1891 * @param collectionId ID of collection1892 * @param tokenId ID of token1893 * @param amount new number of pieces1894 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1895 * @returns true if the repartion was success, otherwise false1896 */1897 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1898 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1899 const repartitionResult = await this.helper.executeExtrinsic(1900 signer,1901 'api.tx.unique.repartition', [collectionId, tokenId, amount],1902 true,1903 );1904 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1905 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1906 }1907}190819091910class FTGroup extends CollectionGroup {1911 /**1912 * Get collection object1913 * @param collectionId ID of collection1914 * @example getCollectionObject(2);1915 * @returns instance of UniqueFTCollection1916 */1917 getCollectionObject(collectionId: number): UniqueFTCollection {1918 return new UniqueFTCollection(collectionId, this.helper);1919 }19201921 /**1922 * Mint new fungible collection1923 * @param signer keyring of signer1924 * @param collectionOptions Collection options1925 * @param decimalPoints number of token decimals1926 * @example1927 * mintCollection(aliceKeyring, {1928 * name: 'New',1929 * description: 'New collection',1930 * tokenPrefix: 'NEW',1931 * }, 18)1932 * @returns newly created fungible collection1933 */1934 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1935 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1936 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1937 collectionOptions.mode = {fungible: decimalPoints};1938 for (const key of ['name', 'description', 'tokenPrefix']) {1939 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1940 }1941 const creationResult = await this.helper.executeExtrinsic(1942 signer,1943 'api.tx.unique.createCollectionEx', [collectionOptions],1944 true,1945 );1946 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1947 }19481949 /**1950 * Mint tokens1951 * @param signer keyring of signer1952 * @param collectionId ID of collection1953 * @param owner address owner of new tokens1954 * @param amount amount of tokens to be meanted1955 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1956 * @returns ```true``` if extrinsic success, otherwise ```false```1957 */1958 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1959 const creationResult = await this.helper.executeExtrinsic(1960 signer,1961 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1962 fungible: {1963 value: amount,1964 },1965 }],1966 true, // `Unable to mint fungible tokens for ${label}`,1967 );1968 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1969 }19701971 /**1972 * Mint multiple Fungible tokens with one owner1973 * @param signer keyring of signer1974 * @param collectionId ID of collection1975 * @param owner tokens owner1976 * @param tokens array of tokens with properties and pieces1977 * @returns ```true``` if extrinsic success, otherwise ```false```1978 */1979 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1980 const rawTokens = [];1981 for (const token of tokens) {1982 const raw = {Fungible: {Value: token.value}};1983 rawTokens.push(raw);1984 }1985 const creationResult = await this.helper.executeExtrinsic(1986 signer,1987 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1988 true,1989 );1990 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1991 }19921993 /**1994 * Get the top 10 owners with the largest balance for the Fungible collection1995 * @param collectionId ID of collection1996 * @example getTop10Owners(10);1997 * @returns array of ```ICrossAccountId```1998 */1999 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2000 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2001 }20022003 /**2004 * Get account balance2005 * @param collectionId ID of collection2006 * @param addressObj address of owner2007 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2008 * @returns amount of fungible tokens owned by address2009 */2010 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2011 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2012 }20132014 /**2015 * Transfer tokens to address2016 * @param signer keyring of signer2017 * @param collectionId ID of collection2018 * @param toAddressObj address recipient2019 * @param amount amount of tokens to be sent2020 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2021 * @returns ```true``` if extrinsic success, otherwise ```false```2022 */2023 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2024 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2025 }20262027 /**2028 * Transfer some tokens on behalf of the owner.2029 * @param signer keyring of signer2030 * @param collectionId ID of collection2031 * @param fromAddressObj address on behalf of which tokens will be sent2032 * @param toAddressObj address where token to be sent2033 * @param amount number of tokens to be sent2034 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2035 * @returns ```true``` if extrinsic success, otherwise ```false```2036 */2037 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2038 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2039 }20402041 /**2042 * Destroy some amount of tokens2043 * @param signer keyring of signer2044 * @param collectionId ID of collection2045 * @param amount amount of tokens to be destroyed2046 * @example burnTokens(aliceKeyring, 10, 1000n);2047 * @returns ```true``` if extrinsic success, otherwise ```false```2048 */2049 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2050 return await super.burnToken(signer, collectionId, 0, amount);2051 }20522053 /**2054 * Burn some tokens on behalf of the owner.2055 * @param signer keyring of signer2056 * @param collectionId ID of collection2057 * @param fromAddressObj address on behalf of which tokens will be burnt2058 * @param amount amount of tokens to be burnt2059 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2060 * @returns ```true``` if extrinsic success, otherwise ```false```2061 */2062 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2063 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2064 }20652066 /**2067 * Get total collection supply2068 * @param collectionId2069 * @returns2070 */2071 async getTotalPieces(collectionId: number): Promise<bigint> {2072 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2073 }20742075 /**2076 * Set, change, or remove approved address to transfer tokens.2077 *2078 * @param signer keyring of signer2079 * @param collectionId ID of collection2080 * @param toAddressObj address to be approved2081 * @param amount amount of tokens to be approved2082 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2083 * @returns ```true``` if extrinsic success, otherwise ```false```2084 */2085 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2086 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2087 }20882089 /**2090 * Get amount of fungible tokens approved to transfer2091 * @param collectionId ID of collection2092 * @param fromAddressObj owner of tokens2093 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2094 * @returns number of tokens approved for the transfer2095 */2096 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2097 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2098 }2099}210021012102class ChainGroup extends HelperGroup<ChainHelperBase> {2103 /**2104 * Get system properties of a chain2105 * @example getChainProperties();2106 * @returns ss58Format, token decimals, and token symbol2107 */2108 getChainProperties(): IChainProperties {2109 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2110 return {2111 ss58Format: properties.ss58Format.toJSON(),2112 tokenDecimals: properties.tokenDecimals.toJSON(),2113 tokenSymbol: properties.tokenSymbol.toJSON(),2114 };2115 }21162117 /**2118 * Get chain header2119 * @example getLatestBlockNumber();2120 * @returns the number of the last block2121 */2122 async getLatestBlockNumber(): Promise<number> {2123 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2124 }21252126 /**2127 * Get block hash by block number2128 * @param blockNumber number of block2129 * @example getBlockHashByNumber(12345);2130 * @returns hash of a block2131 */2132 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2133 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2134 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2135 return blockHash;2136 }21372138 // TODO add docs2139 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2140 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2141 if (!blockHash) return null;2142 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2143 }21442145 /**2146 * Get account nonce2147 * @param address substrate address2148 * @example getNonce("5GrwvaEF5zXb26Fz...");2149 * @returns number, account's nonce2150 */2151 async getNonce(address: TSubstrateAccount): Promise<number> {2152 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2153 }2154}21552156class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2157 /**2158 * Get substrate address balance2159 * @param address substrate address2160 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2161 * @returns amount of tokens on address2162 */2163 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2164 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2165 }21662167 /**2168 * Transfer tokens to substrate address2169 * @param signer keyring of signer2170 * @param address substrate address of a recipient2171 * @param amount amount of tokens to be transfered2172 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2173 * @returns ```true``` if extrinsic success, otherwise ```false```2174 */2175 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2176 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);21772178 let transfer = {from: null, to: null, amount: 0n} as any;2179 result.result.events.forEach(({event: {data, method, section}}) => {2180 if ((section === 'balances') && (method === 'Transfer')) {2181 transfer = {2182 from: this.helper.address.normalizeSubstrate(data[0]),2183 to: this.helper.address.normalizeSubstrate(data[1]),2184 amount: BigInt(data[2]),2185 };2186 }2187 });2188 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2189 && this.helper.address.normalizeSubstrate(address) === transfer.to2190 && BigInt(amount) === transfer.amount;2191 return isSuccess;2192 }21932194 /**2195 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2196 * @param address substrate address2197 * @returns2198 */2199 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2200 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2201 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2202 }2203}22042205class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2206 /**2207 * Get ethereum address balance2208 * @param address ethereum address2209 * @example getEthereum("0x9F0583DbB855d...")2210 * @returns amount of tokens on address2211 */2212 async getEthereum(address: TEthereumAccount): Promise<bigint> {2213 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2214 }22152216 /**2217 * Transfer tokens to address2218 * @param signer keyring of signer2219 * @param address Ethereum address of a recipient2220 * @param amount amount of tokens to be transfered2221 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2222 * @returns ```true``` if extrinsic success, otherwise ```false```2223 */2224 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2225 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22262227 let transfer = {from: null, to: null, amount: 0n} as any;2228 result.result.events.forEach(({event: {data, method, section}}) => {2229 if ((section === 'balances') && (method === 'Transfer')) {2230 transfer = {2231 from: data[0].toString(),2232 to: data[1].toString(),2233 amount: BigInt(data[2]),2234 };2235 }2236 });2237 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2238 && address === transfer.to2239 && BigInt(amount) === transfer.amount;2240 return isSuccess;2241 }2242}22432244class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2245 subBalanceGroup: SubstrateBalanceGroup<T>;2246 ethBalanceGroup: EthereumBalanceGroup<T>;22472248 constructor(helper: T) {2249 super(helper);2250 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2251 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2252 }22532254 getCollectionCreationPrice(): bigint {2255 return 2n * this.getOneTokenNominal();2256 }2257 /**2258 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2259 * @example getOneTokenNominal()2260 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2261 */2262 getOneTokenNominal(): bigint {2263 const chainProperties = this.helper.chain.getChainProperties();2264 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2265 }22662267 /**2268 * Get substrate address balance2269 * @param address substrate address2270 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2271 * @returns amount of tokens on address2272 */2273 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2274 return this.subBalanceGroup.getSubstrate(address);2275 }22762277 /**2278 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2279 * @param address substrate address2280 * @returns2281 */2282 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2283 return this.subBalanceGroup.getSubstrateFull(address);2284 }22852286 /**2287 * Get ethereum address balance2288 * @param address ethereum address2289 * @example getEthereum("0x9F0583DbB855d...")2290 * @returns amount of tokens on address2291 */2292 getEthereum(address: TEthereumAccount): Promise<bigint> {2293 return this.ethBalanceGroup.getEthereum(address);2294 }22952296 /**2297 * Transfer tokens to substrate address2298 * @param signer keyring of signer2299 * @param address substrate address of a recipient2300 * @param amount amount of tokens to be transfered2301 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2302 * @returns ```true``` if extrinsic success, otherwise ```false```2303 */2304 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2305 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2306 }23072308 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2309 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23102311 let transfer = {from: null, to: null, amount: 0n} as any;2312 result.result.events.forEach(({event: {data, method, section}}) => {2313 if ((section === 'balances') && (method === 'Transfer')) {2314 transfer = {2315 from: this.helper.address.normalizeSubstrate(data[0]),2316 to: this.helper.address.normalizeSubstrate(data[1]),2317 amount: BigInt(data[2]),2318 };2319 }2320 });2321 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2322 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2323 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2324 return isSuccess;2325 }2326}23272328class AddressGroup extends HelperGroup<ChainHelperBase> {2329 /**2330 * Normalizes the address to the specified ss58 format, by default ```42```.2331 * @param address substrate address2332 * @param ss58Format format for address conversion, by default ```42```2333 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2334 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2335 */2336 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2337 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2338 }23392340 /**2341 * Get address in the connected chain format2342 * @param address substrate address2343 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2344 * @returns address in chain format2345 */2346 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2347 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2348 }23492350 /**2351 * Get substrate mirror of an ethereum address2352 * @param ethAddress ethereum address2353 * @param toChainFormat false for normalized account2354 * @example ethToSubstrate('0x9F0583DbB855d...')2355 * @returns substrate mirror of a provided ethereum address2356 */2357 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2358 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2359 }23602361 /**2362 * Get ethereum mirror of a substrate address2363 * @param subAddress substrate account2364 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2365 * @returns ethereum mirror of a provided substrate address2366 */2367 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2368 return CrossAccountId.translateSubToEth(subAddress);2369 }23702371 paraSiblingSovereignAccount(paraid: number) {2372 // We are getting a *sibling* parachain sovereign account,2373 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2374 const siblingPrefix = '0x7369626c';23752376 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2377 const suffix = '000000000000000000000000000000000000000000000000';23782379 return siblingPrefix + encodedParaId + suffix;2380 }2381}23822383class StakingGroup extends HelperGroup<UniqueHelper> {2384 /**2385 * Stake tokens for App Promotion2386 * @param signer keyring of signer2387 * @param amountToStake amount of tokens to stake2388 * @param label extra label for log2389 * @returns2390 */2391 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2392 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2393 const _stakeResult = await this.helper.executeExtrinsic(2394 signer, 'api.tx.appPromotion.stake',2395 [amountToStake], true,2396 );2397 // TODO extract info from stakeResult2398 return true;2399 }24002401 /**2402 * Unstake tokens for App Promotion2403 * @param signer keyring of signer2404 * @param amountToUnstake amount of tokens to unstake2405 * @param label extra label for log2406 * @returns block number where balances will be unlocked2407 */2408 async unstake(signer: TSigner, label?: string): Promise<number> {2409 if(typeof label === 'undefined') label = `${signer.address}`;2410 const _unstakeResult = await this.helper.executeExtrinsic(2411 signer, 'api.tx.appPromotion.unstake',2412 [], true,2413 );2414 // TODO extract block number fron events2415 return 1;2416 }24172418 /**2419 * Get total staked amount for address2420 * @param address substrate or ethereum address2421 * @returns total staked amount2422 */2423 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2424 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2425 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2426 }24272428 /**2429 * Get total staked per block2430 * @param address substrate or ethereum address2431 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2432 */2433 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2434 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2435 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2436 return {2437 block: block.toBigInt(),2438 amount: amount.toBigInt(),2439 };2440 });2441 }24422443 /**2444 * Get total pending unstake amount for address2445 * @param address substrate or ethereum address2446 * @returns total pending unstake amount2447 */2448 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2449 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2450 }24512452 /**2453 * Get pending unstake amount per block for address2454 * @param address substrate or ethereum address2455 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2456 */2457 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2458 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2459 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2460 return {2461 block: block.toBigInt(),2462 amount: amount.toBigInt(),2463 };2464 });2465 return result;2466 }2467}24682469class SchedulerGroup extends HelperGroup<UniqueHelper> {2470 constructor(helper: UniqueHelper) {2471 super(helper);2472 }24732474 cancelScheduled(signer: TSigner, scheduledId: string) {2475 return this.helper.executeExtrinsic(2476 signer,2477 'api.tx.scheduler.cancelNamed',2478 [scheduledId],2479 true,2480 );2481 }24822483 changePriority(signer: TSigner, scheduledId: string, priority: number) {2484 return this.helper.executeExtrinsic(2485 signer,2486 'api.tx.scheduler.changeNamedPriority',2487 [scheduledId, priority],2488 true,2489 );2490 }24912492 scheduleAt<T extends UniqueHelper>(2493 scheduledId: string,2494 executionBlockNumber: number,2495 options: ISchedulerOptions = {},2496 ) {2497 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2498 }24992500 scheduleAfter<T extends UniqueHelper>(2501 scheduledId: string,2502 blocksBeforeExecution: number,2503 options: ISchedulerOptions = {},2504 ) {2505 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2506 }25072508 schedule<T extends UniqueHelper>(2509 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2510 scheduledId: string,2511 blocksNum: number,2512 options: ISchedulerOptions = {},2513 ) {2514 // eslint-disable-next-line @typescript-eslint/naming-convention2515 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2516 return this.helper.clone(ScheduledHelperType, {2517 scheduleFn,2518 scheduledId,2519 blocksNum,2520 options,2521 }) as T;2522 }2523}25242525class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2526 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2527 await this.helper.executeExtrinsic(2528 signer,2529 'api.tx.foreignAssets.registerForeignAsset',2530 [ownerAddress, location, metadata],2531 true,2532 );2533 }25342535 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2536 await this.helper.executeExtrinsic(2537 signer,2538 'api.tx.foreignAssets.updateForeignAsset',2539 [foreignAssetId, location, metadata],2540 true,2541 );2542 }2543}25442545class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2546 palletName: string;25472548 constructor(helper: T, palletName: string) {2549 super(helper);25502551 this.palletName = palletName;2552 }25532554 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2555 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2556 }2557}25582559class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2560 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2561 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2562 }25632564 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2565 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2566 }25672568 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2569 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2570 }2571}25722573class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2574 async accounts(address: string, currencyId: any) {2575 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2576 return BigInt(free);2577 }2578}25792580class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2581 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2582 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2583 }25842585 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2586 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2587 }25882589 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2590 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2591 }25922593 async account(assetId: string | number, address: string) {2594 const accountAsset = (2595 await this.helper.callRpc('api.query.assets.account', [assetId, address])2596 ).toJSON()! as any;25972598 if (accountAsset !== null) {2599 return BigInt(accountAsset['balance']);2600 } else {2601 return null;2602 }2603 }2604}26052606class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2607 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2608 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2609 }2610}26112612class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2613 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2614 const apiPrefix = 'api.tx.assetManager.';26152616 const registerTx = this.helper.constructApiCall(2617 apiPrefix + 'registerForeignAsset',2618 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2619 );26202621 const setUnitsTx = this.helper.constructApiCall(2622 apiPrefix + 'setAssetUnitsPerSecond',2623 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2624 );26252626 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2627 const encodedProposal = batchCall?.method.toHex() || '';2628 return encodedProposal;2629 }26302631 async assetTypeId(location: any) {2632 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2633 }2634}26352636class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2637 async notePreimage(signer: TSigner, encodedProposal: string) {2638 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2639 }26402641 externalProposeMajority(proposalHash: string) {2642 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2643 }26442645 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2646 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2647 }26482649 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2650 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2651 }2652}26532654class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2655 collective: string;26562657 constructor(helper: MoonbeamHelper, collective: string) {2658 super(helper);26592660 this.collective = collective;2661 }26622663 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2664 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2665 }26662667 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2668 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2669 }26702671 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2672 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2673 }26742675 async proposalCount() {2676 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2677 }2678}26792680export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2681export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26822683export class UniqueHelper extends ChainHelperBase {2684 balance: BalanceGroup<UniqueHelper>;2685 collection: CollectionGroup;2686 nft: NFTGroup;2687 rft: RFTGroup;2688 ft: FTGroup;2689 staking: StakingGroup;2690 scheduler: SchedulerGroup;2691 foreignAssets: ForeignAssetsGroup;2692 xcm: XcmGroup<UniqueHelper>;2693 xTokens: XTokensGroup<UniqueHelper>;2694 tokens: TokensGroup<UniqueHelper>;26952696 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2697 super(logger, options.helperBase ?? UniqueHelper);26982699 this.balance = new BalanceGroup(this);2700 this.collection = new CollectionGroup(this);2701 this.nft = new NFTGroup(this);2702 this.rft = new RFTGroup(this);2703 this.ft = new FTGroup(this);2704 this.staking = new StakingGroup(this);2705 this.scheduler = new SchedulerGroup(this);2706 this.foreignAssets = new ForeignAssetsGroup(this);2707 this.xcm = new XcmGroup(this, 'polkadotXcm');2708 this.xTokens = new XTokensGroup(this);2709 this.tokens = new TokensGroup(this);2710 }27112712 getSudo<T extends UniqueHelper>() {2713 // eslint-disable-next-line @typescript-eslint/naming-convention2714 const SudoHelperType = SudoHelper(this.helperBase);2715 return this.clone(SudoHelperType) as T;2716 }2717}27182719export class XcmChainHelper extends ChainHelperBase {2720 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2721 const wsProvider = new WsProvider(wsEndpoint);2722 this.api = new ApiPromise({2723 provider: wsProvider,2724 });2725 await this.api.isReadyOrError;2726 this.network = await UniqueHelper.detectNetwork(this.api);2727 }2728}27292730export class RelayHelper extends XcmChainHelper {2731 xcm: XcmGroup<RelayHelper>;27322733 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2734 super(logger, options.helperBase ?? RelayHelper);27352736 this.xcm = new XcmGroup(this, 'xcmPallet');2737 }2738}27392740export class WestmintHelper extends XcmChainHelper {2741 balance: SubstrateBalanceGroup<WestmintHelper>;2742 xcm: XcmGroup<WestmintHelper>;2743 assets: AssetsGroup<WestmintHelper>;2744 xTokens: XTokensGroup<WestmintHelper>;27452746 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2747 super(logger, options.helperBase ?? WestmintHelper);27482749 this.balance = new SubstrateBalanceGroup(this);2750 this.xcm = new XcmGroup(this, 'polkadotXcm');2751 this.assets = new AssetsGroup(this);2752 this.xTokens = new XTokensGroup(this);2753 }2754}27552756export class MoonbeamHelper extends XcmChainHelper {2757 balance: EthereumBalanceGroup<MoonbeamHelper>;2758 assetManager: MoonbeamAssetManagerGroup;2759 assets: AssetsGroup<MoonbeamHelper>;2760 xTokens: XTokensGroup<MoonbeamHelper>;2761 democracy: MoonbeamDemocracyGroup;2762 collective: {2763 council: MoonbeamCollectiveGroup,2764 techCommittee: MoonbeamCollectiveGroup,2765 };27662767 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2768 super(logger, options.helperBase ?? MoonbeamHelper);27692770 this.balance = new EthereumBalanceGroup(this);2771 this.assetManager = new MoonbeamAssetManagerGroup(this);2772 this.assets = new AssetsGroup(this);2773 this.xTokens = new XTokensGroup(this);2774 this.democracy = new MoonbeamDemocracyGroup(this);2775 this.collective = {2776 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2777 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2778 };2779 }2780}27812782export class AcalaHelper extends XcmChainHelper {2783 balance: SubstrateBalanceGroup<AcalaHelper>;2784 assetRegistry: AcalaAssetRegistryGroup;2785 xTokens: XTokensGroup<AcalaHelper>;2786 tokens: TokensGroup<AcalaHelper>;27872788 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2789 super(logger, options.helperBase ?? AcalaHelper);27902791 this.balance = new SubstrateBalanceGroup(this);2792 this.assetRegistry = new AcalaAssetRegistryGroup(this);2793 this.xTokens = new XTokensGroup(this);2794 this.tokens = new TokensGroup(this);2795 }27962797 getSudo<T extends AcalaHelper>() {2798 // eslint-disable-next-line @typescript-eslint/naming-convention2799 const SudoHelperType = SudoHelper(this.helperBase);2800 return this.clone(SudoHelperType) as T;2801 }2802}28032804// eslint-disable-next-line @typescript-eslint/naming-convention2805function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2806 return class extends Base {2807 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2808 scheduledId: string;2809 blocksNum: number;2810 options: ISchedulerOptions;28112812 constructor(...args: any[]) {2813 const logger = args[0] as ILogger;2814 const options = args[1] as {2815 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2816 scheduledId: string,2817 blocksNum: number,2818 options: ISchedulerOptions2819 };28202821 super(logger);28222823 this.scheduleFn = options.scheduleFn;2824 this.scheduledId = options.scheduledId;2825 this.blocksNum = options.blocksNum;2826 this.options = options.options;2827 }28282829 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2830 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2831 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;28322833 return super.executeExtrinsic(2834 sender,2835 extrinsic,2836 [2837 this.scheduledId,2838 this.blocksNum,2839 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2840 this.options.priority ?? null,2841 {Value: scheduledTx},2842 ],2843 expectSuccess,2844 );2845 }2846 };2847}28482849// eslint-disable-next-line @typescript-eslint/naming-convention2850function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2851 return class extends Base {2852 constructor(...args: any[]) {2853 super(...args);2854 }28552856 executeExtrinsic (2857 sender: IKeyringPair,2858 extrinsic: string,2859 params: any[],2860 expectSuccess?: boolean,2861 ): Promise<ITransactionResult> {2862 const call = this.constructApiCall(extrinsic, params);2863 return super.executeExtrinsic(2864 sender,2865 'api.tx.sudo.sudo',2866 [call],2867 expectSuccess,2868 );2869 }2870 };2871}28722873export class UniqueBaseCollection {2874 helper: UniqueHelper;2875 collectionId: number;28762877 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2878 this.collectionId = collectionId;2879 this.helper = uniqueHelper;2880 }28812882 async getData() {2883 return await this.helper.collection.getData(this.collectionId);2884 }28852886 async getLastTokenId() {2887 return await this.helper.collection.getLastTokenId(this.collectionId);2888 }28892890 async doesTokenExist(tokenId: number) {2891 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2892 }28932894 async getAdmins() {2895 return await this.helper.collection.getAdmins(this.collectionId);2896 }28972898 async getAllowList() {2899 return await this.helper.collection.getAllowList(this.collectionId);2900 }29012902 async getEffectiveLimits() {2903 return await this.helper.collection.getEffectiveLimits(this.collectionId);2904 }29052906 async getProperties(propertyKeys?: string[] | null) {2907 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2908 }29092910 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2911 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2912 }29132914 async getOptions() {2915 return await this.helper.collection.getCollectionOptions(this.collectionId);2916 }29172918 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2919 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2920 }29212922 async confirmSponsorship(signer: TSigner) {2923 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2924 }29252926 async removeSponsor(signer: TSigner) {2927 return await this.helper.collection.removeSponsor(signer, this.collectionId);2928 }29292930 async setLimits(signer: TSigner, limits: ICollectionLimits) {2931 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2932 }29332934 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2935 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2936 }29372938 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2939 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2940 }29412942 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2943 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2944 }29452946 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2947 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2948 }29492950 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2951 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2952 }29532954 async setProperties(signer: TSigner, properties: IProperty[]) {2955 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2956 }29572958 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2959 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2960 }29612962 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2963 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2964 }29652966 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2967 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2968 }29692970 async disableNesting(signer: TSigner) {2971 return await this.helper.collection.disableNesting(signer, this.collectionId);2972 }29732974 async burn(signer: TSigner) {2975 return await this.helper.collection.burn(signer, this.collectionId);2976 }29772978 scheduleAt<T extends UniqueHelper>(2979 scheduledId: string,2980 executionBlockNumber: number,2981 options: ISchedulerOptions = {},2982 ) {2983 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2984 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2985 }29862987 scheduleAfter<T extends UniqueHelper>(2988 scheduledId: string,2989 blocksBeforeExecution: number,2990 options: ISchedulerOptions = {},2991 ) {2992 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2993 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2994 }29952996 getSudo<T extends UniqueHelper>() {2997 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2998 }2999}300030013002export class UniqueNFTCollection extends UniqueBaseCollection {3003 getTokenObject(tokenId: number) {3004 return new UniqueNFToken(tokenId, this);3005 }30063007 async getTokensByAddress(addressObj: ICrossAccountId) {3008 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3009 }30103011 async getToken(tokenId: number, blockHashAt?: string) {3012 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3013 }30143015 async getTokenOwner(tokenId: number, blockHashAt?: string) {3016 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3017 }30183019 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3020 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3021 }30223023 async getTokenChildren(tokenId: number, blockHashAt?: string) {3024 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3025 }30263027 async getPropertyPermissions(propertyKeys: string[] | null = null) {3028 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3029 }30303031 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3032 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3033 }30343035 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3036 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3037 }30383039 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3040 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3041 }30423043 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3044 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3045 }30463047 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3048 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3049 }30503051 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3052 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3053 }30543055 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3056 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3057 }30583059 async burnToken(signer: TSigner, tokenId: number) {3060 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3061 }30623063 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3064 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3065 }30663067 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3068 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3069 }30703071 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3072 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3073 }30743075 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3076 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3077 }30783079 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3080 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3081 }30823083 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3084 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3085 }30863087 scheduleAt<T extends UniqueHelper>(3088 scheduledId: string,3089 executionBlockNumber: number,3090 options: ISchedulerOptions = {},3091 ) {3092 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3093 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3094 }30953096 scheduleAfter<T extends UniqueHelper>(3097 scheduledId: string,3098 blocksBeforeExecution: number,3099 options: ISchedulerOptions = {},3100 ) {3101 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3102 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3103 }31043105 getSudo<T extends UniqueHelper>() {3106 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3107 }3108}310931103111export class UniqueRFTCollection extends UniqueBaseCollection {3112 getTokenObject(tokenId: number) {3113 return new UniqueRFToken(tokenId, this);3114 }31153116 async getToken(tokenId: number, blockHashAt?: string) {3117 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3118 }31193120 async getTokensByAddress(addressObj: ICrossAccountId) {3121 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3122 }31233124 async getTop10TokenOwners(tokenId: number) {3125 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3126 }31273128 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3129 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3130 }31313132 async getTokenTotalPieces(tokenId: number) {3133 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3134 }31353136 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3137 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3138 }31393140 async getPropertyPermissions(propertyKeys: string[] | null = null) {3141 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3142 }31433144 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3145 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3146 }31473148 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3149 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3150 }31513152 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3153 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3154 }31553156 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3157 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3158 }31593160 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3161 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3162 }31633164 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3165 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3166 }31673168 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3169 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3170 }31713172 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3173 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3174 }31753176 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3177 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3178 }31793180 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3181 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3182 }31833184 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3185 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3186 }31873188 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3189 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3190 }31913192 scheduleAt<T extends UniqueHelper>(3193 scheduledId: string,3194 executionBlockNumber: number,3195 options: ISchedulerOptions = {},3196 ) {3197 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3198 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3199 }32003201 scheduleAfter<T extends UniqueHelper>(3202 scheduledId: string,3203 blocksBeforeExecution: number,3204 options: ISchedulerOptions = {},3205 ) {3206 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3207 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3208 }32093210 getSudo<T extends UniqueHelper>() {3211 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3212 }3213}321432153216export class UniqueFTCollection extends UniqueBaseCollection {3217 async getBalance(addressObj: ICrossAccountId) {3218 return await this.helper.ft.getBalance(this.collectionId, addressObj);3219 }32203221 async getTotalPieces() {3222 return await this.helper.ft.getTotalPieces(this.collectionId);3223 }32243225 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3226 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3227 }32283229 async getTop10Owners() {3230 return await this.helper.ft.getTop10Owners(this.collectionId);3231 }32323233 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3234 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3235 }32363237 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3238 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3239 }32403241 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3242 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3243 }32443245 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3246 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3247 }32483249 async burnTokens(signer: TSigner, amount=1n) {3250 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3251 }32523253 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3254 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3255 }32563257 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3258 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3259 }32603261 scheduleAt<T extends UniqueHelper>(3262 scheduledId: string,3263 executionBlockNumber: number,3264 options: ISchedulerOptions = {},3265 ) {3266 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3267 return new UniqueFTCollection(this.collectionId, scheduledHelper);3268 }32693270 scheduleAfter<T extends UniqueHelper>(3271 scheduledId: string,3272 blocksBeforeExecution: number,3273 options: ISchedulerOptions = {},3274 ) {3275 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3276 return new UniqueFTCollection(this.collectionId, scheduledHelper);3277 }32783279 getSudo<T extends UniqueHelper>() {3280 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3281 }3282}328332843285export class UniqueBaseToken {3286 collection: UniqueNFTCollection | UniqueRFTCollection;3287 collectionId: number;3288 tokenId: number;32893290 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3291 this.collection = collection;3292 this.collectionId = collection.collectionId;3293 this.tokenId = tokenId;3294 }32953296 async getNextSponsored(addressObj: ICrossAccountId) {3297 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3298 }32993300 async getProperties(propertyKeys?: string[] | null) {3301 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3302 }33033304 async setProperties(signer: TSigner, properties: IProperty[]) {3305 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3306 }33073308 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3309 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3310 }33113312 async doesExist() {3313 return await this.collection.doesTokenExist(this.tokenId);3314 }33153316 nestingAccount() {3317 return this.collection.helper.util.getTokenAccount(this);3318 }33193320 scheduleAt<T extends UniqueHelper>(3321 scheduledId: string,3322 executionBlockNumber: number,3323 options: ISchedulerOptions = {},3324 ) {3325 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3326 return new UniqueBaseToken(this.tokenId, scheduledCollection);3327 }33283329 scheduleAfter<T extends UniqueHelper>(3330 scheduledId: string,3331 blocksBeforeExecution: number,3332 options: ISchedulerOptions = {},3333 ) {3334 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3335 return new UniqueBaseToken(this.tokenId, scheduledCollection);3336 }33373338 getSudo<T extends UniqueHelper>() {3339 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3340 }3341}334233433344export class UniqueNFToken extends UniqueBaseToken {3345 collection: UniqueNFTCollection;33463347 constructor(tokenId: number, collection: UniqueNFTCollection) {3348 super(tokenId, collection);3349 this.collection = collection;3350 }33513352 async getData(blockHashAt?: string) {3353 return await this.collection.getToken(this.tokenId, blockHashAt);3354 }33553356 async getOwner(blockHashAt?: string) {3357 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3358 }33593360 async getTopmostOwner(blockHashAt?: string) {3361 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3362 }33633364 async getChildren(blockHashAt?: string) {3365 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3366 }33673368 async nest(signer: TSigner, toTokenObj: IToken) {3369 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3370 }33713372 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3373 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3374 }33753376 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3377 return await this.collection.transferToken(signer, this.tokenId, addressObj);3378 }33793380 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3381 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3382 }33833384 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3385 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3386 }33873388 async isApproved(toAddressObj: ICrossAccountId) {3389 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3390 }33913392 async burn(signer: TSigner) {3393 return await this.collection.burnToken(signer, this.tokenId);3394 }33953396 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3397 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3398 }33993400 scheduleAt<T extends UniqueHelper>(3401 scheduledId: string,3402 executionBlockNumber: number,3403 options: ISchedulerOptions = {},3404 ) {3405 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3406 return new UniqueNFToken(this.tokenId, scheduledCollection);3407 }34083409 scheduleAfter<T extends UniqueHelper>(3410 scheduledId: string,3411 blocksBeforeExecution: number,3412 options: ISchedulerOptions = {},3413 ) {3414 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3415 return new UniqueNFToken(this.tokenId, scheduledCollection);3416 }34173418 getSudo<T extends UniqueHelper>() {3419 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3420 }3421}34223423export class UniqueRFToken extends UniqueBaseToken {3424 collection: UniqueRFTCollection;34253426 constructor(tokenId: number, collection: UniqueRFTCollection) {3427 super(tokenId, collection);3428 this.collection = collection;3429 }34303431 async getData(blockHashAt?: string) {3432 return await this.collection.getToken(this.tokenId, blockHashAt);3433 }34343435 async getTop10Owners() {3436 return await this.collection.getTop10TokenOwners(this.tokenId);3437 }34383439 async getBalance(addressObj: ICrossAccountId) {3440 return await this.collection.getTokenBalance(this.tokenId, addressObj);3441 }34423443 async getTotalPieces() {3444 return await this.collection.getTokenTotalPieces(this.tokenId);3445 }34463447 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3448 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3449 }34503451 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3452 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3453 }34543455 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3456 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3457 }34583459 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3460 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3461 }34623463 async repartition(signer: TSigner, amount: bigint) {3464 return await this.collection.repartitionToken(signer, this.tokenId, amount);3465 }34663467 async burn(signer: TSigner, amount=1n) {3468 return await this.collection.burnToken(signer, this.tokenId, amount);3469 }34703471 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3472 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3473 }34743475 scheduleAt<T extends UniqueHelper>(3476 scheduledId: string,3477 executionBlockNumber: number,3478 options: ISchedulerOptions = {},3479 ) {3480 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3481 return new UniqueRFToken(this.tokenId, scheduledCollection);3482 }34833484 scheduleAfter<T extends UniqueHelper>(3485 scheduledId: string,3486 blocksBeforeExecution: number,3487 options: ISchedulerOptions = {},3488 ) {3489 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3490 return new UniqueRFToken(this.tokenId, scheduledCollection);3491 }34923493 getSudo<T extends UniqueHelper>() {3494 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3495 }3496}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';4647export class CrossAccountId implements ICrossAccountId {48 Substrate?: TSubstrateAccount;49 Ethereum?: TEthereumAccount;5051 constructor(account: ICrossAccountId) {52 if (account.Substrate) this.Substrate = account.Substrate;53 if (account.Ethereum) this.Ethereum = account.Ethereum;54 }5556 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {57 switch (domain) {58 case 'Substrate': return new CrossAccountId({Substrate: account.address});59 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();60 }61 }6263 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {64 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});65 }6667 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {68 return encodeAddress(decodeAddress(address), ss58Format);69 }7071 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {72 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});73 }7475 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {76 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);77 return this;78 }7980 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {81 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));82 }8384 toEthereum(): CrossAccountId {85 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});86 return this;87 }8889 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {90 return evmToAddress(address, ss58Format);91 }9293 toSubstrate(ss58Format?: number): CrossAccountId {94 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});95 return this;96 }9798 toLowerCase(): CrossAccountId {99 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();100 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();101 return this;102 }103}104105const nesting = {106 toChecksumAddress(address: string): string {107 if (typeof address === 'undefined') return '';108109 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);110111 address = address.toLowerCase().replace(/^0x/i,'');112 const addressHash = keccakAsHex(address).replace(/^0x/i,'');113 const checksumAddress = ['0x'];114115 for (let i = 0; i < address.length; i++) {116 // If ith character is 8 to f then make it uppercase117 if (parseInt(addressHash[i], 16) > 7) {118 checksumAddress.push(address[i].toUpperCase());119 } else {120 checksumAddress.push(address[i]);121 }122 }123 return checksumAddress.join('');124 },125 tokenIdToAddress(collectionId: number, tokenId: number) {126 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);127 },128};129130class UniqueUtil {131 static transactionStatus = {132 NOT_READY: 'NotReady',133 FAIL: 'Fail',134 SUCCESS: 'Success',135 };136137 static chainLogType = {138 EXTRINSIC: 'extrinsic',139 RPC: 'rpc',140 };141142 static getTokenAccount(token: IToken): CrossAccountId {143 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});144 }145146 static getTokenAddress(token: IToken): string {147 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);148 }149150 static getDefaultLogger(): ILogger {151 return {152 log(msg: any, level = 'INFO') {153 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));154 },155 level: {156 ERROR: 'ERROR',157 WARNING: 'WARNING',158 INFO: 'INFO',159 },160 };161 }162163 static vec2str(arr: string[] | number[]) {164 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');165 }166167 static str2vec(string: string) {168 if (typeof string !== 'string') return string;169 return Array.from(string).map(x => x.charCodeAt(0));170 }171172 static fromSeed(seed: string, ss58Format = 42) {173 const keyring = new Keyring({type: 'sr25519', ss58Format});174 return keyring.addFromUri(seed);175 }176177 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {178 if (creationResult.status !== this.transactionStatus.SUCCESS) {179 throw Error('Unable to create collection!');180 }181182 let collectionId = null;183 creationResult.result.events.forEach(({event: {data, method, section}}) => {184 if ((section === 'common') && (method === 'CollectionCreated')) {185 collectionId = parseInt(data[0].toString(), 10);186 }187 });188189 if (collectionId === null) {190 throw Error('No CollectionCreated event was found!');191 }192193 return collectionId;194 }195196 static extractTokensFromCreationResult(creationResult: ITransactionResult): {197 success: boolean,198 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],199 } {200 if (creationResult.status !== this.transactionStatus.SUCCESS) {201 throw Error('Unable to create tokens!');202 }203 let success = false;204 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];205 creationResult.result.events.forEach(({event: {data, method, section}}) => {206 if (method === 'ExtrinsicSuccess') {207 success = true;208 } else if ((section === 'common') && (method === 'ItemCreated')) {209 tokens.push({210 collectionId: parseInt(data[0].toString(), 10),211 tokenId: parseInt(data[1].toString(), 10),212 owner: data[2].toHuman(),213 amount: data[3].toBigInt(),214 });215 }216 });217 return {success, tokens};218 }219220 static extractTokensFromBurnResult(burnResult: ITransactionResult): {221 success: boolean,222 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],223 } {224 if (burnResult.status !== this.transactionStatus.SUCCESS) {225 throw Error('Unable to burn tokens!');226 }227 let success = false;228 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];229 burnResult.result.events.forEach(({event: {data, method, section}}) => {230 if (method === 'ExtrinsicSuccess') {231 success = true;232 } else if ((section === 'common') && (method === 'ItemDestroyed')) {233 tokens.push({234 collectionId: parseInt(data[0].toString(), 10),235 tokenId: parseInt(data[1].toString(), 10),236 owner: data[2].toHuman(),237 amount: data[3].toBigInt(),238 });239 }240 });241 return {success, tokens};242 }243244 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {245 let eventId = null;246 events.forEach(({event: {data, method, section}}) => {247 if ((section === expectedSection) && (method === expectedMethod)) {248 eventId = parseInt(data[0].toString(), 10);249 }250 });251252 if (eventId === null) {253 throw Error(`No ${expectedMethod} event was found!`);254 }255 return eventId === collectionId;256 }257258 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {259 const normalizeAddress = (address: string | ICrossAccountId) => {260 if(typeof address === 'string') return address;261 const obj = {} as any;262 Object.keys(address).forEach(k => {263 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];264 });265 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);266 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();267 return address;268 };269 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;270 events.forEach(({event: {data, method, section}}) => {271 if ((section === 'common') && (method === 'Transfer')) {272 const hData = (data as any).toJSON();273 transfer = {274 collectionId: hData[0],275 tokenId: hData[1],276 from: normalizeAddress(hData[2]),277 to: normalizeAddress(hData[3]),278 amount: BigInt(hData[4]),279 };280 }281 });282 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;283 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);284 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);285 isSuccess = isSuccess && amount === transfer.amount;286 return isSuccess;287 }288289 static bigIntToDecimals(number: bigint, decimals = 18) {290 const numberStr = number.toString();291 const dotPos = numberStr.length - decimals;292293 if (dotPos <= 0) {294 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;295 } else {296 const intPart = numberStr.substring(0, dotPos);297 const fractPart = numberStr.substring(dotPos);298 return intPart + '.' + fractPart;299 }300 }301}302303class UniqueEventHelper {304 private static extractIndex(index: any): [number, number] | string {305 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];306 return index.toJSON();307 }308309 private static extractSub(data: any, subTypes: any): {[key: string]: any} {310 let obj: any = {};311 let index = 0;312313 if (data.entries) {314 for(const [key, value] of data.entries()) {315 obj[key] = this.extractData(value, subTypes[index]);316 index++;317 }318 } else obj = data.toJSON();319320 return obj;321 }322323 private static extractData(data: any, type: any): any {324 if(!type) return data.toHuman();325 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();326 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();327 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);328 return data.toHuman();329 }330331 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {332 const parsedEvents: IEvent[] = [];333334 events.forEach((record) => {335 const {event, phase} = record;336 const types = event.typeDef;337338 const eventData: IEvent = {339 section: event.section.toString(),340 method: event.method.toString(),341 index: this.extractIndex(event.index),342 data: [],343 phase: phase.toJSON(),344 };345346 event.data.forEach((val: any, index: number) => {347 eventData.data.push(this.extractData(val, types[index]));348 });349350 parsedEvents.push(eventData);351 });352353 return parsedEvents;354 }355}356357export class ChainHelperBase {358 helperBase: any;359360 transactionStatus = UniqueUtil.transactionStatus;361 chainLogType = UniqueUtil.chainLogType;362 util: typeof UniqueUtil;363 eventHelper: typeof UniqueEventHelper;364 logger: ILogger;365 api: ApiPromise | null;366 forcedNetwork: TNetworks | null;367 network: TNetworks | null;368 chainLog: IUniqueHelperLog[];369 children: ChainHelperBase[];370 address: AddressGroup;371 chain: ChainGroup;372373 constructor(logger?: ILogger, helperBase?: any) {374 this.helperBase = helperBase;375376 this.util = UniqueUtil;377 this.eventHelper = UniqueEventHelper;378 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();379 this.logger = logger;380 this.api = null;381 this.forcedNetwork = null;382 this.network = null;383 this.chainLog = [];384 this.children = [];385 this.address = new AddressGroup(this);386 this.chain = new ChainGroup(this);387 }388389 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {390 Object.setPrototypeOf(helperCls.prototype, this);391 const newHelper = new helperCls(this.logger, options);392393 newHelper.api = this.api;394 newHelper.network = this.network;395 newHelper.forceNetwork = this.forceNetwork;396397 this.children.push(newHelper);398399 return newHelper;400 }401402 getApi(): ApiPromise {403 if(this.api === null) throw Error('API not initialized');404 return this.api;405 }406407 clearChainLog(): void {408 this.chainLog = [];409 }410411 forceNetwork(value: TNetworks): void {412 this.forcedNetwork = value;413 }414415 async connect(wsEndpoint: string, listeners?: IApiListeners) {416 if (this.api !== null) throw Error('Already connected');417 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);418 this.api = api;419 this.network = network;420 }421422 async disconnect() {423 for (const child of this.children) {424 child.clearApi();425 }426427 if (this.api === null) return;428 await this.api.disconnect();429 this.clearApi();430 }431432 clearApi() {433 this.api = null;434 this.network = null;435 }436437 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {438 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;439 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];440441 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;442443 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;444 return 'opal';445 }446447 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {448 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});449 await api.isReady;450451 const network = await this.detectNetwork(api);452453 await api.disconnect();454455 return network;456 }457458 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{459 api: ApiPromise;460 network: TNetworks;461 }> {462 if(typeof network === 'undefined' || network === null) network = 'opal';463 const supportedRPC = {464 opal: {465 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,466 },467 quartz: {468 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,469 },470 unique: {471 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,472 },473 rococo: {},474 westend: {},475 moonbeam: {},476 moonriver: {},477 acala: {},478 karura: {},479 westmint: {},480 };481 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);482 const rpc = supportedRPC[network];483484 // TODO: investigate how to replace rpc in runtime485 // api._rpcCore.addUserInterfaces(rpc);486487 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});488489 await api.isReadyOrError;490491 if (typeof listeners === 'undefined') listeners = {};492 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {493 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;494 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);495 }496497 return {api, network};498 }499500 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {501 const {events, status} = data;502 if (status.isReady) {503 return this.transactionStatus.NOT_READY;504 }505 if (status.isBroadcast) {506 return this.transactionStatus.NOT_READY;507 }508 if (status.isInBlock || status.isFinalized) {509 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');510 if (errors.length > 0) {511 return this.transactionStatus.FAIL;512 }513 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {514 return this.transactionStatus.SUCCESS;515 }516 }517518 return this.transactionStatus.FAIL;519 }520521 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {522 const sign = (callback: any) => {523 if(options !== null) return transaction.signAndSend(sender, options, callback);524 return transaction.signAndSend(sender, callback);525 };526 // eslint-disable-next-line no-async-promise-executor527 return new Promise(async (resolve, reject) => {528 try {529 const unsub = await sign((result: any) => {530 const status = this.getTransactionStatus(result);531532 if (status === this.transactionStatus.SUCCESS) {533 this.logger.log(`${label} successful`);534 unsub();535 resolve({result, status});536 } else if (status === this.transactionStatus.FAIL) {537 let moduleError = null;538539 if (result.hasOwnProperty('dispatchError')) {540 const dispatchError = result['dispatchError'];541542 if (dispatchError) {543 if (dispatchError.isModule) {544 const modErr = dispatchError.asModule;545 const errorMeta = dispatchError.registry.findMetaError(modErr);546547 moduleError = `${errorMeta.section}.${errorMeta.name}`;548 } else {549 moduleError = dispatchError.toHuman();550 }551 } else {552 this.logger.log(result, this.logger.level.ERROR);553 }554 }555556 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);557 unsub();558 reject({status, moduleError, result});559 }560 });561 } catch (e) {562 this.logger.log(e, this.logger.level.ERROR);563 reject(e);564 }565 });566 }567568 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {569 const api = this.getApi();570 const signingInfo = await api.derive.tx.signingInfo(signer.address);571572 // We need to sign the tx because573 // unsigned transactions does not have an inclusion fee574 tx.sign(signer, {575 blockHash: api.genesisHash,576 genesisHash: api.genesisHash,577 runtimeVersion: api.runtimeVersion,578 nonce: signingInfo.nonce,579 });580581 if (len === null) {582 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;583 } else {584 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;585 }586 }587588 constructApiCall(apiCall: string, params: any[]) {589 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);590 let call = this.getApi() as any;591 for(const part of apiCall.slice(4).split('.')) {592 call = call[part];593 }594 return call(...params);595 }596597 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {598 if(this.api === null) throw Error('API not initialized');599 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);600601 const startTime = (new Date()).getTime();602 let result: ITransactionResult;603 let events: IEvent[] = [];604 try {605 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;606 events = this.eventHelper.extractEvents(result.result.events);607 }608 catch(e) {609 if(!(e as object).hasOwnProperty('status')) throw e;610 result = e as ITransactionResult;611 }612613 const endTime = (new Date()).getTime();614615 const log = {616 executedAt: endTime,617 executionTime: endTime - startTime,618 type: this.chainLogType.EXTRINSIC,619 status: result.status,620 call: extrinsic,621 signer: this.getSignerAddress(sender),622 params,623 } as IUniqueHelperLog;624625 if(result.status !== this.transactionStatus.SUCCESS) {626 if (result.moduleError) log.moduleError = result.moduleError;627 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;628 }629 if(events.length > 0) log.events = events;630631 this.chainLog.push(log);632633 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {634 if (result.moduleError) throw Error(`${result.moduleError}`);635 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));636 }637 return result;638 }639640 async callRpc(rpc: string, params?: any[]) {641 if(typeof params === 'undefined') params = [];642 if(this.api === null) throw Error('API not initialized');643 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);644645 const startTime = (new Date()).getTime();646 let result;647 let error = null;648 const log = {649 type: this.chainLogType.RPC,650 call: rpc,651 params,652 } as IUniqueHelperLog;653654 try {655 result = await this.constructApiCall(rpc, params);656 }657 catch(e) {658 error = e;659 }660661 const endTime = (new Date()).getTime();662663 log.executedAt = endTime;664 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';665 log.executionTime = endTime - startTime;666667 this.chainLog.push(log);668669 if(error !== null) throw error;670671 return result;672 }673674 getSignerAddress(signer: IKeyringPair | string): string {675 if(typeof signer === 'string') return signer;676 return signer.address;677 }678679 fetchAllPalletNames(): string[] {680 if(this.api === null) throw Error('API not initialized');681 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());682 }683684 fetchMissingPalletNames(requiredPallets: string[]): string[] {685 const palletNames = this.fetchAllPalletNames();686 return requiredPallets.filter(p => !palletNames.includes(p));687 }688}689690691class HelperGroup<T extends ChainHelperBase> {692 helper: T;693694 constructor(uniqueHelper: T) {695 this.helper = uniqueHelper;696 }697}698699700class CollectionGroup extends HelperGroup<UniqueHelper> {701 /**702 * Get number of blocks when sponsored transaction is available.703 *704 * @param collectionId ID of collection705 * @param tokenId ID of token706 * @param addressObj address for which the sponsorship is checked707 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});708 * @returns number of blocks or null if sponsorship hasn't been set709 */710 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {711 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();712 }713714 /**715 * Get the number of created collections.716 *717 * @returns number of created collections718 */719 async getTotalCount(): Promise<number> {720 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();721 }722723 /**724 * Get information about the collection with additional data,725 * including the number of tokens it contains, its administrators,726 * the normalized address of the collection's owner, and decoded name and description.727 *728 * @param collectionId ID of collection729 * @example await getData(2)730 * @returns collection information object731 */732 async getData(collectionId: number): Promise<{733 id: number;734 name: string;735 description: string;736 tokensCount: number;737 admins: CrossAccountId[];738 normalizedOwner: TSubstrateAccount;739 raw: any740 } | null> {741 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);742 const humanCollection = collection.toHuman(), collectionData = {743 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],744 raw: humanCollection,745 } as any, jsonCollection = collection.toJSON();746 if (humanCollection === null) return null;747 collectionData.raw.limits = jsonCollection.limits;748 collectionData.raw.permissions = jsonCollection.permissions;749 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);750 for (const key of ['name', 'description']) {751 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);752 }753754 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))755 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)756 : 0;757 collectionData.admins = await this.getAdmins(collectionId);758759 return collectionData;760 }761762 /**763 * Get the addresses of the collection's administrators, optionally normalized.764 *765 * @param collectionId ID of collection766 * @param normalize whether to normalize the addresses to the default ss58 format767 * @example await getAdmins(1)768 * @returns array of administrators769 */770 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {771 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();772773 return normalize774 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())775 : admins;776 }777778 /**779 * Get the addresses added to the collection allow-list, optionally normalized.780 * @param collectionId ID of collection781 * @param normalize whether to normalize the addresses to the default ss58 format782 * @example await getAllowList(1)783 * @returns array of allow-listed addresses784 */785 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {786 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();787 return normalize788 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())789 : allowListed;790 }791792 /**793 * Get the effective limits of the collection instead of null for default values794 *795 * @param collectionId ID of collection796 * @example await getEffectiveLimits(2)797 * @returns object of collection limits798 */799 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {800 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();801 }802803 /**804 * Burns the collection if the signer has sufficient permissions and collection is empty.805 *806 * @param signer keyring of signer807 * @param collectionId ID of collection808 * @example await helper.collection.burn(aliceKeyring, 3);809 * @returns ```true``` if extrinsic success, otherwise ```false```810 */811 async burn(signer: TSigner, collectionId: number): Promise<boolean> {812 const result = await this.helper.executeExtrinsic(813 signer,814 'api.tx.unique.destroyCollection', [collectionId],815 true,816 );817818 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');819 }820821 /**822 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.823 *824 * @param signer keyring of signer825 * @param collectionId ID of collection826 * @param sponsorAddress Sponsor substrate address827 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")828 * @returns ```true``` if extrinsic success, otherwise ```false```829 */830 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {831 const result = await this.helper.executeExtrinsic(832 signer,833 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],834 true,835 );836837 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');838 }839840 /**841 * Confirms consent to sponsor the collection on behalf of the signer.842 *843 * @param signer keyring of signer844 * @param collectionId ID of collection845 * @example confirmSponsorship(aliceKeyring, 10)846 * @returns ```true``` if extrinsic success, otherwise ```false```847 */848 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {849 const result = await this.helper.executeExtrinsic(850 signer,851 'api.tx.unique.confirmSponsorship', [collectionId],852 true,853 );854855 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');856 }857858 /**859 * Removes the sponsor of a collection, regardless if it consented or not.860 *861 * @param signer keyring of signer862 * @param collectionId ID of collection863 * @example removeSponsor(aliceKeyring, 10)864 * @returns ```true``` if extrinsic success, otherwise ```false```865 */866 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {867 const result = await this.helper.executeExtrinsic(868 signer,869 'api.tx.unique.removeCollectionSponsor', [collectionId],870 true,871 );872873 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');874 }875876 /**877 * Sets the limits of the collection. At least one limit must be specified for a correct call.878 *879 * @param signer keyring of signer880 * @param collectionId ID of collection881 * @param limits collection limits object882 * @example883 * await setLimits(884 * aliceKeyring,885 * 10,886 * {887 * sponsorTransferTimeout: 0,888 * ownerCanDestroy: false889 * }890 * )891 * @returns ```true``` if extrinsic success, otherwise ```false```892 */893 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {894 const result = await this.helper.executeExtrinsic(895 signer,896 'api.tx.unique.setCollectionLimits', [collectionId, limits],897 true,898 );899900 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');901 }902903 /**904 * Changes the owner of the collection to the new Substrate address.905 *906 * @param signer keyring of signer907 * @param collectionId ID of collection908 * @param ownerAddress substrate address of new owner909 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")910 * @returns ```true``` if extrinsic success, otherwise ```false```911 */912 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {913 const result = await this.helper.executeExtrinsic(914 signer,915 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],916 true,917 );918919 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');920 }921922 /**923 * Adds a collection administrator.924 *925 * @param signer keyring of signer926 * @param collectionId ID of collection927 * @param adminAddressObj Administrator address (substrate or ethereum)928 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})929 * @returns ```true``` if extrinsic success, otherwise ```false```930 */931 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {932 const result = await this.helper.executeExtrinsic(933 signer,934 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],935 true,936 );937938 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');939 }940941 /**942 * Removes a collection administrator.943 *944 * @param signer keyring of signer945 * @param collectionId ID of collection946 * @param adminAddressObj Administrator address (substrate or ethereum)947 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})948 * @returns ```true``` if extrinsic success, otherwise ```false```949 */950 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {951 const result = await this.helper.executeExtrinsic(952 signer,953 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],954 true,955 );956957 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');958 }959960 /**961 * Check if user is in allow list.962 *963 * @param collectionId ID of collection964 * @param user Account to check965 * @example await getAdmins(1)966 * @returns is user in allow list967 */968 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {969 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();970 }971972 /**973 * Adds an address to allow list974 * @param signer keyring of signer975 * @param collectionId ID of collection976 * @param addressObj address to add to the allow list977 * @returns ```true``` if extrinsic success, otherwise ```false```978 */979 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {980 const result = await this.helper.executeExtrinsic(981 signer,982 'api.tx.unique.addToAllowList', [collectionId, addressObj],983 true,984 );985986 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');987 }988989 /**990 * Removes an address from allow list991 *992 * @param signer keyring of signer993 * @param collectionId ID of collection994 * @param addressObj address to remove from the allow list995 * @returns ```true``` if extrinsic success, otherwise ```false```996 */997 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {998 const result = await this.helper.executeExtrinsic(999 signer,1000 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1001 true,1002 );10031004 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');1005 }10061007 /**1008 * Sets onchain permissions for selected collection.1009 *1010 * @param signer keyring of signer1011 * @param collectionId ID of collection1012 * @param permissions collection permissions object1013 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1014 * @returns ```true``` if extrinsic success, otherwise ```false```1015 */1016 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1017 const result = await this.helper.executeExtrinsic(1018 signer,1019 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1020 true,1021 );10221023 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1024 }10251026 /**1027 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1028 *1029 * @param signer keyring of signer1030 * @param collectionId ID of collection1031 * @param permissions nesting permissions object1032 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1033 * @returns ```true``` if extrinsic success, otherwise ```false```1034 */1035 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1036 return await this.setPermissions(signer, collectionId, {nesting: permissions});1037 }10381039 /**1040 * Disables nesting for selected collection.1041 *1042 * @param signer keyring of signer1043 * @param collectionId ID of collection1044 * @example disableNesting(aliceKeyring, 10);1045 * @returns ```true``` if extrinsic success, otherwise ```false```1046 */1047 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1048 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1049 }10501051 /**1052 * Sets onchain properties to the collection.1053 *1054 * @param signer keyring of signer1055 * @param collectionId ID of collection1056 * @param properties array of property objects1057 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1058 * @returns ```true``` if extrinsic success, otherwise ```false```1059 */1060 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1061 const result = await this.helper.executeExtrinsic(1062 signer,1063 'api.tx.unique.setCollectionProperties', [collectionId, properties],1064 true,1065 );10661067 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1068 }10691070 /**1071 * Get collection properties.1072 *1073 * @param collectionId ID of collection1074 * @param propertyKeys optionally filter the returned properties to only these keys1075 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1076 * @returns array of key-value pairs1077 */1078 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1079 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1080 }10811082 async getCollectionOptions(collectionId: number) {1083 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1084 }10851086 /**1087 * Deletes onchain properties from the collection.1088 *1089 * @param signer keyring of signer1090 * @param collectionId ID of collection1091 * @param propertyKeys array of property keys to delete1092 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1093 * @returns ```true``` if extrinsic success, otherwise ```false```1094 */1095 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1096 const result = await this.helper.executeExtrinsic(1097 signer,1098 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1099 true,1100 );11011102 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1103 }11041105 /**1106 * Changes the owner of the token.1107 *1108 * @param signer keyring of signer1109 * @param collectionId ID of collection1110 * @param tokenId ID of token1111 * @param addressObj address of a new owner1112 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1113 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1114 * @returns true if the token success, otherwise false1115 */1116 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1117 const result = await this.helper.executeExtrinsic(1118 signer,1119 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1120 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1121 );11221123 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1124 }11251126 /**1127 *1128 * Change ownership of a token(s) on behalf of the owner.1129 *1130 * @param signer keyring of signer1131 * @param collectionId ID of collection1132 * @param tokenId ID of token1133 * @param fromAddressObj address on behalf of which the token will be sent1134 * @param toAddressObj new token owner1135 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1136 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1137 * @returns true if the token success, otherwise false1138 */1139 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1140 const result = await this.helper.executeExtrinsic(1141 signer,1142 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1143 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1144 );1145 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1146 }11471148 /**1149 *1150 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1151 *1152 * @param signer keyring of signer1153 * @param collectionId ID of collection1154 * @param tokenId ID of token1155 * @param amount amount of tokens to be burned. For NFT must be set to 1n1156 * @example burnToken(aliceKeyring, 10, 5);1157 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1158 */1159 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1160 const burnResult = await this.helper.executeExtrinsic(1161 signer,1162 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1163 true, // `Unable to burn token for ${label}`,1164 );1165 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1166 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1167 return burnedTokens.success;1168 }11691170 /**1171 * Destroys a concrete instance of NFT on behalf of the owner1172 *1173 * @param signer keyring of signer1174 * @param collectionId ID of collection1175 * @param tokenId ID of token1176 * @param fromAddressObj address on behalf of which the token will be burnt1177 * @param amount amount of tokens to be burned. For NFT must be set to 1n1178 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1179 * @returns ```true``` if extrinsic success, otherwise ```false```1180 */1181 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1182 const burnResult = await this.helper.executeExtrinsic(1183 signer,1184 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1185 true, // `Unable to burn token from for ${label}`,1186 );1187 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1188 return burnedTokens.success && burnedTokens.tokens.length > 0;1189 }11901191 /**1192 * Set, change, or remove approved address to transfer the ownership of the NFT.1193 *1194 * @param signer keyring of signer1195 * @param collectionId ID of collection1196 * @param tokenId ID of token1197 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1198 * @param amount amount of token to be approved. For NFT must be set to 1n1199 * @returns ```true``` if extrinsic success, otherwise ```false```1200 */1201 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1202 const approveResult = await this.helper.executeExtrinsic(1203 signer,1204 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1205 true, // `Unable to approve token for ${label}`,1206 );12071208 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1209 }12101211 /**1212 * Get the amount of token pieces approved to transfer or burn. Normally 0.1213 *1214 * @param collectionId ID of collection1215 * @param tokenId ID of token1216 * @param toAccountObj address which is approved to use token pieces1217 * @param fromAccountObj address which may have allowed the use of its owned tokens1218 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1219 * @returns number of approved to transfer pieces1220 */1221 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1222 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1223 }12241225 /**1226 * Get the last created token ID in a collection1227 *1228 * @param collectionId ID of collection1229 * @example getLastTokenId(10);1230 * @returns id of the last created token1231 */1232 async getLastTokenId(collectionId: number): Promise<number> {1233 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1234 }12351236 /**1237 * Check if token exists1238 *1239 * @param collectionId ID of collection1240 * @param tokenId ID of token1241 * @example doesTokenExist(10, 20);1242 * @returns true if the token exists, otherwise false1243 */1244 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1245 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1246 }1247}12481249class NFTnRFT extends CollectionGroup {1250 /**1251 * Get tokens owned by account1252 *1253 * @param collectionId ID of collection1254 * @param addressObj tokens owner1255 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1256 * @returns array of token ids owned by account1257 */1258 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1259 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1260 }12611262 /**1263 * Get token data1264 *1265 * @param collectionId ID of collection1266 * @param tokenId ID of token1267 * @param propertyKeys optionally filter the token properties to only these keys1268 * @param blockHashAt optionally query the data at some block with this hash1269 * @example getToken(10, 5);1270 * @returns human readable token data1271 */1272 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1273 properties: IProperty[];1274 owner: CrossAccountId;1275 normalizedOwner: CrossAccountId;1276 }| null> {1277 let tokenData;1278 if(typeof blockHashAt === 'undefined') {1279 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1280 }1281 else {1282 if(propertyKeys.length == 0) {1283 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1284 if(!collection) return null;1285 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1286 }1287 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1288 }1289 tokenData = tokenData.toHuman();1290 if (tokenData === null || tokenData.owner === null) return null;1291 const owner = {} as any;1292 for (const key of Object.keys(tokenData.owner)) {1293 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1294 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1295 : tokenData.owner[key];1296 }1297 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1298 return tokenData;1299 }13001301 /**1302 * Set permissions to change token properties1303 *1304 * @param signer keyring of signer1305 * @param collectionId ID of collection1306 * @param permissions permissions to change a property by the collection admin or token owner1307 * @example setTokenPropertyPermissions(1308 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1309 * )1310 * @returns true if extrinsic success otherwise false1311 */1312 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1313 const result = await this.helper.executeExtrinsic(1314 signer,1315 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1316 true,1317 );13181319 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1320 }13211322 /**1323 * Get token property permissions.1324 *1325 * @param collectionId ID of collection1326 * @param propertyKeys optionally filter the returned property permissions to only these keys1327 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1328 * @returns array of key-permission pairs1329 */1330 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1331 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1332 }13331334 /**1335 * Set token properties1336 *1337 * @param signer keyring of signer1338 * @param collectionId ID of collection1339 * @param tokenId ID of token1340 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1341 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1342 * @returns ```true``` if extrinsic success, otherwise ```false```1343 */1344 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1345 const result = await this.helper.executeExtrinsic(1346 signer,1347 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1348 true,1349 );13501351 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1352 }13531354 /**1355 * Get properties, metadata assigned to a token.1356 *1357 * @param collectionId ID of collection1358 * @param tokenId ID of token1359 * @param propertyKeys optionally filter the returned properties to only these keys1360 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1361 * @returns array of key-value pairs1362 */1363 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1364 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1365 }13661367 /**1368 * Delete the provided properties of a token1369 * @param signer keyring of signer1370 * @param collectionId ID of collection1371 * @param tokenId ID of token1372 * @param propertyKeys property keys to be deleted1373 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1374 * @returns ```true``` if extrinsic success, otherwise ```false```1375 */1376 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1377 const result = await this.helper.executeExtrinsic(1378 signer,1379 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1380 true,1381 );13821383 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1384 }13851386 /**1387 * Mint new collection1388 *1389 * @param signer keyring of signer1390 * @param collectionOptions basic collection options and properties1391 * @param mode NFT or RFT type of a collection1392 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1393 * @returns object of the created collection1394 */1395 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1396 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1397 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1398 for (const key of ['name', 'description', 'tokenPrefix']) {1399 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1400 }1401 const creationResult = await this.helper.executeExtrinsic(1402 signer,1403 'api.tx.unique.createCollectionEx', [collectionOptions],1404 true, // errorLabel,1405 );1406 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1407 }14081409 getCollectionObject(_collectionId: number): any {1410 return null;1411 }14121413 getTokenObject(_collectionId: number, _tokenId: number): any {1414 return null;1415 }1416}141714181419class NFTGroup extends NFTnRFT {1420 /**1421 * Get collection object1422 * @param collectionId ID of collection1423 * @example getCollectionObject(2);1424 * @returns instance of UniqueNFTCollection1425 */1426 getCollectionObject(collectionId: number): UniqueNFTCollection {1427 return new UniqueNFTCollection(collectionId, this.helper);1428 }14291430 /**1431 * Get token object1432 * @param collectionId ID of collection1433 * @param tokenId ID of token1434 * @example getTokenObject(10, 5);1435 * @returns instance of UniqueNFTToken1436 */1437 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1438 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1439 }14401441 /**1442 * Get token's owner1443 * @param collectionId ID of collection1444 * @param tokenId ID of token1445 * @param blockHashAt optionally query the data at the block with this hash1446 * @example getTokenOwner(10, 5);1447 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1448 */1449 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1450 let owner;1451 if (typeof blockHashAt === 'undefined') {1452 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1453 } else {1454 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1455 }1456 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1457 }14581459 /**1460 * Is token approved to transfer1461 * @param collectionId ID of collection1462 * @param tokenId ID of token1463 * @param toAccountObj address to be approved1464 * @returns ```true``` if extrinsic success, otherwise ```false```1465 */1466 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1467 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1468 }14691470 /**1471 * Changes the owner of the token.1472 *1473 * @param signer keyring of signer1474 * @param collectionId ID of collection1475 * @param tokenId ID of token1476 * @param addressObj address of a new owner1477 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1478 * @returns ```true``` if extrinsic success, otherwise ```false```1479 */1480 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1481 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1482 }14831484 /**1485 *1486 * Change ownership of a NFT on behalf of the owner.1487 *1488 * @param signer keyring of signer1489 * @param collectionId ID of collection1490 * @param tokenId ID of token1491 * @param fromAddressObj address on behalf of which the token will be sent1492 * @param toAddressObj new token owner1493 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1494 * @returns ```true``` if extrinsic success, otherwise ```false```1495 */1496 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1497 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1498 }14991500 /**1501 * Recursively find the address that owns the token1502 * @param collectionId ID of collection1503 * @param tokenId ID of token1504 * @param blockHashAt1505 * @example getTokenTopmostOwner(10, 5);1506 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1507 */1508 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1509 let owner;1510 if (typeof blockHashAt === 'undefined') {1511 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1512 } else {1513 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1514 }15151516 if (owner === null) return null;15171518 return owner.toHuman();1519 }15201521 /**1522 * Get tokens nested in the provided token1523 * @param collectionId ID of collection1524 * @param tokenId ID of token1525 * @param blockHashAt optionally query the data at the block with this hash1526 * @example getTokenChildren(10, 5);1527 * @returns tokens whose depth of nesting is <= 51528 */1529 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1530 let children;1531 if(typeof blockHashAt === 'undefined') {1532 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1533 } else {1534 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1535 }15361537 return children.toJSON().map((x: any) => {1538 return {collectionId: x.collection, tokenId: x.token};1539 });1540 }15411542 /**1543 * Nest one token into another1544 * @param signer keyring of signer1545 * @param tokenObj token to be nested1546 * @param rootTokenObj token to be parent1547 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1548 * @returns ```true``` if extrinsic success, otherwise ```false```1549 */1550 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1551 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1552 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1553 if(!result) {1554 throw Error('Unable to nest token!');1555 }1556 return result;1557 }15581559 /**1560 * Remove token from nested state1561 * @param signer keyring of signer1562 * @param tokenObj token to unnest1563 * @param rootTokenObj parent of a token1564 * @param toAddressObj address of a new token owner1565 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1566 * @returns ```true``` if extrinsic success, otherwise ```false```1567 */1568 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1569 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1570 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1571 if(!result) {1572 throw Error('Unable to unnest token!');1573 }1574 return result;1575 }15761577 /**1578 * Mint new collection1579 * @param signer keyring of signer1580 * @param collectionOptions Collection options1581 * @example1582 * mintCollection(aliceKeyring, {1583 * name: 'New',1584 * description: 'New collection',1585 * tokenPrefix: 'NEW',1586 * })1587 * @returns object of the created collection1588 */1589 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1590 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1591 }15921593 /**1594 * Mint new token1595 * @param signer keyring of signer1596 * @param data token data1597 * @returns created token object1598 */1599 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1600 const creationResult = await this.helper.executeExtrinsic(1601 signer,1602 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1603 nft: {1604 properties: data.properties,1605 },1606 }],1607 true,1608 );1609 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1610 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1611 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1612 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1613 }16141615 /**1616 * Mint multiple NFT tokens1617 * @param signer keyring of signer1618 * @param collectionId ID of collection1619 * @param tokens array of tokens with owner and properties1620 * @example1621 * mintMultipleTokens(aliceKeyring, 10, [{1622 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1623 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1624 * },{1625 * owner: {Ethereum: "0x9F0583DbB855d..."},1626 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1627 * }]);1628 * @returns ```true``` if extrinsic success, otherwise ```false```1629 */1630 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1631 const creationResult = await this.helper.executeExtrinsic(1632 signer,1633 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1634 true,1635 );1636 const collection = this.getCollectionObject(collectionId);1637 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1638 }16391640 /**1641 * Mint multiple NFT tokens with one owner1642 * @param signer keyring of signer1643 * @param collectionId ID of collection1644 * @param owner tokens owner1645 * @param tokens array of tokens with owner and properties1646 * @example1647 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1648 * properties: [{1649 * key: "gender",1650 * value: "female",1651 * },{1652 * key: "age",1653 * value: "33",1654 * }],1655 * }]);1656 * @returns array of newly created tokens1657 */1658 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1659 const rawTokens = [];1660 for (const token of tokens) {1661 const raw = {NFT: {properties: token.properties}};1662 rawTokens.push(raw);1663 }1664 const creationResult = await this.helper.executeExtrinsic(1665 signer,1666 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1667 true,1668 );1669 const collection = this.getCollectionObject(collectionId);1670 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1671 }16721673 /**1674 * Set, change, or remove approved address to transfer the ownership of the NFT.1675 *1676 * @param signer keyring of signer1677 * @param collectionId ID of collection1678 * @param tokenId ID of token1679 * @param toAddressObj address to approve1680 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1681 * @returns ```true``` if extrinsic success, otherwise ```false```1682 */1683 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1684 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1685 }1686}168716881689class RFTGroup extends NFTnRFT {1690 /**1691 * Get collection object1692 * @param collectionId ID of collection1693 * @example getCollectionObject(2);1694 * @returns instance of UniqueRFTCollection1695 */1696 getCollectionObject(collectionId: number): UniqueRFTCollection {1697 return new UniqueRFTCollection(collectionId, this.helper);1698 }16991700 /**1701 * Get token object1702 * @param collectionId ID of collection1703 * @param tokenId ID of token1704 * @example getTokenObject(10, 5);1705 * @returns instance of UniqueNFTToken1706 */1707 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1708 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1709 }17101711 /**1712 * Get top 10 token owners with the largest number of pieces1713 * @param collectionId ID of collection1714 * @param tokenId ID of token1715 * @example getTokenTop10Owners(10, 5);1716 * @returns array of top 10 owners1717 */1718 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1719 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1720 }17211722 /**1723 * Get number of pieces owned by address1724 * @param collectionId ID of collection1725 * @param tokenId ID of token1726 * @param addressObj address token owner1727 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1728 * @returns number of pieces ownerd by address1729 */1730 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1731 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1732 }17331734 /**1735 * Transfer pieces of token to another address1736 * @param signer keyring of signer1737 * @param collectionId ID of collection1738 * @param tokenId ID of token1739 * @param addressObj address of a new owner1740 * @param amount number of pieces to be transfered1741 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1742 * @returns ```true``` if extrinsic success, otherwise ```false```1743 */1744 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1745 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1746 }17471748 /**1749 * Change ownership of some pieces of RFT on behalf of the owner.1750 * @param signer keyring of signer1751 * @param collectionId ID of collection1752 * @param tokenId ID of token1753 * @param fromAddressObj address on behalf of which the token will be sent1754 * @param toAddressObj new token owner1755 * @param amount number of pieces to be transfered1756 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1757 * @returns ```true``` if extrinsic success, otherwise ```false```1758 */1759 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1760 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1761 }17621763 /**1764 * Mint new collection1765 * @param signer keyring of signer1766 * @param collectionOptions Collection options1767 * @example1768 * mintCollection(aliceKeyring, {1769 * name: 'New',1770 * description: 'New collection',1771 * tokenPrefix: 'NEW',1772 * })1773 * @returns object of the created collection1774 */1775 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1776 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1777 }17781779 /**1780 * Mint new token1781 * @param signer keyring of signer1782 * @param data token data1783 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1784 * @returns created token object1785 */1786 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1787 const creationResult = await this.helper.executeExtrinsic(1788 signer,1789 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1790 refungible: {1791 pieces: data.pieces,1792 properties: data.properties,1793 },1794 }],1795 true,1796 );1797 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1798 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1799 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1800 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1801 }18021803 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1804 throw Error('Not implemented');1805 const creationResult = await this.helper.executeExtrinsic(1806 signer,1807 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1808 true, // `Unable to mint RFT tokens for ${label}`,1809 );1810 const collection = this.getCollectionObject(collectionId);1811 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1812 }18131814 /**1815 * Mint multiple RFT tokens with one owner1816 * @param signer keyring of signer1817 * @param collectionId ID of collection1818 * @param owner tokens owner1819 * @param tokens array of tokens with properties and pieces1820 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1821 * @returns array of newly created RFT tokens1822 */1823 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1824 const rawTokens = [];1825 for (const token of tokens) {1826 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1827 rawTokens.push(raw);1828 }1829 const creationResult = await this.helper.executeExtrinsic(1830 signer,1831 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1832 true,1833 );1834 const collection = this.getCollectionObject(collectionId);1835 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1836 }18371838 /**1839 * Destroys a concrete instance of RFT.1840 * @param signer keyring of signer1841 * @param collectionId ID of collection1842 * @param tokenId ID of token1843 * @param amount number of pieces to be burnt1844 * @example burnToken(aliceKeyring, 10, 5);1845 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1846 */1847 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1848 return await super.burnToken(signer, collectionId, tokenId, amount);1849 }18501851 /**1852 * Destroys a concrete instance of RFT on behalf of the owner.1853 * @param signer keyring of signer1854 * @param collectionId ID of collection1855 * @param tokenId ID of token1856 * @param fromAddressObj address on behalf of which the token will be burnt1857 * @param amount number of pieces to be burnt1858 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1859 * @returns ```true``` if extrinsic success, otherwise ```false```1860 */1861 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1862 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1863 }18641865 /**1866 * Set, change, or remove approved address to transfer the ownership of the RFT.1867 *1868 * @param signer keyring of signer1869 * @param collectionId ID of collection1870 * @param tokenId ID of token1871 * @param toAddressObj address to approve1872 * @param amount number of pieces to be approved1873 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1874 * @returns true if the token success, otherwise false1875 */1876 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1877 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1878 }18791880 /**1881 * Get total number of pieces1882 * @param collectionId ID of collection1883 * @param tokenId ID of token1884 * @example getTokenTotalPieces(10, 5);1885 * @returns number of pieces1886 */1887 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1888 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1889 }18901891 /**1892 * Change number of token pieces. Signer must be the owner of all token pieces.1893 * @param signer keyring of signer1894 * @param collectionId ID of collection1895 * @param tokenId ID of token1896 * @param amount new number of pieces1897 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1898 * @returns true if the repartion was success, otherwise false1899 */1900 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1901 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1902 const repartitionResult = await this.helper.executeExtrinsic(1903 signer,1904 'api.tx.unique.repartition', [collectionId, tokenId, amount],1905 true,1906 );1907 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1908 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1909 }1910}191119121913class FTGroup extends CollectionGroup {1914 /**1915 * Get collection object1916 * @param collectionId ID of collection1917 * @example getCollectionObject(2);1918 * @returns instance of UniqueFTCollection1919 */1920 getCollectionObject(collectionId: number): UniqueFTCollection {1921 return new UniqueFTCollection(collectionId, this.helper);1922 }19231924 /**1925 * Mint new fungible collection1926 * @param signer keyring of signer1927 * @param collectionOptions Collection options1928 * @param decimalPoints number of token decimals1929 * @example1930 * mintCollection(aliceKeyring, {1931 * name: 'New',1932 * description: 'New collection',1933 * tokenPrefix: 'NEW',1934 * }, 18)1935 * @returns newly created fungible collection1936 */1937 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1938 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1939 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1940 collectionOptions.mode = {fungible: decimalPoints};1941 for (const key of ['name', 'description', 'tokenPrefix']) {1942 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1943 }1944 const creationResult = await this.helper.executeExtrinsic(1945 signer,1946 'api.tx.unique.createCollectionEx', [collectionOptions],1947 true,1948 );1949 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1950 }19511952 /**1953 * Mint tokens1954 * @param signer keyring of signer1955 * @param collectionId ID of collection1956 * @param owner address owner of new tokens1957 * @param amount amount of tokens to be meanted1958 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1959 * @returns ```true``` if extrinsic success, otherwise ```false```1960 */1961 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1962 const creationResult = await this.helper.executeExtrinsic(1963 signer,1964 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1965 fungible: {1966 value: amount,1967 },1968 }],1969 true, // `Unable to mint fungible tokens for ${label}`,1970 );1971 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1972 }19731974 /**1975 * Mint multiple Fungible tokens with one owner1976 * @param signer keyring of signer1977 * @param collectionId ID of collection1978 * @param owner tokens owner1979 * @param tokens array of tokens with properties and pieces1980 * @returns ```true``` if extrinsic success, otherwise ```false```1981 */1982 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1983 const rawTokens = [];1984 for (const token of tokens) {1985 const raw = {Fungible: {Value: token.value}};1986 rawTokens.push(raw);1987 }1988 const creationResult = await this.helper.executeExtrinsic(1989 signer,1990 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1991 true,1992 );1993 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1994 }19951996 /**1997 * Get the top 10 owners with the largest balance for the Fungible collection1998 * @param collectionId ID of collection1999 * @example getTop10Owners(10);2000 * @returns array of ```ICrossAccountId```2001 */2002 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2003 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2004 }20052006 /**2007 * Get account balance2008 * @param collectionId ID of collection2009 * @param addressObj address of owner2010 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2011 * @returns amount of fungible tokens owned by address2012 */2013 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2014 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2015 }20162017 /**2018 * Transfer tokens to address2019 * @param signer keyring of signer2020 * @param collectionId ID of collection2021 * @param toAddressObj address recipient2022 * @param amount amount of tokens to be sent2023 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2024 * @returns ```true``` if extrinsic success, otherwise ```false```2025 */2026 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2027 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2028 }20292030 /**2031 * Transfer some tokens on behalf of the owner.2032 * @param signer keyring of signer2033 * @param collectionId ID of collection2034 * @param fromAddressObj address on behalf of which tokens will be sent2035 * @param toAddressObj address where token to be sent2036 * @param amount number of tokens to be sent2037 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2038 * @returns ```true``` if extrinsic success, otherwise ```false```2039 */2040 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2041 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2042 }20432044 /**2045 * Destroy some amount of tokens2046 * @param signer keyring of signer2047 * @param collectionId ID of collection2048 * @param amount amount of tokens to be destroyed2049 * @example burnTokens(aliceKeyring, 10, 1000n);2050 * @returns ```true``` if extrinsic success, otherwise ```false```2051 */2052 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2053 return await super.burnToken(signer, collectionId, 0, amount);2054 }20552056 /**2057 * Burn some tokens on behalf of the owner.2058 * @param signer keyring of signer2059 * @param collectionId ID of collection2060 * @param fromAddressObj address on behalf of which tokens will be burnt2061 * @param amount amount of tokens to be burnt2062 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2063 * @returns ```true``` if extrinsic success, otherwise ```false```2064 */2065 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2066 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2067 }20682069 /**2070 * Get total collection supply2071 * @param collectionId2072 * @returns2073 */2074 async getTotalPieces(collectionId: number): Promise<bigint> {2075 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2076 }20772078 /**2079 * Set, change, or remove approved address to transfer tokens.2080 *2081 * @param signer keyring of signer2082 * @param collectionId ID of collection2083 * @param toAddressObj address to be approved2084 * @param amount amount of tokens to be approved2085 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2086 * @returns ```true``` if extrinsic success, otherwise ```false```2087 */2088 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2089 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2090 }20912092 /**2093 * Get amount of fungible tokens approved to transfer2094 * @param collectionId ID of collection2095 * @param fromAddressObj owner of tokens2096 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2097 * @returns number of tokens approved for the transfer2098 */2099 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2100 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2101 }2102}210321042105class ChainGroup extends HelperGroup<ChainHelperBase> {2106 /**2107 * Get system properties of a chain2108 * @example getChainProperties();2109 * @returns ss58Format, token decimals, and token symbol2110 */2111 getChainProperties(): IChainProperties {2112 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2113 return {2114 ss58Format: properties.ss58Format.toJSON(),2115 tokenDecimals: properties.tokenDecimals.toJSON(),2116 tokenSymbol: properties.tokenSymbol.toJSON(),2117 };2118 }21192120 /**2121 * Get chain header2122 * @example getLatestBlockNumber();2123 * @returns the number of the last block2124 */2125 async getLatestBlockNumber(): Promise<number> {2126 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2127 }21282129 /**2130 * Get block hash by block number2131 * @param blockNumber number of block2132 * @example getBlockHashByNumber(12345);2133 * @returns hash of a block2134 */2135 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2136 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2137 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2138 return blockHash;2139 }21402141 // TODO add docs2142 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2143 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2144 if (!blockHash) return null;2145 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2146 }21472148 /**2149 * Get account nonce2150 * @param address substrate address2151 * @example getNonce("5GrwvaEF5zXb26Fz...");2152 * @returns number, account's nonce2153 */2154 async getNonce(address: TSubstrateAccount): Promise<number> {2155 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2156 }2157}21582159class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2160 /**2161 * Get substrate address balance2162 * @param address substrate address2163 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2164 * @returns amount of tokens on address2165 */2166 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2167 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2168 }21692170 /**2171 * Transfer tokens to substrate address2172 * @param signer keyring of signer2173 * @param address substrate address of a recipient2174 * @param amount amount of tokens to be transfered2175 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2176 * @returns ```true``` if extrinsic success, otherwise ```false```2177 */2178 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2179 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);21802181 let transfer = {from: null, to: null, amount: 0n} as any;2182 result.result.events.forEach(({event: {data, method, section}}) => {2183 if ((section === 'balances') && (method === 'Transfer')) {2184 transfer = {2185 from: this.helper.address.normalizeSubstrate(data[0]),2186 to: this.helper.address.normalizeSubstrate(data[1]),2187 amount: BigInt(data[2]),2188 };2189 }2190 });2191 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2192 && this.helper.address.normalizeSubstrate(address) === transfer.to2193 && BigInt(amount) === transfer.amount;2194 return isSuccess;2195 }21962197 /**2198 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2199 * @param address substrate address2200 * @returns2201 */2202 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2203 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2204 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2205 }2206}22072208class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2209 /**2210 * Get ethereum address balance2211 * @param address ethereum address2212 * @example getEthereum("0x9F0583DbB855d...")2213 * @returns amount of tokens on address2214 */2215 async getEthereum(address: TEthereumAccount): Promise<bigint> {2216 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2217 }22182219 /**2220 * Transfer tokens to address2221 * @param signer keyring of signer2222 * @param address Ethereum address of a recipient2223 * @param amount amount of tokens to be transfered2224 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2225 * @returns ```true``` if extrinsic success, otherwise ```false```2226 */2227 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2228 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22292230 let transfer = {from: null, to: null, amount: 0n} as any;2231 result.result.events.forEach(({event: {data, method, section}}) => {2232 if ((section === 'balances') && (method === 'Transfer')) {2233 transfer = {2234 from: data[0].toString(),2235 to: data[1].toString(),2236 amount: BigInt(data[2]),2237 };2238 }2239 });2240 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2241 && address === transfer.to2242 && BigInt(amount) === transfer.amount;2243 return isSuccess;2244 }2245}22462247class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2248 subBalanceGroup: SubstrateBalanceGroup<T>;2249 ethBalanceGroup: EthereumBalanceGroup<T>;22502251 constructor(helper: T) {2252 super(helper);2253 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2254 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2255 }22562257 getCollectionCreationPrice(): bigint {2258 return 2n * this.getOneTokenNominal();2259 }2260 /**2261 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2262 * @example getOneTokenNominal()2263 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2264 */2265 getOneTokenNominal(): bigint {2266 const chainProperties = this.helper.chain.getChainProperties();2267 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2268 }22692270 /**2271 * Get substrate address balance2272 * @param address substrate address2273 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2274 * @returns amount of tokens on address2275 */2276 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2277 return this.subBalanceGroup.getSubstrate(address);2278 }22792280 /**2281 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2282 * @param address substrate address2283 * @returns2284 */2285 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2286 return this.subBalanceGroup.getSubstrateFull(address);2287 }22882289 /**2290 * Get ethereum address balance2291 * @param address ethereum address2292 * @example getEthereum("0x9F0583DbB855d...")2293 * @returns amount of tokens on address2294 */2295 getEthereum(address: TEthereumAccount): Promise<bigint> {2296 return this.ethBalanceGroup.getEthereum(address);2297 }22982299 /**2300 * Transfer tokens to substrate address2301 * @param signer keyring of signer2302 * @param address substrate address of a recipient2303 * @param amount amount of tokens to be transfered2304 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2305 * @returns ```true``` if extrinsic success, otherwise ```false```2306 */2307 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2308 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2309 }23102311 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2312 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23132314 let transfer = {from: null, to: null, amount: 0n} as any;2315 result.result.events.forEach(({event: {data, method, section}}) => {2316 if ((section === 'balances') && (method === 'Transfer')) {2317 transfer = {2318 from: this.helper.address.normalizeSubstrate(data[0]),2319 to: this.helper.address.normalizeSubstrate(data[1]),2320 amount: BigInt(data[2]),2321 };2322 }2323 });2324 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2325 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2326 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2327 return isSuccess;2328 }2329}23302331class AddressGroup extends HelperGroup<ChainHelperBase> {2332 /**2333 * Normalizes the address to the specified ss58 format, by default ```42```.2334 * @param address substrate address2335 * @param ss58Format format for address conversion, by default ```42```2336 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2337 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2338 */2339 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2340 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2341 }23422343 /**2344 * Get address in the connected chain format2345 * @param address substrate address2346 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2347 * @returns address in chain format2348 */2349 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2350 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2351 }23522353 /**2354 * Get substrate mirror of an ethereum address2355 * @param ethAddress ethereum address2356 * @param toChainFormat false for normalized account2357 * @example ethToSubstrate('0x9F0583DbB855d...')2358 * @returns substrate mirror of a provided ethereum address2359 */2360 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2361 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2362 }23632364 /**2365 * Get ethereum mirror of a substrate address2366 * @param subAddress substrate account2367 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2368 * @returns ethereum mirror of a provided substrate address2369 */2370 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2371 return CrossAccountId.translateSubToEth(subAddress);2372 }23732374 /**2375 * Encode key to substrate address2376 * @param key key for encoding address2377 * @param ss58Format prefix for encoding to the address of the corresponding network2378 * @returns encoded substrate address2379 */2380 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2381 const u8a :Uint8Array = typeof key === 'string'2382 ? hexToU8a(key)2383 : typeof key === 'bigint'2384 ? hexToU8a(key.toString(16))2385 : key;2386 2387 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2388 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2389 }2390 2391 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2392 if (!allowedDecodedLengths.includes(u8a.length)) {2393 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2394 }2395 2396 const u8aPrefix = ss58Format < 642397 ? new Uint8Array([ss58Format])2398 : new Uint8Array([2399 ((ss58Format & 0xfc) >> 2) | 0x40,2400 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2401 ]);24022403 const input = u8aConcat(u8aPrefix, u8a);2404 2405 return base58Encode(u8aConcat(2406 input,2407 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2408 ));2409 }24102411 /**2412 * Restore substrate address from bigint representation2413 * @param number decimal representation of substrate address2414 * @returns substrate address2415 */2416 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2417 if (this.helper.api === null) {2418 throw 'Not connected';2419 }2420 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2421 if (res === undefined || res === null) {2422 throw 'Restore address error';2423 }2424 return res.toString();2425 }24262427 /**2428 * Convert etherium cross account id to substrate cross account id2429 * @param ethCrossAccount etherium cross account2430 * @returns substrate cross account id2431 */2432 convertCrossAccountFromEthCrossAcoount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2433 if (ethCrossAccount.sub === '0') {2434 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2435 }2436 2437 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2438 return {Substrate: ss58};2439 }24402441 paraSiblingSovereignAccount(paraid: number) {2442 // We are getting a *sibling* parachain sovereign account,2443 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2444 const siblingPrefix = '0x7369626c';24452446 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2447 const suffix = '000000000000000000000000000000000000000000000000';24482449 return siblingPrefix + encodedParaId + suffix;2450 }2451}24522453class StakingGroup extends HelperGroup<UniqueHelper> {2454 /**2455 * Stake tokens for App Promotion2456 * @param signer keyring of signer2457 * @param amountToStake amount of tokens to stake2458 * @param label extra label for log2459 * @returns2460 */2461 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2462 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2463 const _stakeResult = await this.helper.executeExtrinsic(2464 signer, 'api.tx.appPromotion.stake',2465 [amountToStake], true,2466 );2467 // TODO extract info from stakeResult2468 return true;2469 }24702471 /**2472 * Unstake tokens for App Promotion2473 * @param signer keyring of signer2474 * @param amountToUnstake amount of tokens to unstake2475 * @param label extra label for log2476 * @returns block number where balances will be unlocked2477 */2478 async unstake(signer: TSigner, label?: string): Promise<number> {2479 if(typeof label === 'undefined') label = `${signer.address}`;2480 const _unstakeResult = await this.helper.executeExtrinsic(2481 signer, 'api.tx.appPromotion.unstake',2482 [], true,2483 );2484 // TODO extract block number fron events2485 return 1;2486 }24872488 /**2489 * Get total staked amount for address2490 * @param address substrate or ethereum address2491 * @returns total staked amount2492 */2493 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2494 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2495 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2496 }24972498 /**2499 * Get total staked per block2500 * @param address substrate or ethereum address2501 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2502 */2503 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2504 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2505 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2506 return {2507 block: block.toBigInt(),2508 amount: amount.toBigInt(),2509 };2510 });2511 }25122513 /**2514 * Get total pending unstake amount for address2515 * @param address substrate or ethereum address2516 * @returns total pending unstake amount2517 */2518 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2519 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2520 }25212522 /**2523 * Get pending unstake amount per block for address2524 * @param address substrate or ethereum address2525 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2526 */2527 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2528 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2529 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2530 return {2531 block: block.toBigInt(),2532 amount: amount.toBigInt(),2533 };2534 });2535 return result;2536 }2537}25382539class SchedulerGroup extends HelperGroup<UniqueHelper> {2540 constructor(helper: UniqueHelper) {2541 super(helper);2542 }25432544 cancelScheduled(signer: TSigner, scheduledId: string) {2545 return this.helper.executeExtrinsic(2546 signer,2547 'api.tx.scheduler.cancelNamed',2548 [scheduledId],2549 true,2550 );2551 }25522553 changePriority(signer: TSigner, scheduledId: string, priority: number) {2554 return this.helper.executeExtrinsic(2555 signer,2556 'api.tx.scheduler.changeNamedPriority',2557 [scheduledId, priority],2558 true,2559 );2560 }25612562 scheduleAt<T extends UniqueHelper>(2563 scheduledId: string,2564 executionBlockNumber: number,2565 options: ISchedulerOptions = {},2566 ) {2567 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2568 }25692570 scheduleAfter<T extends UniqueHelper>(2571 scheduledId: string,2572 blocksBeforeExecution: number,2573 options: ISchedulerOptions = {},2574 ) {2575 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2576 }25772578 schedule<T extends UniqueHelper>(2579 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2580 scheduledId: string,2581 blocksNum: number,2582 options: ISchedulerOptions = {},2583 ) {2584 // eslint-disable-next-line @typescript-eslint/naming-convention2585 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2586 return this.helper.clone(ScheduledHelperType, {2587 scheduleFn,2588 scheduledId,2589 blocksNum,2590 options,2591 }) as T;2592 }2593}25942595class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2596 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2597 await this.helper.executeExtrinsic(2598 signer,2599 'api.tx.foreignAssets.registerForeignAsset',2600 [ownerAddress, location, metadata],2601 true,2602 );2603 }26042605 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2606 await this.helper.executeExtrinsic(2607 signer,2608 'api.tx.foreignAssets.updateForeignAsset',2609 [foreignAssetId, location, metadata],2610 true,2611 );2612 }2613}26142615class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2616 palletName: string;26172618 constructor(helper: T, palletName: string) {2619 super(helper);26202621 this.palletName = palletName;2622 }26232624 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2625 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2626 }2627}26282629class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2630 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2631 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2632 }26332634 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2635 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2636 }26372638 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2639 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2640 }2641}26422643class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2644 async accounts(address: string, currencyId: any) {2645 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2646 return BigInt(free);2647 }2648}26492650class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2651 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2652 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2653 }26542655 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2656 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2657 }26582659 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2660 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2661 }26622663 async account(assetId: string | number, address: string) {2664 const accountAsset = (2665 await this.helper.callRpc('api.query.assets.account', [assetId, address])2666 ).toJSON()! as any;26672668 if (accountAsset !== null) {2669 return BigInt(accountAsset['balance']);2670 } else {2671 return null;2672 }2673 }2674}26752676class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2677 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2678 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2679 }2680}26812682class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2683 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2684 const apiPrefix = 'api.tx.assetManager.';26852686 const registerTx = this.helper.constructApiCall(2687 apiPrefix + 'registerForeignAsset',2688 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2689 );26902691 const setUnitsTx = this.helper.constructApiCall(2692 apiPrefix + 'setAssetUnitsPerSecond',2693 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2694 );26952696 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2697 const encodedProposal = batchCall?.method.toHex() || '';2698 return encodedProposal;2699 }27002701 async assetTypeId(location: any) {2702 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2703 }2704}27052706class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2707 async notePreimage(signer: TSigner, encodedProposal: string) {2708 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2709 }27102711 externalProposeMajority(proposalHash: string) {2712 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2713 }27142715 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2716 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2717 }27182719 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2720 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2721 }2722}27232724class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2725 collective: string;27262727 constructor(helper: MoonbeamHelper, collective: string) {2728 super(helper);27292730 this.collective = collective;2731 }27322733 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2734 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2735 }27362737 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2738 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2739 }27402741 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2742 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2743 }27442745 async proposalCount() {2746 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2747 }2748}27492750export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2751export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;27522753export class UniqueHelper extends ChainHelperBase {2754 balance: BalanceGroup<UniqueHelper>;2755 collection: CollectionGroup;2756 nft: NFTGroup;2757 rft: RFTGroup;2758 ft: FTGroup;2759 staking: StakingGroup;2760 scheduler: SchedulerGroup;2761 foreignAssets: ForeignAssetsGroup;2762 xcm: XcmGroup<UniqueHelper>;2763 xTokens: XTokensGroup<UniqueHelper>;2764 tokens: TokensGroup<UniqueHelper>;27652766 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2767 super(logger, options.helperBase ?? UniqueHelper);27682769 this.balance = new BalanceGroup(this);2770 this.collection = new CollectionGroup(this);2771 this.nft = new NFTGroup(this);2772 this.rft = new RFTGroup(this);2773 this.ft = new FTGroup(this);2774 this.staking = new StakingGroup(this);2775 this.scheduler = new SchedulerGroup(this);2776 this.foreignAssets = new ForeignAssetsGroup(this);2777 this.xcm = new XcmGroup(this, 'polkadotXcm');2778 this.xTokens = new XTokensGroup(this);2779 this.tokens = new TokensGroup(this);2780 }27812782 getSudo<T extends UniqueHelper>() {2783 // eslint-disable-next-line @typescript-eslint/naming-convention2784 const SudoHelperType = SudoHelper(this.helperBase);2785 return this.clone(SudoHelperType) as T;2786 }2787}27882789export class XcmChainHelper extends ChainHelperBase {2790 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2791 const wsProvider = new WsProvider(wsEndpoint);2792 this.api = new ApiPromise({2793 provider: wsProvider,2794 });2795 await this.api.isReadyOrError;2796 this.network = await UniqueHelper.detectNetwork(this.api);2797 }2798}27992800export class RelayHelper extends XcmChainHelper {2801 xcm: XcmGroup<RelayHelper>;28022803 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2804 super(logger, options.helperBase ?? RelayHelper);28052806 this.xcm = new XcmGroup(this, 'xcmPallet');2807 }2808}28092810export class WestmintHelper extends XcmChainHelper {2811 balance: SubstrateBalanceGroup<WestmintHelper>;2812 xcm: XcmGroup<WestmintHelper>;2813 assets: AssetsGroup<WestmintHelper>;2814 xTokens: XTokensGroup<WestmintHelper>;28152816 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2817 super(logger, options.helperBase ?? WestmintHelper);28182819 this.balance = new SubstrateBalanceGroup(this);2820 this.xcm = new XcmGroup(this, 'polkadotXcm');2821 this.assets = new AssetsGroup(this);2822 this.xTokens = new XTokensGroup(this);2823 }2824}28252826export class MoonbeamHelper extends XcmChainHelper {2827 balance: EthereumBalanceGroup<MoonbeamHelper>;2828 assetManager: MoonbeamAssetManagerGroup;2829 assets: AssetsGroup<MoonbeamHelper>;2830 xTokens: XTokensGroup<MoonbeamHelper>;2831 democracy: MoonbeamDemocracyGroup;2832 collective: {2833 council: MoonbeamCollectiveGroup,2834 techCommittee: MoonbeamCollectiveGroup,2835 };28362837 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2838 super(logger, options.helperBase ?? MoonbeamHelper);28392840 this.balance = new EthereumBalanceGroup(this);2841 this.assetManager = new MoonbeamAssetManagerGroup(this);2842 this.assets = new AssetsGroup(this);2843 this.xTokens = new XTokensGroup(this);2844 this.democracy = new MoonbeamDemocracyGroup(this);2845 this.collective = {2846 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2847 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2848 };2849 }2850}28512852export class AcalaHelper extends XcmChainHelper {2853 balance: SubstrateBalanceGroup<AcalaHelper>;2854 assetRegistry: AcalaAssetRegistryGroup;2855 xTokens: XTokensGroup<AcalaHelper>;2856 tokens: TokensGroup<AcalaHelper>;28572858 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2859 super(logger, options.helperBase ?? AcalaHelper);28602861 this.balance = new SubstrateBalanceGroup(this);2862 this.assetRegistry = new AcalaAssetRegistryGroup(this);2863 this.xTokens = new XTokensGroup(this);2864 this.tokens = new TokensGroup(this);2865 }28662867 getSudo<T extends AcalaHelper>() {2868 // eslint-disable-next-line @typescript-eslint/naming-convention2869 const SudoHelperType = SudoHelper(this.helperBase);2870 return this.clone(SudoHelperType) as T;2871 }2872}28732874// eslint-disable-next-line @typescript-eslint/naming-convention2875function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2876 return class extends Base {2877 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2878 scheduledId: string;2879 blocksNum: number;2880 options: ISchedulerOptions;28812882 constructor(...args: any[]) {2883 const logger = args[0] as ILogger;2884 const options = args[1] as {2885 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2886 scheduledId: string,2887 blocksNum: number,2888 options: ISchedulerOptions2889 };28902891 super(logger);28922893 this.scheduleFn = options.scheduleFn;2894 this.scheduledId = options.scheduledId;2895 this.blocksNum = options.blocksNum;2896 this.options = options.options;2897 }28982899 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2900 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2901 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;29022903 return super.executeExtrinsic(2904 sender,2905 extrinsic,2906 [2907 this.scheduledId,2908 this.blocksNum,2909 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2910 this.options.priority ?? null,2911 {Value: scheduledTx},2912 ],2913 expectSuccess,2914 );2915 }2916 };2917}29182919// eslint-disable-next-line @typescript-eslint/naming-convention2920function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2921 return class extends Base {2922 constructor(...args: any[]) {2923 super(...args);2924 }29252926 executeExtrinsic (2927 sender: IKeyringPair,2928 extrinsic: string,2929 params: any[],2930 expectSuccess?: boolean,2931 ): Promise<ITransactionResult> {2932 const call = this.constructApiCall(extrinsic, params);2933 return super.executeExtrinsic(2934 sender,2935 'api.tx.sudo.sudo',2936 [call],2937 expectSuccess,2938 );2939 }2940 };2941}29422943export class UniqueBaseCollection {2944 helper: UniqueHelper;2945 collectionId: number;29462947 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2948 this.collectionId = collectionId;2949 this.helper = uniqueHelper;2950 }29512952 async getData() {2953 return await this.helper.collection.getData(this.collectionId);2954 }29552956 async getLastTokenId() {2957 return await this.helper.collection.getLastTokenId(this.collectionId);2958 }29592960 async doesTokenExist(tokenId: number) {2961 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2962 }29632964 async getAdmins() {2965 return await this.helper.collection.getAdmins(this.collectionId);2966 }29672968 async getAllowList() {2969 return await this.helper.collection.getAllowList(this.collectionId);2970 }29712972 async getEffectiveLimits() {2973 return await this.helper.collection.getEffectiveLimits(this.collectionId);2974 }29752976 async getProperties(propertyKeys?: string[] | null) {2977 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2978 }29792980 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2981 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2982 }29832984 async getOptions() {2985 return await this.helper.collection.getCollectionOptions(this.collectionId);2986 }29872988 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2989 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2990 }29912992 async confirmSponsorship(signer: TSigner) {2993 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2994 }29952996 async removeSponsor(signer: TSigner) {2997 return await this.helper.collection.removeSponsor(signer, this.collectionId);2998 }29993000 async setLimits(signer: TSigner, limits: ICollectionLimits) {3001 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3002 }30033004 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3005 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3006 }30073008 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3009 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3010 }30113012 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3013 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3014 }30153016 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3017 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3018 }30193020 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3021 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3022 }30233024 async setProperties(signer: TSigner, properties: IProperty[]) {3025 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3026 }30273028 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3029 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3030 }30313032 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3033 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3034 }30353036 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3037 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3038 }30393040 async disableNesting(signer: TSigner) {3041 return await this.helper.collection.disableNesting(signer, this.collectionId);3042 }30433044 async burn(signer: TSigner) {3045 return await this.helper.collection.burn(signer, this.collectionId);3046 }30473048 scheduleAt<T extends UniqueHelper>(3049 scheduledId: string,3050 executionBlockNumber: number,3051 options: ISchedulerOptions = {},3052 ) {3053 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3054 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3055 }30563057 scheduleAfter<T extends UniqueHelper>(3058 scheduledId: string,3059 blocksBeforeExecution: number,3060 options: ISchedulerOptions = {},3061 ) {3062 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3063 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3064 }30653066 getSudo<T extends UniqueHelper>() {3067 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3068 }3069}307030713072export class UniqueNFTCollection extends UniqueBaseCollection {3073 getTokenObject(tokenId: number) {3074 return new UniqueNFToken(tokenId, this);3075 }30763077 async getTokensByAddress(addressObj: ICrossAccountId) {3078 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3079 }30803081 async getToken(tokenId: number, blockHashAt?: string) {3082 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3083 }30843085 async getTokenOwner(tokenId: number, blockHashAt?: string) {3086 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3087 }30883089 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3090 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3091 }30923093 async getTokenChildren(tokenId: number, blockHashAt?: string) {3094 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3095 }30963097 async getPropertyPermissions(propertyKeys: string[] | null = null) {3098 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3099 }31003101 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3102 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3103 }31043105 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3106 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3107 }31083109 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3110 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3111 }31123113 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3114 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3115 }31163117 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3118 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3119 }31203121 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3122 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3123 }31243125 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3126 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3127 }31283129 async burnToken(signer: TSigner, tokenId: number) {3130 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3131 }31323133 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3134 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3135 }31363137 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3138 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3139 }31403141 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3142 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3143 }31443145 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3146 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3147 }31483149 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3150 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3151 }31523153 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3154 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3155 }31563157 scheduleAt<T extends UniqueHelper>(3158 scheduledId: string,3159 executionBlockNumber: number,3160 options: ISchedulerOptions = {},3161 ) {3162 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3163 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3164 }31653166 scheduleAfter<T extends UniqueHelper>(3167 scheduledId: string,3168 blocksBeforeExecution: number,3169 options: ISchedulerOptions = {},3170 ) {3171 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3172 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3173 }31743175 getSudo<T extends UniqueHelper>() {3176 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3177 }3178}317931803181export class UniqueRFTCollection extends UniqueBaseCollection {3182 getTokenObject(tokenId: number) {3183 return new UniqueRFToken(tokenId, this);3184 }31853186 async getToken(tokenId: number, blockHashAt?: string) {3187 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3188 }31893190 async getTokensByAddress(addressObj: ICrossAccountId) {3191 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3192 }31933194 async getTop10TokenOwners(tokenId: number) {3195 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3196 }31973198 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3199 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3200 }32013202 async getTokenTotalPieces(tokenId: number) {3203 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3204 }32053206 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3207 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3208 }32093210 async getPropertyPermissions(propertyKeys: string[] | null = null) {3211 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3212 }32133214 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3215 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3216 }32173218 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3219 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3220 }32213222 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3223 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3224 }32253226 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3227 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3228 }32293230 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3231 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3232 }32333234 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3235 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3236 }32373238 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3239 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3240 }32413242 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3243 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3244 }32453246 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3247 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3248 }32493250 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3251 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3252 }32533254 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3255 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3256 }32573258 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3259 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3260 }32613262 scheduleAt<T extends UniqueHelper>(3263 scheduledId: string,3264 executionBlockNumber: number,3265 options: ISchedulerOptions = {},3266 ) {3267 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3268 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3269 }32703271 scheduleAfter<T extends UniqueHelper>(3272 scheduledId: string,3273 blocksBeforeExecution: number,3274 options: ISchedulerOptions = {},3275 ) {3276 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3277 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3278 }32793280 getSudo<T extends UniqueHelper>() {3281 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3282 }3283}328432853286export class UniqueFTCollection extends UniqueBaseCollection {3287 async getBalance(addressObj: ICrossAccountId) {3288 return await this.helper.ft.getBalance(this.collectionId, addressObj);3289 }32903291 async getTotalPieces() {3292 return await this.helper.ft.getTotalPieces(this.collectionId);3293 }32943295 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3296 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3297 }32983299 async getTop10Owners() {3300 return await this.helper.ft.getTop10Owners(this.collectionId);3301 }33023303 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3304 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3305 }33063307 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3308 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3309 }33103311 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3312 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3313 }33143315 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3316 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3317 }33183319 async burnTokens(signer: TSigner, amount=1n) {3320 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3321 }33223323 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3324 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3325 }33263327 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3328 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3329 }33303331 scheduleAt<T extends UniqueHelper>(3332 scheduledId: string,3333 executionBlockNumber: number,3334 options: ISchedulerOptions = {},3335 ) {3336 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3337 return new UniqueFTCollection(this.collectionId, scheduledHelper);3338 }33393340 scheduleAfter<T extends UniqueHelper>(3341 scheduledId: string,3342 blocksBeforeExecution: number,3343 options: ISchedulerOptions = {},3344 ) {3345 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3346 return new UniqueFTCollection(this.collectionId, scheduledHelper);3347 }33483349 getSudo<T extends UniqueHelper>() {3350 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3351 }3352}335333543355export class UniqueBaseToken {3356 collection: UniqueNFTCollection | UniqueRFTCollection;3357 collectionId: number;3358 tokenId: number;33593360 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3361 this.collection = collection;3362 this.collectionId = collection.collectionId;3363 this.tokenId = tokenId;3364 }33653366 async getNextSponsored(addressObj: ICrossAccountId) {3367 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3368 }33693370 async getProperties(propertyKeys?: string[] | null) {3371 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3372 }33733374 async setProperties(signer: TSigner, properties: IProperty[]) {3375 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3376 }33773378 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3379 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3380 }33813382 async doesExist() {3383 return await this.collection.doesTokenExist(this.tokenId);3384 }33853386 nestingAccount() {3387 return this.collection.helper.util.getTokenAccount(this);3388 }33893390 scheduleAt<T extends UniqueHelper>(3391 scheduledId: string,3392 executionBlockNumber: number,3393 options: ISchedulerOptions = {},3394 ) {3395 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3396 return new UniqueBaseToken(this.tokenId, scheduledCollection);3397 }33983399 scheduleAfter<T extends UniqueHelper>(3400 scheduledId: string,3401 blocksBeforeExecution: number,3402 options: ISchedulerOptions = {},3403 ) {3404 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3405 return new UniqueBaseToken(this.tokenId, scheduledCollection);3406 }34073408 getSudo<T extends UniqueHelper>() {3409 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3410 }3411}341234133414export class UniqueNFToken extends UniqueBaseToken {3415 collection: UniqueNFTCollection;34163417 constructor(tokenId: number, collection: UniqueNFTCollection) {3418 super(tokenId, collection);3419 this.collection = collection;3420 }34213422 async getData(blockHashAt?: string) {3423 return await this.collection.getToken(this.tokenId, blockHashAt);3424 }34253426 async getOwner(blockHashAt?: string) {3427 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3428 }34293430 async getTopmostOwner(blockHashAt?: string) {3431 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3432 }34333434 async getChildren(blockHashAt?: string) {3435 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3436 }34373438 async nest(signer: TSigner, toTokenObj: IToken) {3439 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3440 }34413442 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3443 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3444 }34453446 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3447 return await this.collection.transferToken(signer, this.tokenId, addressObj);3448 }34493450 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3451 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3452 }34533454 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3455 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3456 }34573458 async isApproved(toAddressObj: ICrossAccountId) {3459 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3460 }34613462 async burn(signer: TSigner) {3463 return await this.collection.burnToken(signer, this.tokenId);3464 }34653466 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3467 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3468 }34693470 scheduleAt<T extends UniqueHelper>(3471 scheduledId: string,3472 executionBlockNumber: number,3473 options: ISchedulerOptions = {},3474 ) {3475 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3476 return new UniqueNFToken(this.tokenId, scheduledCollection);3477 }34783479 scheduleAfter<T extends UniqueHelper>(3480 scheduledId: string,3481 blocksBeforeExecution: number,3482 options: ISchedulerOptions = {},3483 ) {3484 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3485 return new UniqueNFToken(this.tokenId, scheduledCollection);3486 }34873488 getSudo<T extends UniqueHelper>() {3489 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3490 }3491}34923493export class UniqueRFToken extends UniqueBaseToken {3494 collection: UniqueRFTCollection;34953496 constructor(tokenId: number, collection: UniqueRFTCollection) {3497 super(tokenId, collection);3498 this.collection = collection;3499 }35003501 async getData(blockHashAt?: string) {3502 return await this.collection.getToken(this.tokenId, blockHashAt);3503 }35043505 async getTop10Owners() {3506 return await this.collection.getTop10TokenOwners(this.tokenId);3507 }35083509 async getBalance(addressObj: ICrossAccountId) {3510 return await this.collection.getTokenBalance(this.tokenId, addressObj);3511 }35123513 async getTotalPieces() {3514 return await this.collection.getTokenTotalPieces(this.tokenId);3515 }35163517 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3518 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3519 }35203521 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3522 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3523 }35243525 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3526 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3527 }35283529 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3530 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3531 }35323533 async repartition(signer: TSigner, amount: bigint) {3534 return await this.collection.repartitionToken(signer, this.tokenId, amount);3535 }35363537 async burn(signer: TSigner, amount=1n) {3538 return await this.collection.burnToken(signer, this.tokenId, amount);3539 }35403541 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3542 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3543 }35443545 scheduleAt<T extends UniqueHelper>(3546 scheduledId: string,3547 executionBlockNumber: number,3548 options: ISchedulerOptions = {},3549 ) {3550 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3551 return new UniqueRFToken(this.tokenId, scheduledCollection);3552 }35533554 scheduleAfter<T extends UniqueHelper>(3555 scheduledId: string,3556 blocksBeforeExecution: number,3557 options: ISchedulerOptions = {},3558 ) {3559 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3560 return new UniqueRFToken(this.tokenId, scheduledCollection);3561 }35623563 getSudo<T extends UniqueHelper>() {3564 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3565 }3566}