difftreelog
Merge pull request #681 from UniqueNetwork/eth_temp_develop
in: master
Eth temp develop
59 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -746,7 +746,9 @@
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223"
dependencies = [
+ "lazy_static",
"memchr",
+ "regex-automata",
]
[[package]]
@@ -1055,6 +1057,16 @@
]
[[package]]
+name = "concat-idents"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b6f90860248d75014b7b103db8fee4f291c07bfb41306cdf77a0a5ab7a10d2f"
+dependencies = [
+ "quote",
+ "syn",
+]
+
+[[package]]
name = "concurrent-queue"
version = "1.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1064,6 +1076,19 @@
]
[[package]]
+name = "console"
+version = "0.15.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c050367d967ced717c04b65d8c619d863ef9292ce0c5760028655a2fb298718c"
+dependencies = [
+ "encode_unicode",
+ "lazy_static",
+ "libc",
+ "terminal_size",
+ "winapi",
+]
+
+[[package]]
name = "const-oid"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1846,9 +1871,9 @@
[[package]]
name = "cxx"
-version = "1.0.79"
+version = "1.0.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f83d0ebf42c6eafb8d7c52f7e5f2d3003b89c7aa4fd2b79229209459a849af8"
+checksum = "19f39818dcfc97d45b03953c1292efc4e80954e1583c4aa770bac1383e2310a4"
dependencies = [
"cc",
"cxxbridge-flags",
@@ -1858,9 +1883,9 @@
[[package]]
name = "cxx-build"
-version = "1.0.79"
+version = "1.0.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07d050484b55975889284352b0ffc2ecbda25c0c55978017c132b29ba0818a86"
+checksum = "3e580d70777c116df50c390d1211993f62d40302881e54d4b79727acb83d0199"
dependencies = [
"cc",
"codespan-reporting",
@@ -1873,15 +1898,15 @@
[[package]]
name = "cxxbridge-flags"
-version = "1.0.79"
+version = "1.0.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "99d2199b00553eda8012dfec8d3b1c75fce747cf27c169a270b3b99e3448ab78"
+checksum = "56a46460b88d1cec95112c8c363f0e2c39afdb237f60583b0b36343bf627ea9c"
[[package]]
name = "cxxbridge-macro"
-version = "1.0.79"
+version = "1.0.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dcb67a6de1f602736dd7eaead0080cf3435df806c61b24b13328db128c58868f"
+checksum = "747b608fecf06b0d72d440f27acc99288207324b793be2c17991839f3d4995ea"
dependencies = [
"proc-macro2",
"quote",
@@ -2140,6 +2165,12 @@
]
[[package]]
+name = "encode_unicode"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
+
+[[package]]
name = "enum-as-inner"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2302,6 +2333,7 @@
name = "evm-coder"
version = "0.1.3"
dependencies = [
+ "concat-idents",
"ethereum",
"evm-coder-procedural",
"evm-core",
@@ -2310,6 +2342,7 @@
"hex-literal",
"impl-trait-for-tuples",
"primitive-types",
+ "similar-asserts",
"sp-std",
]
@@ -3528,9 +3561,9 @@
[[package]]
name = "iana-time-zone-haiku"
-version = "0.1.1"
+version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca"
+checksum = "fde6edd6cef363e9359ed3c98ba64590ba9eecba2293eb5a723ab32aee8926aa"
dependencies = [
"cxx",
"cxx-build",
@@ -5792,7 +5825,7 @@
[[package]]
name = "pallet-common"
-version = "0.1.8"
+version = "0.1.9"
dependencies = [
"ethereum",
"evm-coder",
@@ -6325,7 +6358,7 @@
[[package]]
name = "pallet-nonfungible"
-version = "0.1.5"
+version = "0.1.6"
dependencies = [
"ethereum",
"evm-coder",
@@ -6447,7 +6480,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.2.4"
+version = "0.2.5"
dependencies = [
"derivative",
"ethereum",
@@ -6766,7 +6799,7 @@
[[package]]
name = "pallet-unique"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"ethereum",
"evm-coder",
@@ -10741,9 +10774,9 @@
[[package]]
name = "serde_json"
-version = "1.0.87"
+version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6ce777b7b150d76b9cf60d28b55f5847135a003f7d7350c6be7a773508ce7d45"
+checksum = "41feea4228a6f1cd09ec7a3593a682276702cd67b5273544757dae23c096f074"
dependencies = [
"itoa",
"ryu",
@@ -10886,6 +10919,26 @@
]
[[package]]
+name = "similar"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "62ac7f900db32bf3fd12e0117dd3dc4da74bc52ebaac97f39668446d89694803"
+dependencies = [
+ "bstr",
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "similar-asserts"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbf644ad016b75129f01a34a355dcb8d66a5bc803e417c7a77cc5d5ee9fa0f18"
+dependencies = [
+ "console",
+ "similar",
+]
+
+[[package]]
name = "slab"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -12002,9 +12055,9 @@
[[package]]
name = "syn"
-version = "1.0.103"
+version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d"
+checksum = "3fcd952facd492f9be3ef0d0b7032a6e442ee9b361d4acc2b1d0c4aaa5f613a1"
dependencies = [
"proc-macro2",
"quote",
@@ -12080,6 +12133,16 @@
]
[[package]]
+name = "terminal_size"
+version = "0.1.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df"
+dependencies = [
+ "libc",
+ "winapi",
+]
+
+[[package]]
name = "test-runtime-constants"
version = "0.9.30"
source = "git+https://github.com/paritytech/polkadot?branch=release-v0.9.30#064536093f5ff70d867f4bbce8d4c41a406d317a"
@@ -12660,6 +12723,12 @@
]
[[package]]
+name = "unicode-segmentation"
+version = "1.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fdbf052a0783de01e944a6ce7a8cb939e295b1e7be835a1112c3b9a7f047a5a"
+
+[[package]]
name = "unicode-width"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
crates/evm-coder/Cargo.tomldiffbeforeafterboth--- a/crates/evm-coder/Cargo.toml
+++ b/crates/evm-coder/Cargo.toml
@@ -14,7 +14,7 @@
sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
# Error types for execution
-evm-core = { default-features = false , git = "https://github.com/uniquenetwork/evm", branch = "unique-polkadot-v0.9.30" }
+evm-core = { default-features = false, git = "https://github.com/uniquenetwork/evm", branch = "unique-polkadot-v0.9.30" }
# We have tuple-heavy code in solidity.rs
impl-trait-for-tuples = "0.2.2"
@@ -22,7 +22,14 @@
# 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"
[features]
default = ["std"]
-std = ["ethereum/std", "primitive-types/std", "evm-core/std", "frame-support/std"]
+std = [
+ "ethereum/std",
+ "primitive-types/std",
+ "evm-core/std",
+ "frame-support/std",
+]
crates/evm-coder/src/abi.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi.rs
+++ b/crates/evm-coder/src/abi.rs
@@ -25,14 +25,18 @@
use crate::{
execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},
- types::{string, self},
+ types::*,
};
use crate::execution::Result;
const ABI_ALIGNMENT: usize = 32;
trait TypeHelper {
+ /// Is type dynamic sized.
fn is_dynamic() -> bool;
+
+ /// Size for type aligned to [`ABI_ALIGNMENT`].
+ fn size() -> usize;
}
/// View into RLP data, which provides method to read typed items from it
@@ -52,7 +56,7 @@
}
}
/// Start reading RLP buffer, parsing first 4 bytes as selector
- pub fn new_call(buf: &'i [u8]) -> Result<(types::bytes4, Self)> {
+ pub fn new_call(buf: &'i [u8]) -> Result<(bytes4, Self)> {
if buf.len() < 4 {
return Err(Error::Error(ExitError::OutOfOffset));
}
@@ -218,12 +222,21 @@
static_part: Vec<u8>,
dynamic_part: Vec<(usize, AbiWriter)>,
had_call: bool,
+ is_dynamic: bool,
}
impl AbiWriter {
/// Initialize internal buffers for output data, assuming no padding required
pub fn new() -> Self {
Self::default()
}
+
+ /// Initialize internal buffers with data size
+ pub fn new_dynamic(is_dynamic: bool) -> Self {
+ Self {
+ is_dynamic,
+ ..Default::default()
+ }
+ }
/// Initialize internal buffers, inserting method selector at beginning
pub fn new_call(method_id: u32) -> Self {
let mut val = Self::new();
@@ -239,11 +252,11 @@
self.static_part.extend(block);
}
- fn write_padright(&mut self, bytes: &[u8]) {
- assert!(bytes.len() <= ABI_ALIGNMENT);
- self.static_part.extend(bytes);
+ fn write_padright(&mut self, block: &[u8]) {
+ assert!(block.len() <= ABI_ALIGNMENT);
+ self.static_part.extend(block);
self.static_part
- .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - bytes.len()]);
+ .extend(&[0; ABI_ALIGNMENT][0..ABI_ALIGNMENT - block.len()]);
}
/// Write [`H160`] to end of buffer
@@ -313,12 +326,14 @@
/// Finish writer, concatenating all internal buffers
pub fn finish(mut self) -> Vec<u8> {
for (static_offset, part) in self.dynamic_part {
- let part_offset = self.static_part.len() - if self.had_call { 4 } else { 0 };
+ let part_offset = self.static_part.len()
+ - if self.had_call { 4 } else { 0 }
+ - if self.is_dynamic { ABI_ALIGNMENT } else { 0 };
let encoded_dynamic_offset = usize::to_be_bytes(part_offset);
- self.static_part[static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len()
- ..static_offset + ABI_ALIGNMENT]
- .copy_from_slice(&encoded_dynamic_offset);
+ let start = static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len();
+ let stop = static_offset + ABI_ALIGNMENT;
+ self.static_part[start..stop].copy_from_slice(&encoded_dynamic_offset);
self.static_part.extend(part.finish())
}
self.static_part
@@ -333,9 +348,6 @@
pub trait AbiRead<T> {
/// Read item from current position, advanding decoder
fn abi_read(&mut self) -> Result<T>;
-
- /// Size for type aligned to [`ABI_ALIGNMENT`].
- fn size() -> usize;
}
macro_rules! impl_abi_readable {
@@ -344,29 +356,43 @@
fn is_dynamic() -> bool {
$dynamic
}
+
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
}
impl AbiRead<$ty> for AbiReader<'_> {
fn abi_read(&mut self) -> Result<$ty> {
self.$method()
- }
-
- fn size() -> usize {
- ABI_ALIGNMENT
}
}
};
}
-impl_abi_readable!(u8, uint8, false);
-impl_abi_readable!(u32, uint32, false);
-impl_abi_readable!(u64, uint64, false);
-impl_abi_readable!(u128, uint128, false);
-impl_abi_readable!(U256, uint256, false);
-impl_abi_readable!([u8; 4], bytes4, false);
-impl_abi_readable!(H160, address, false);
-impl_abi_readable!(Vec<u8>, bytes, true);
-impl_abi_readable!(bool, bool, true);
+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);
+impl_abi_readable!(uint256, uint256, false);
+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 bytes {
+ fn is_dynamic() -> bool {
+ true
+ }
+ fn size() -> usize {
+ ABI_ALIGNMENT
+ }
+}
+impl AbiRead<bytes> for AbiReader<'_> {
+ fn abi_read(&mut self) -> Result<bytes> {
+ Ok(bytes(self.bytes()?))
+ }
+}
mod sealed {
/// Not all types can be placed in vec, i.e `Vec<u8>` is restricted, `bytes` should be used instead
@@ -390,22 +416,27 @@
out.push(<Self as AbiRead<R>>::abi_read(&mut sub)?);
}
Ok(out)
- }
-
- fn size() -> usize {
- ABI_ALIGNMENT
}
}
macro_rules! impl_tuples {
($($ident:ident)+) => {
- impl<$($ident: TypeHelper,)+> TypeHelper for ($($ident,)+) {
+ impl<$($ident: TypeHelper,)+> TypeHelper for ($($ident,)+)
+ where
+ $(
+ $ident: TypeHelper,
+ )+
+ {
fn is_dynamic() -> bool {
false
$(
|| <$ident>::is_dynamic()
)*
}
+
+ fn size() -> usize {
+ 0 $(+ <$ident>::size())+
+ }
}
impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}
impl<$($ident),+> AbiRead<($($ident,)+)> for AbiReader<'_>
@@ -416,25 +447,27 @@
($($ident,)+): TypeHelper,
{
fn abi_read(&mut self) -> Result<($($ident,)+)> {
- let size = if !<($($ident,)+)>::is_dynamic() { Some(<Self as AbiRead<($($ident,)+)>>::size()) } else { None };
+ let size = if !<($($ident,)+)>::is_dynamic() { Some(<($($ident,)+)>::size()) } else { None };
let mut subresult = self.subresult(size)?;
Ok((
$(<Self as AbiRead<$ident>>::abi_read(&mut subresult)?,)+
))
- }
-
- fn size() -> usize {
- 0 $(+ <AbiReader<'_> as AbiRead<$ident>>::size())+
}
}
#[allow(non_snake_case)]
- impl<$($ident),+> AbiWrite for &($($ident,)+)
+ impl<$($ident),+> AbiWrite for ($($ident,)+)
where
$($ident: AbiWrite,)+
{
fn abi_write(&self, writer: &mut AbiWriter) {
let ($($ident,)+) = self;
- $($ident.abi_write(writer);)+
+ if writer.is_dynamic {
+ let mut sub = AbiWriter::new();
+ $($ident.abi_write(&mut sub);)+
+ writer.write_subresult(sub);
+ } else {
+ $($ident.abi_write(writer);)+
+ }
}
}
};
@@ -505,14 +538,35 @@
impl_abi_writeable!(H160, address);
impl_abi_writeable!(bool, bool);
impl_abi_writeable!(&str, string);
-impl AbiWrite for &string {
+
+impl AbiWrite for string {
fn abi_write(&self, writer: &mut AbiWriter) {
writer.string(self)
}
}
-impl AbiWrite for &Vec<u8> {
+
+impl AbiWrite for bytes {
+ fn abi_write(&self, writer: &mut AbiWriter) {
+ writer.bytes(self.0.as_slice())
+ }
+}
+
+impl<T: AbiWrite + TypeHelper> AbiWrite for Vec<T> {
fn abi_write(&self, writer: &mut AbiWriter) {
- writer.bytes(self)
+ let is_dynamic = T::is_dynamic();
+ let mut sub = if is_dynamic {
+ AbiWriter::new_dynamic(is_dynamic)
+ } else {
+ AbiWriter::new()
+ };
+
+ // Write items count
+ (self.len() as u32).abi_write(&mut sub);
+
+ for item in self {
+ item.abi_write(&mut sub);
+ }
+ writer.write_subresult(sub);
}
}
@@ -556,13 +610,145 @@
#[cfg(test)]
pub mod test {
use crate::{
- abi::AbiRead,
- types::{string, uint256},
+ abi::{AbiRead, AbiWrite},
+ types::*,
};
use super::{AbiReader, AbiWriter};
use hex_literal::hex;
+ use primitive_types::{H160, U256};
+ use concat_idents::concat_idents;
+
+ macro_rules! test_impl {
+ ($name:ident, $type:ty, $function_identifier:expr, $decoded_data:expr, $encoded_data:expr) => {
+ concat_idents!(test_name = encode_decode_, $name {
+ #[test]
+ fn test_name() {
+ let function_identifier: u32 = $function_identifier;
+ let decoded_data = $decoded_data;
+ let encoded_data = $encoded_data;
+
+ 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();
+ assert_eq!(data, decoded_data);
+
+ let mut writer = AbiWriter::new_call(function_identifier);
+ decoded_data.abi_write(&mut writer);
+ let ed = writer.finish();
+ similar_asserts::assert_eq!(encoded_data, ed.as_slice());
+ }
+ });
+ };
+ }
+
+ macro_rules! test_impl_uint {
+ ($type:ident) => {
+ test_impl!(
+ $type,
+ $type,
+ 0xdeadbeef,
+ 255 as $type,
+ &hex!(
+ "
+ deadbeef
+ 00000000000000000000000000000000000000000000000000000000000000ff
+ "
+ )
+ );
+ };
+ }
+
+ test_impl_uint!(uint8);
+ test_impl_uint!(uint32);
+ test_impl_uint!(uint128);
+
+ test_impl!(
+ uint256,
+ uint256,
+ 0xdeadbeef,
+ U256([255, 0, 0, 0]),
+ &hex!(
+ "
+ deadbeef
+ 00000000000000000000000000000000000000000000000000000000000000ff
+ "
+ )
+ );
+
+ test_impl!(
+ vec_tuple_address_uint256,
+ Vec<(address, uint256)>,
+ 0x1ACF2D55,
+ vec![
+ (
+ H160(hex!("2D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC")),
+ U256([10, 0, 0, 0]),
+ ),
+ (
+ H160(hex!("AB8E3D9134955566483B11E6825C9223B6737B10")),
+ U256([20, 0, 0, 0]),
+ ),
+ (
+ H160(hex!("8C582BDF2953046705FC56F189385255EFC1BE18")),
+ U256([30, 0, 0, 0]),
+ ),
+ ],
+ &hex!(
+ "
+ 1ACF2D55
+ 0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
+ 0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
+
+ 0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
+ 000000000000000000000000000000000000000000000000000000000000000A // uint256
+
+ 000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
+ 0000000000000000000000000000000000000000000000000000000000000014 // uint256
+
+ 0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
+ 000000000000000000000000000000000000000000000000000000000000001E // uint256
+ "
+ )
+ );
+
+ test_impl!(
+ vec_tuple_uint256_string,
+ Vec<(uint256, string)>,
+ 0xdeadbeef,
+ vec![
+ (1.into(), "Test URI 0".to_string()),
+ (11.into(), "Test URI 1".to_string()),
+ (12.into(), "Test URI 2".to_string()),
+ ],
+ &hex!(
+ "
+ deadbeef
+ 0000000000000000000000000000000000000000000000000000000000000020 // offset of (uint256, string)[]
+ 0000000000000000000000000000000000000000000000000000000000000003 // length of (uint256, string)[]
+
+ 0000000000000000000000000000000000000000000000000000000000000060 // offset of first elem
+ 00000000000000000000000000000000000000000000000000000000000000e0 // offset of second elem
+ 0000000000000000000000000000000000000000000000000000000000000160 // offset of third elem
+
+ 0000000000000000000000000000000000000000000000000000000000000001 // first token id? #60
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203000000000000000000000000000000000000000000000 // string
+
+ 000000000000000000000000000000000000000000000000000000000000000b // second token id? Why ==11? #e0
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203100000000000000000000000000000000000000000000 // string
+ 000000000000000000000000000000000000000000000000000000000000000c // third token id? Why ==12? #160
+ 0000000000000000000000000000000000000000000000000000000000000040 // offset of string
+ 000000000000000000000000000000000000000000000000000000000000000a // size of string
+ 5465737420555249203200000000000000000000000000000000000000000000 // string
+ "
+ )
+ );
+
#[test]
fn dynamic_after_static() {
let mut encoder = AbiWriter::new();
@@ -609,8 +795,17 @@
}
#[test]
- fn mint_bulk() {
- let (call, mut decoder) = AbiReader::new_call(&hex!(
+ fn parse_vec_with_dynamic_type() {
+ let decoded_data = (
+ 0x36543006,
+ vec![
+ (1.into(), "Test URI 0".to_string()),
+ (11.into(), "Test URI 1".to_string()),
+ (12.into(), "Test URI 2".to_string()),
+ ],
+ );
+
+ let encoded_data = &hex!(
"
36543006
00000000000000000000000053744e6da587ba10b32a2554d2efdcd985bc27a3 // address
@@ -636,64 +831,19 @@
000000000000000000000000000000000000000000000000000000000000000a // size of string
5465737420555249203200000000000000000000000000000000000000000000 // string
"
- ))
- .unwrap();
- assert_eq!(call, u32::to_be_bytes(0x36543006));
- let _ = decoder.address().unwrap();
+ );
+
+ 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();
- assert_eq!(
- data,
- vec![
- (1.into(), "Test URI 0".to_string()),
- (11.into(), "Test URI 1".to_string()),
- (12.into(), "Test URI 2".to_string())
- ]
- );
- }
+ assert_eq!(data, decoded_data.1);
- #[test]
- fn parse_vec_with_simple_type() {
- use crate::types::address;
- use primitive_types::{H160, U256};
-
- let (call, mut decoder) = AbiReader::new_call(&hex!(
- "
- 1ACF2D55
- 0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
- 0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
-
- 0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
- 000000000000000000000000000000000000000000000000000000000000000A // uint256
-
- 000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
- 0000000000000000000000000000000000000000000000000000000000000014 // uint256
-
- 0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
- 000000000000000000000000000000000000000000000000000000000000001E // uint256
- "
- ))
- .unwrap();
- assert_eq!(call, u32::to_be_bytes(0x1ACF2D55));
- let data =
- <AbiReader<'_> as AbiRead<Vec<(address, uint256)>>>::abi_read(&mut decoder).unwrap();
- assert_eq!(data.len(), 3);
- assert_eq!(
- data,
- vec![
- (
- H160(hex!("2D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC")),
- U256([10, 0, 0, 0])
- ),
- (
- H160(hex!("AB8E3D9134955566483B11E6825C9223B6737B10")),
- U256([20, 0, 0, 0])
- ),
- (
- H160(hex!("8C582BDF2953046705FC56F189385255EFC1BE18")),
- U256([30, 0, 0, 0])
- ),
- ]
- );
+ let mut writer = AbiWriter::new_call(decoded_data.0);
+ address.abi_write(&mut writer);
+ decoded_data.1.abi_write(&mut writer);
+ let ed = writer.finish();
+ similar_asserts::assert_eq!(encoded_data, ed.as_slice());
}
}
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -133,8 +133,10 @@
pub type string = ::alloc::string::String;
#[cfg(feature = "std")]
pub type string = ::std::string::String;
- pub type bytes = Vec<u8>;
+ #[derive(Default, Debug)]
+ pub struct bytes(pub Vec<u8>);
+
/// Solidity doesn't have `void` type, however we have special implementation
/// for empty tuple return type
pub type void = ();
@@ -157,6 +159,30 @@
/// and there is no `receiver()` function defined.
pub value: U256,
}
+
+ impl From<Vec<u8>> for bytes {
+ fn from(src: Vec<u8>) -> Self {
+ Self(src)
+ }
+ }
+
+ impl Into<Vec<u8>> for bytes {
+ fn into(self) -> Vec<u8> {
+ self.0
+ }
+ }
+
+ impl bytes {
+ #[must_use]
+ pub fn len(&self) -> usize {
+ self.0.len()
+ }
+
+ #[must_use]
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+ }
}
/// Parseable EVM call, this trait should be implemented with [`solidity_interface`] macro
crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -154,8 +154,10 @@
fn is_simple() -> bool {
false
}
- fn solidity_default(writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {
- write!(writer, "[]")
+ fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
+ write!(writer, "new ")?;
+ T::solidity_name(writer, tc)?;
+ write!(writer, "[](0)")
}
}
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -33,12 +33,12 @@
// limitations under the License.
use crate::{
- chain_spec::{
- self, RuntimeId, RuntimeIdentification, ServiceId, ServiceIdentification, default_runtime,
- },
+ chain_spec::{self, RuntimeId, RuntimeIdentification, ServiceId, ServiceIdentification},
cli::{Cli, RelayChainCli, Subcommand},
service::{new_partial, start_node, start_dev_node},
};
+#[cfg(feature = "runtime-benchmarks")]
+use crate::chain_spec::default_runtime;
#[cfg(feature = "unique-runtime")]
use crate::service::UniqueRuntimeExecutor;
@@ -46,7 +46,10 @@
#[cfg(feature = "quartz-runtime")]
use crate::service::QuartzRuntimeExecutor;
-use crate::service::{OpalRuntimeExecutor, DefaultRuntimeExecutor};
+use crate::service::OpalRuntimeExecutor;
+
+#[cfg(feature = "runtime-benchmarks")]
+use crate::service::DefaultRuntimeExecutor;
use codec::Encode;
use cumulus_primitives_core::ParaId;
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -46,7 +46,6 @@
use cumulus_relay_chain_rpc_interface::{RelayChainRpcInterface, create_client_and_start_worker};
// Substrate Imports
-use sc_client_api::ExecutorProvider;
use sc_executor::NativeElseWasmExecutor;
use sc_executor::NativeExecutionDispatch;
use sc_network::{NetworkService, NetworkBlock};
@@ -84,13 +83,21 @@
/// Opal native executor instance.
pub struct OpalRuntimeExecutor;
-#[cfg(feature = "unique-runtime")]
+#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]
pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;
-#[cfg(all(not(feature = "unique-runtime"), feature = "quartz-runtime"))]
+#[cfg(all(
+ not(feature = "unique-runtime"),
+ feature = "quartz-runtime",
+ feature = "runtime-benchmarks"
+))]
pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;
-#[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]
+#[cfg(all(
+ not(feature = "unique-runtime"),
+ not(feature = "quartz-runtime"),
+ feature = "runtime-benchmarks"
+))]
pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;
#[cfg(feature = "unique-runtime")]
pallets/common/CHANGELOG.mddiffbeforeafterboth--- a/pallets/common/CHANGELOG.md
+++ b/pallets/common/CHANGELOG.md
@@ -2,29 +2,37 @@
All notable changes to this project will be documented in this file.
+## [0.1.9] - 2022-10-13
+
+## Added
+
+- EVM event for `destroy_collection`.
+
## [0.1.8] - 2022-08-24
## Added
- - Eth methods for collection
- + set_collection_sponsor_substrate
- + has_collection_pending_sponsor
- + remove_collection_sponsor
- + get_collection_sponsor
+
+- Eth methods for collection
+ - set_collection_sponsor_substrate
+ - has_collection_pending_sponsor
+ - remove_collection_sponsor
+ - get_collection_sponsor
- Add convert function from `uint256` to `CrossAccountId`.
## [0.1.7] - 2022-08-19
### Added
- - Add convert funtion from `CrossAccountId` to eth `uint256`.
+- Add convert funtion from `CrossAccountId` to eth `uint256`.
-
## [0.1.6] - 2022-08-16
### Added
-- New Ethereum API methods: changeOwner, changeOwner(Substrate) and verifyOwnerOrAdmin(Substrate).
+- New Ethereum API methods: changeOwner, changeOwner(Substrate) and verifyOwnerOrAdmin(Substrate).
+
<!-- bureaucrate goes here -->
+
## [v0.1.5] 2022-08-16
### Other changes
@@ -45,19 +53,21 @@
- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
## [0.1.3] - 2022-07-25
+
### Add
-- Some static property keys and values.
+- Some static property keys and values.
+
## [0.1.2] - 2022-07-20
### Fixed
-- Some methods in `#[solidity_interface]` for `CollectionHandle` had invalid
- mutability modifiers, causing invalid stub/abi generation.
+- Some methods in `#[solidity_interface]` for `CollectionHandle` had invalid
+ mutability modifiers, causing invalid stub/abi generation.
## [0.1.1] - 2022-07-14
### Added
- - Implementation of RPC method `token_owners` returning 10 owners in no particular order.
- This was an internal request to improve the web interface and support fractionalization event.
+- Implementation of RPC method `token_owners` returning 10 owners in no particular order.
+ This was an internal request to improve the web interface and support fractionalization event.
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.8"
+version = "0.1.9"
license = "GPLv3"
edition = "2021"
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -34,8 +34,8 @@
use crate::{
Pallet, CollectionHandle, Config, CollectionProperties, SelfWeightOf,
eth::{
- convert_cross_account_to_uint256, convert_uint256_to_cross_account,
- convert_cross_account_to_tuple,
+ convert_cross_account_to_uint256, convert_cross_account_to_tuple,
+ convert_tuple_to_cross_account,
},
weights::WeightInfo,
};
@@ -53,6 +53,12 @@
#[indexed]
collection_id: address,
},
+ /// The collection has been destroyed.
+ CollectionDestroyed {
+ /// Collection ID.
+ #[indexed]
+ collection_id: address,
+ },
}
/// Does not always represent a full collection, for RFT it is either
@@ -85,19 +91,45 @@
let key = <Vec<u8>>::from(key)
.try_into()
.map_err(|_| "key too large")?;
- let value = value.try_into().map_err(|_| "value too large")?;
+ let value = value.0.try_into().map_err(|_| "value too large")?;
<Pallet<T>>::set_collection_property(self, &caller, Property { key, value })
.map_err(dispatch_to_evm::<T>)
}
+ /// Set collection properties.
+ ///
+ /// @param properties Vector of properties key/value pair.
+ #[weight(<SelfWeightOf<T>>::set_collection_properties(properties.len() as u32))]
+ fn set_collection_properties(
+ &mut self,
+ caller: caller,
+ properties: Vec<(string, bytes)>,
+ ) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+
+ let properties = properties
+ .into_iter()
+ .map(|(key, value)| {
+ let key = <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "key too large")?;
+
+ let value = value.0.try_into().map_err(|_| "value too large")?;
+
+ Ok(Property { key, value })
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ <Pallet<T>>::set_collection_properties(self, &caller, properties)
+ .map_err(dispatch_to_evm::<T>)
+ }
+
/// Delete collection property.
///
/// @param key Property key.
#[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]
fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {
- self.consume_store_reads_and_writes(1, 1)?;
-
let caller = T::CrossAccountId::from_eth(caller);
let key = <Vec<u8>>::from(key)
.try_into()
@@ -106,6 +138,24 @@
<Pallet<T>>::delete_collection_property(self, &caller, key).map_err(dispatch_to_evm::<T>)
}
+ /// Delete collection properties.
+ ///
+ /// @param keys Properties keys.
+ #[weight(<SelfWeightOf<T>>::delete_collection_properties(keys.len() as u32))]
+ fn delete_collection_properties(&mut self, caller: caller, keys: Vec<string>) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let keys = keys
+ .into_iter()
+ .map(|key| {
+ <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| Error::Revert("key too large".into()))
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ <Pallet<T>>::delete_collection_properties(self, &caller, keys).map_err(dispatch_to_evm::<T>)
+ }
+
/// Get collection property.
///
/// @dev Throws error if key not found.
@@ -117,12 +167,44 @@
.try_into()
.map_err(|_| "key too large")?;
- let props = <CollectionProperties<T>>::get(self.id);
+ let props = CollectionProperties::<T>::get(self.id);
let prop = props.get(&key).ok_or("key not found")?;
- Ok(prop.to_vec())
+ Ok(bytes(prop.to_vec()))
}
+ /// Get collection properties.
+ ///
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @return Vector of properties key/value pairs.
+ fn collection_properties(&self, keys: Vec<string>) -> Result<Vec<(string, bytes)>> {
+ let keys = keys
+ .into_iter()
+ .map(|key| {
+ <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| Error::Revert("key too large".into()))
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ let properties = Pallet::<T>::filter_collection_properties(
+ self.id,
+ if keys.is_empty() { None } else { Some(keys) },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+
+ let properties = properties
+ .into_iter()
+ .map(|p| {
+ let key =
+ string::from_utf8(p.key.into()).map_err(|e| Error::Revert(format!("{}", e)))?;
+ let value = bytes(p.value.to_vec());
+ Ok((key, value))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Ok(properties)
+ }
+
/// Set the sponsor of the collection.
///
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
@@ -139,26 +221,25 @@
save(self)
}
- // TODO: Temprorary off. Need refactor
- // /// Set the substrate sponsor of the collection.
- // ///
- // /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
- // ///
- // /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
- // fn set_collection_sponsor_substrate(
- // &mut self,
- // caller: caller,
- // sponsor: uint256,
- // ) -> Result<void> {
- // self.consume_store_reads_and_writes(1, 1)?;
+ /// Set the sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
+ fn set_collection_sponsor_cross(
+ &mut self,
+ caller: caller,
+ sponsor: (address, uint256),
+ ) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
- // check_is_owner_or_admin(caller, self)?;
+ check_is_owner_or_admin(caller, self)?;
- // let sponsor = convert_uint256_to_cross_account::<T>(sponsor);
- // self.set_sponsor(sponsor.as_sub().clone())
- // .map_err(dispatch_to_evm::<T>)?;
- // save(self)
- // }
+ let sponsor = convert_tuple_to_cross_account::<T>(sponsor)?;
+ self.set_sponsor(sponsor.as_sub().clone())
+ .map_err(dispatch_to_evm::<T>)?;
+ save(self)
+ }
/// Whether there is a pending sponsor.
fn has_collection_pending_sponsor(&self) -> Result<bool> {
@@ -300,37 +381,35 @@
Ok(crate::eth::collection_id_to_address(self.id))
}
- // TODO: Temprorary off. Need refactor
- // /// Add collection admin by substrate address.
- // /// @param newAdmin Substrate administrator address.
- // fn add_collection_admin_substrate(
- // &mut self,
- // caller: caller,
- // new_admin: uint256,
- // ) -> Result<void> {
- // self.consume_store_writes(2)?;
+ /// Add collection admin.
+ /// @param newAdmin Cross account administrator address.
+ fn add_collection_admin_cross(
+ &mut self,
+ caller: caller,
+ new_admin: (address, uint256),
+ ) -> Result<void> {
+ self.consume_store_writes(2)?;
- // let caller = T::CrossAccountId::from_eth(caller);
- // let new_admin = convert_uint256_to_cross_account::<T>(new_admin);
- // <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
- // Ok(())
- // }
+ let caller = T::CrossAccountId::from_eth(caller);
+ let new_admin = convert_tuple_to_cross_account::<T>(new_admin)?;
+ <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
- // TODO: Temprorary off. Need refactor
- // /// Remove collection admin by substrate address.
- // /// @param admin Substrate administrator address.
- // fn remove_collection_admin_substrate(
- // &mut self,
- // caller: caller,
- // admin: uint256,
- // ) -> Result<void> {
- // self.consume_store_writes(2)?;
+ /// Remove collection admin.
+ /// @param admin Cross account administrator address.
+ fn remove_collection_admin_cross(
+ &mut self,
+ caller: caller,
+ admin: (address, uint256),
+ ) -> Result<void> {
+ self.consume_store_writes(2)?;
- // let caller = T::CrossAccountId::from_eth(caller);
- // let admin = convert_uint256_to_cross_account::<T>(admin);
- // <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
- // Ok(())
- // }
+ let caller = T::CrossAccountId::from_eth(caller);
+ let admin = convert_tuple_to_cross_account::<T>(admin)?;
+ <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
/// Add collection admin.
/// @param newAdmin Address of the added administrator.
@@ -479,22 +558,21 @@
Ok(())
}
- // TODO: Temprorary off. Need refactor
- // /// Add substrate user to allowed list.
- // ///
- // /// @param user User substrate address.
- // fn add_to_collection_allow_list_substrate(
- // &mut self,
- // caller: caller,
- // user: uint256,
- // ) -> Result<void> {
- // self.consume_store_writes(1)?;
+ /// Add user to allowed list.
+ ///
+ /// @param user User cross account address.
+ fn add_to_collection_allow_list_cross(
+ &mut self,
+ caller: caller,
+ user: (address, uint256),
+ ) -> Result<void> {
+ self.consume_store_writes(1)?;
- // let caller = T::CrossAccountId::from_eth(caller);
- // let user = convert_uint256_to_cross_account::<T>(user);
- // Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
- // Ok(())
- // }
+ let caller = T::CrossAccountId::from_eth(caller);
+ let user = convert_tuple_to_cross_account::<T>(user)?;
+ Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
/// Remove the user from the allowed list.
///
@@ -508,22 +586,21 @@
Ok(())
}
- // TODO: Temprorary off. Need refactor
- // /// Remove substrate user from allowed list.
- // ///
- // /// @param user User substrate address.
- // fn remove_from_collection_allow_list_substrate(
- // &mut self,
- // caller: caller,
- // user: uint256,
- // ) -> Result<void> {
- // self.consume_store_writes(1)?;
+ /// Remove user from allowed list.
+ ///
+ /// @param user User cross account address.
+ fn remove_from_collection_allow_list_cross(
+ &mut self,
+ caller: caller,
+ user: (address, uint256),
+ ) -> Result<void> {
+ self.consume_store_writes(1)?;
- // let caller = T::CrossAccountId::from_eth(caller);
- // let user = convert_uint256_to_cross_account::<T>(user);
- // Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
- // Ok(())
- // }
+ let caller = T::CrossAccountId::from_eth(caller);
+ let user = convert_tuple_to_cross_account::<T>(user)?;
+ Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
/// Switch permission for minting.
///
@@ -556,15 +633,14 @@
Ok(self.is_owner_or_admin(&user))
}
- // TODO: Temprorary off. Need refactor
- // /// Check that substrate account is the owner or admin of the collection
- // ///
- // /// @param user account to verify
- // /// @return "true" if account is the owner or admin
- // fn is_owner_or_admin_substrate(&self, user: uint256) -> Result<bool> {
- // let user = convert_uint256_to_cross_account::<T>(user);
- // Ok(self.is_owner_or_admin(&user))
- // }
+ /// Check that account is the owner or admin of the collection
+ ///
+ /// @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)?;
+ Ok(self.is_owner_or_admin(&user))
+ }
/// Returns collection type
///
@@ -580,7 +656,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple 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>(
@@ -602,27 +678,29 @@
.map_err(dispatch_to_evm::<T>)
}
- // TODO: Temprorary off. Need refactor
- // /// Changes collection owner to another substrate account
- // ///
- // /// @dev Owner can be changed only by current owner
- // /// @param newOwner new owner substrate account
- // fn set_owner_substrate(&mut self, caller: caller, new_owner: uint256) -> Result<void> {
- // self.consume_store_writes(1)?;
+ /// Get collection administrators
+ ///
+ /// @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)>> {
+ let result = crate::IsAdmin::<T>::iter_prefix((self.id,))
+ .map(|(admin, _)| crate::eth::convert_cross_account_to_tuple::<T>(&admin))
+ .collect();
+ Ok(result)
+ }
- // let caller = T::CrossAccountId::from_eth(caller);
- // let new_owner = convert_uint256_to_cross_account::<T>(new_owner);
- // self.set_owner_internal(caller, new_owner)
- // .map_err(dispatch_to_evm::<T>)
- // }
+ /// Changes collection owner to another account
+ ///
+ /// @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> {
+ self.consume_store_writes(1)?;
- // TODO: need implement AbiWriter for &Vec<T>
- // fn collection_admins(&self) -> Result<Vec<(address, uint256)>> {
- // let result = pallet_common::IsAdmin::<T>::iter_prefix((self.id,))
- // .map(|(admin, _)| pallet_common::eth::convert_cross_account_to_tuple::<T>(&admin))
- // .collect();
- // Ok(result)
- // }
+ let caller = T::CrossAccountId::from_eth(caller);
+ let new_owner = convert_tuple_to_cross_account::<T>(new_owner)?;
+ self.set_owner_internal(caller, new_owner)
+ .map_err(dispatch_to_evm::<T>)
+ }
}
/// ### Note
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -85,3 +85,27 @@
(eth, Default::default())
}
}
+
+/// Convert tuple `(address, uint256)` to `CrossAccountId`.
+///
+/// If `address` in the tuple has *default* value, then the canonical form is substrate,
+/// if `uint256` has *default* value, then the ethereum form is canonical,
+/// if both values are *default* or *non default*, then this is considered an invalid address and `Error` is returned.
+pub fn convert_tuple_to_cross_account<T: Config>(
+ eth_cross_account_id: (address, uint256),
+) -> evm_coder::execution::Result<T::CrossAccountId>
+where
+ T::AccountId: From<[u8; 32]>,
+{
+ if eth_cross_account_id == Default::default() {
+ Err("All fields of cross account is zeroed".into())
+ } else if eth_cross_account_id.0 == Default::default() {
+ Ok(convert_uint256_to_cross_account::<T>(
+ eth_cross_account_id.1,
+ ))
+ } else if eth_cross_account_id.1 == Default::default() {
+ Ok(T::CrossAccountId::from_eth(eth_cross_account_id.0))
+ } else {
+ Err("All fields of cross account is non zeroed".into())
+ }
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -999,6 +999,13 @@
<CollectionProperties<T>>::remove(collection.id);
<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));
+
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionDestroyed {
+ collection_id: eth::collection_id_to_address(collection.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
Ok(())
}
pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -19,6 +19,7 @@
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;
@@ -149,7 +150,26 @@
}
#[solidity_interface(name = ERC20UniqueExtensions)]
-impl<T: Config> FungibleHandle<T> {
+impl<T: Config> FungibleHandle<T>
+where
+ T::AccountId: From<[u8; 32]>,
+{
+ #[weight(<SelfWeightOf<T>>::approve())]
+ fn approve_cross(
+ &mut self,
+ caller: caller,
+ spender: (address, uint256),
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let spender = convert_tuple_to_cross_account::<T>(spender)?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+ <Pallet<T>>::set_allowance(self, &caller, &spender, amount)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
/// Burn tokens from account
/// @dev Function that burns an `amount` of the tokens of a given account,
/// deducting from the sender's allowance for said account.
@@ -169,6 +189,30 @@
Ok(true)
}
+ /// Burn tokens from account
+ /// @dev Function that burns an `amount` of the tokens of a given account,
+ /// deducting from the sender's allowance for said account.
+ /// @param from The account whose tokens will be burnt.
+ /// @param amount The amount that will be burnt.
+ #[weight(<SelfWeightOf<T>>::burn_from())]
+ fn burn_from_cross(
+ &mut self,
+ caller: caller,
+ from: (address, uint256),
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = convert_tuple_to_cross_account::<T>(from)?;
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::burn_from(self, &caller, &from, amount, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
/// Mint tokens for multiple accounts.
/// @param amounts array of pairs of account address and amount
#[weight(<SelfWeightOf<T>>::create_multiple_items_ex(amounts.len() as u32))]
@@ -191,6 +235,27 @@
.map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
+
+ #[weight(<SelfWeightOf<T>>::transfer_from())]
+ fn transfer_from_cross(
+ &mut self,
+ caller: caller,
+ from: (address, uint256),
+ to: (address, uint256),
+ 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 amount = amount.try_into().map_err(|_| "amount overflow")?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
}
#[solidity_interface(
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
@@ -18,7 +18,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -33,6 +33,17 @@
dummy = 0;
}
+ /// Set collection properties.
+ ///
+ /// @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 {
+ require(false, stub_error);
+ properties;
+ dummy = 0;
+ }
+
/// Delete collection property.
///
/// @param key Property key.
@@ -44,6 +55,17 @@
dummy = 0;
}
+ /// Delete collection properties.
+ ///
+ /// @param keys Properties keys.
+ /// @dev EVM selector for this function is: 0xee206ee3,
+ /// or in textual repr: deleteCollectionProperties(string[])
+ function deleteCollectionProperties(string[] memory keys) public {
+ require(false, stub_error);
+ keys;
+ dummy = 0;
+ }
+
/// Get collection property.
///
/// @dev Throws error if key not found.
@@ -59,6 +81,19 @@
return hex"";
}
+ /// Get collection properties.
+ ///
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @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) {
+ require(false, stub_error);
+ keys;
+ dummy;
+ return new Tuple10[](0);
+ }
+
/// Set the sponsor of the collection.
///
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
@@ -72,6 +107,19 @@
dummy = 0;
}
+ /// Set the sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// or in textual repr: setCollectionSponsorCross((address,uint256))
+ function setCollectionSponsorCross(Tuple6 memory sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
/// Whether there is a pending sponsor.
/// @dev EVM selector for this function is: 0x058ac185,
/// or in textual repr: hasCollectionPendingSponsor()
@@ -155,6 +203,26 @@
}
/// Add collection admin.
+ /// @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 {
+ require(false, stub_error);
+ newAdmin;
+ dummy = 0;
+ }
+
+ /// 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) public {
+ require(false, stub_error);
+ admin;
+ dummy = 0;
+ }
+
+ /// Add collection admin.
/// @param newAdmin Address of the added administrator.
/// @dev EVM selector for this function is: 0x92e462c7,
/// or in textual repr: addCollectionAdmin(address)
@@ -234,6 +302,17 @@
dummy = 0;
}
+ /// Add user to allowed list.
+ ///
+ /// @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 {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -245,6 +324,17 @@
dummy = 0;
}
+ /// Remove user from allowed list.
+ ///
+ /// @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 {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -269,6 +359,19 @@
return false;
}
+ /// Check that account is the owner or admin of the collection
+ ///
+ /// @param user User cross account to verify
+ /// @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) {
+ require(false, stub_error);
+ user;
+ dummy;
+ return false;
+ }
+
/// Returns collection type
///
/// @return `Fungible` or `NFT` or `ReFungible`
@@ -282,7 +385,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple 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()
@@ -303,10 +406,50 @@
newOwner;
dummy = 0;
}
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// 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) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple6[](0);
+ }
+
+ /// Changes collection owner to another account
+ ///
+ /// @dev Owner can be changed only by current owner
+ /// @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 {
+ require(false, stub_error);
+ newOwner;
+ dummy = 0;
+ }
}
-/// @dev the ERC-165 identifier for this interface is 0x63034ac5
+/// @dev anonymous struct
+struct Tuple10 {
+ string field_0;
+ bytes field_1;
+}
+
+/// @dev the ERC-165 identifier for this interface is 0x032e5926
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) {
+ require(false, stub_error);
+ spender;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
/// Burn tokens from account
/// @dev Function that burns an `amount` of the tokens of a given account,
/// deducting from the sender's allowance for said account.
@@ -322,6 +465,21 @@
return false;
}
+ /// Burn tokens from account
+ /// @dev Function that burns an `amount` of the tokens of a given account,
+ /// deducting from the sender's allowance for said account.
+ /// @param from The account whose tokens will be burnt.
+ /// @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) {
+ require(false, stub_error);
+ from;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
/// Mint tokens for multiple accounts.
/// @param amounts array of pairs of account address and amount
/// @dev EVM selector for this function is: 0x1acf2d55,
@@ -332,6 +490,21 @@
dummy = 0;
return false;
}
+
+ /// @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,
+ uint256 amount
+ ) public returns (bool) {
+ require(false, stub_error);
+ from;
+ to;
+ amount;
+ dummy = 0;
+ return false;
+ }
}
/// @dev anonymous struct
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -2,12 +2,20 @@
All notable changes to this project will be documented in this file.
+<!-- bureaucrate goes here -->
+
+## [v0.1.6] - 2022-20-10
+
+### Change
+
+- Added `set_properties` method for `TokenProperties` interface.
+
## [v0.1.5] - 2022-08-24
### Change
- - Add bound `AsRef<[u8; 32]>` to `T::CrossAccountId`.
-<!-- bureaucrate goes here -->
+- Add bound `AsRef<[u8; 32]>` to `T::CrossAccountId`.
+
## [v0.1.4] 2022-08-16
### Other changes
@@ -28,7 +36,9 @@
- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
## [0.1.2] - 2022-07-25
+
### Changed
+
- New `token_uri` retrieval logic:
If the collection has a `url` property and it is not empty, it is returned.
@@ -39,8 +49,9 @@
otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
## [0.1.1] - 2022-07-14
+
### Added
- Implementation of RPC method `token_owners`.
- For reasons of compatibility with this pallet, returns only one owner if token exists.
- This was an internal request to improve the web interface and support fractionalization event.
+ For reasons of compatibility with this pallet, returns only one owner if token exists.
+ This was an internal request to improve the web interface and support fractionalization event.
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.5"
+version = "0.1.6"
license = "GPLv3"
edition = "2021"
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -35,6 +35,7 @@
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;
@@ -97,7 +98,7 @@
let key = <Vec<u8>>::from(key)
.try_into()
.map_err(|_| "key too long")?;
- let value = value.try_into().map_err(|_| "value too long")?;
+ let value = value.0.try_into().map_err(|_| "value too long")?;
let nesting_budget = self
.recorder
@@ -113,6 +114,48 @@
.map_err(dispatch_to_evm::<T>)
}
+ /// @notice Set token properties value.
+ /// @dev Throws error if `msg.sender` has no permission to edit the property.
+ /// @param tokenId ID of the token.
+ /// @param properties settable properties
+ #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]
+ fn set_properties(
+ &mut self,
+ caller: caller,
+ token_id: uint256,
+ properties: Vec<(string, bytes)>,
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
+
+ let nesting_budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ let properties = properties
+ .into_iter()
+ .map(|(key, value)| {
+ let key = <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "key too large")?;
+
+ let value = value.0.try_into().map_err(|_| "value too large")?;
+
+ Ok(Property { key, value })
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ <Pallet<T>>::set_token_properties(
+ self,
+ &caller,
+ TokenId(token_id),
+ properties.into_iter(),
+ <Pallet<T>>::token_exists(&self, TokenId(token_id)),
+ &nesting_budget,
+ )
+ .map_err(dispatch_to_evm::<T>)
+ }
+
/// @notice Delete token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
@@ -146,7 +189,7 @@
let props = <TokenProperties<T>>::get((self.id, token_id));
let prop = props.get(&key).ok_or("key not found")?;
- Ok(prop.to_vec())
+ Ok(prop.to_vec().into())
}
}
@@ -198,7 +241,10 @@
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]
-impl<T: Config> NonfungibleHandle<T> {
+impl<T: Config> NonfungibleHandle<T>
+where
+ T::AccountId: From<[u8; 32]>,
+{
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev real implementation of this function lies in `ERC721UniqueExtensions`
#[solidity(hide, rename_selector = "name")]
@@ -603,7 +649,10 @@
/// @title Unique extensions for ERC721.
#[solidity_interface(name = ERC721UniqueExtensions)]
-impl<T: Config> NonfungibleHandle<T> {
+impl<T: Config> NonfungibleHandle<T>
+where
+ T::AccountId: From<[u8; 32]>,
+{
/// @notice A descriptive name for a collection of NFTs in this contract
fn name(&self) -> Result<string> {
Ok(decode_utf16(self.name.iter().copied())
@@ -616,6 +665,28 @@
Ok(string::from_utf8_lossy(&self.token_prefix).into())
}
+ /// @notice Set or reaffirm the approved address for an NFT
+ /// @dev The zero address indicates there is no approved address.
+ /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
+ /// operator of the current owner.
+ /// @param approved The new substrate address approved NFT controller
+ /// @param tokenId The NFT to approve
+ #[weight(<SelfWeightOf<T>>::approve())]
+ fn approve_cross(
+ &mut self,
+ caller: caller,
+ approved: (address, uint256),
+ token_id: uint256,
+ ) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let approved = convert_tuple_to_cross_account::<T>(approved)?;
+ let token = token_id.try_into()?;
+
+ <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -634,6 +705,32 @@
Ok(())
}
+ /// @notice Transfer ownership of an NFT from cross account address to cross account address
+ /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
+ /// is the zero address. Throws if `tokenId` is not a valid NFT.
+ /// @param from Cross acccount address of current owner
+ /// @param to Cross acccount address of new owner
+ /// @param tokenId The NFT to transfer
+ #[weight(<SelfWeightOf<T>>::transfer())]
+ fn transfer_from_cross(
+ &mut self,
+ caller: caller,
+ from: (address, uint256),
+ to: (address, uint256),
+ 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 token_id = token_id.try_into()?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+ Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
/// @notice Burns a specific ERC721 token.
/// @dev Throws unless `msg.sender` is the current owner or an authorized
/// operator for this NFT. Throws if `from` is not the current owner. Throws
@@ -654,6 +751,31 @@
Ok(())
}
+ /// @notice Burns a specific ERC721 token.
+ /// @dev Throws unless `msg.sender` is the current owner or an authorized
+ /// operator for this NFT. Throws if `from` is not the current owner. Throws
+ /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.
+ /// @param from The current owner of the NFT
+ /// @param tokenId The NFT to transfer
+ #[weight(<SelfWeightOf<T>>::burn_from())]
+ fn burn_from_cross(
+ &mut self,
+ caller: caller,
+ from: (address, uint256),
+ token_id: uint256,
+ ) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = convert_tuple_to_cross_account::<T>(from)?;
+ let token = token_id.try_into()?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
/// @notice Returns next free NFT ID.
fn next_token_id(&self) -> Result<uint256> {
self.consume_store_reads(1)?;
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
@@ -18,7 +18,7 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x41369377
+/// @dev the ERC-165 identifier for this interface is 0x55dba919
contract TokenProperties is Dummy, ERC165 {
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
@@ -61,6 +61,19 @@
dummy = 0;
}
+ /// @notice Set token properties value.
+ /// @dev Throws error if `msg.sender` has no permission to edit the property.
+ /// @param tokenId ID of the token.
+ /// @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 {
+ require(false, stub_error);
+ tokenId;
+ properties;
+ dummy = 0;
+ }
+
/// @notice Delete token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
@@ -91,7 +104,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -106,6 +119,17 @@
dummy = 0;
}
+ /// Set collection properties.
+ ///
+ /// @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 {
+ require(false, stub_error);
+ properties;
+ dummy = 0;
+ }
+
/// Delete collection property.
///
/// @param key Property key.
@@ -117,6 +141,17 @@
dummy = 0;
}
+ /// Delete collection properties.
+ ///
+ /// @param keys Properties keys.
+ /// @dev EVM selector for this function is: 0xee206ee3,
+ /// or in textual repr: deleteCollectionProperties(string[])
+ function deleteCollectionProperties(string[] memory keys) public {
+ require(false, stub_error);
+ keys;
+ dummy = 0;
+ }
+
/// Get collection property.
///
/// @dev Throws error if key not found.
@@ -132,6 +167,19 @@
return hex"";
}
+ /// Get collection properties.
+ ///
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @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) {
+ require(false, stub_error);
+ keys;
+ dummy;
+ return new Tuple19[](0);
+ }
+
/// Set the sponsor of the collection.
///
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
@@ -145,6 +193,19 @@
dummy = 0;
}
+ /// Set the sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// or in textual repr: setCollectionSponsorCross((address,uint256))
+ function setCollectionSponsorCross(Tuple6 memory sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
/// Whether there is a pending sponsor.
/// @dev EVM selector for this function is: 0x058ac185,
/// or in textual repr: hasCollectionPendingSponsor()
@@ -177,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 (Tuple17 memory) {
+ function collectionSponsor() public view returns (Tuple6 memory) {
require(false, stub_error);
dummy;
- return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ return Tuple6(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -228,6 +289,26 @@
}
/// Add collection admin.
+ /// @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 {
+ require(false, stub_error);
+ newAdmin;
+ dummy = 0;
+ }
+
+ /// 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) public {
+ require(false, stub_error);
+ admin;
+ dummy = 0;
+ }
+
+ /// Add collection admin.
/// @param newAdmin Address of the added administrator.
/// @dev EVM selector for this function is: 0x92e462c7,
/// or in textual repr: addCollectionAdmin(address)
@@ -307,6 +388,17 @@
dummy = 0;
}
+ /// Add user to allowed list.
+ ///
+ /// @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 {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -318,6 +410,17 @@
dummy = 0;
}
+ /// Remove user from allowed list.
+ ///
+ /// @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 {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -342,6 +445,19 @@
return false;
}
+ /// Check that account is the owner or admin of the collection
+ ///
+ /// @param user User cross account to verify
+ /// @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) {
+ require(false, stub_error);
+ user;
+ dummy;
+ return false;
+ }
+
/// Returns collection type
///
/// @return `Fungible` or `NFT` or `ReFungible`
@@ -355,14 +471,14 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple 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 (Tuple17 memory) {
+ function collectionOwner() public view returns (Tuple6 memory) {
require(false, stub_error);
dummy;
- return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ return Tuple6(0x0000000000000000000000000000000000000000, 0);
}
/// Changes collection owner to another account
@@ -376,12 +492,36 @@
newOwner;
dummy = 0;
}
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// 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) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple6[](0);
+ }
+
+ /// Changes collection owner to another account
+ ///
+ /// @dev Owner can be changed only by current owner
+ /// @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 {
+ require(false, stub_error);
+ newOwner;
+ dummy = 0;
+ }
}
/// @dev anonymous struct
-struct Tuple17 {
- address field_0;
- uint256 field_1;
+struct Tuple19 {
+ string field_0;
+ bytes field_1;
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
@@ -528,7 +668,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x4468500d
+/// @dev the ERC-165 identifier for this interface is 0x244543ee
contract ERC721UniqueExtensions is Dummy, ERC165 {
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev EVM selector for this function is: 0x06fdde03,
@@ -548,6 +688,21 @@
return "";
}
+ /// @notice Set or reaffirm the approved address for an NFT
+ /// @dev The zero address indicates there is no approved address.
+ /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
+ /// operator of the current owner.
+ /// @param approved The new substrate address approved NFT controller
+ /// @param tokenId The NFT to approve
+ /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// or in textual repr: approveCross((address,uint256),uint256)
+ function approveCross(Tuple6 memory approved, uint256 tokenId) public {
+ require(false, stub_error);
+ approved;
+ tokenId;
+ dummy = 0;
+ }
+
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -562,6 +717,26 @@
dummy = 0;
}
+ /// @notice Transfer ownership of an NFT from cross account address to cross account address
+ /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
+ /// is the zero address. Throws if `tokenId` is not a valid NFT.
+ /// @param from Cross acccount address of current owner
+ /// @param to Cross acccount address of new owner
+ /// @param tokenId The NFT to transfer
+ /// @dev EVM selector for this function is: 0xd5cf430b,
+ /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ function transferFromCross(
+ Tuple6 memory from,
+ Tuple6 memory to,
+ uint256 tokenId
+ ) public {
+ require(false, stub_error);
+ from;
+ to;
+ tokenId;
+ dummy = 0;
+ }
+
/// @notice Burns a specific ERC721 token.
/// @dev Throws unless `msg.sender` is the current owner or an authorized
/// operator for this NFT. Throws if `from` is not the current owner. Throws
@@ -577,6 +752,21 @@
dummy = 0;
}
+ /// @notice Burns a specific ERC721 token.
+ /// @dev Throws unless `msg.sender` is the current owner or an authorized
+ /// operator for this NFT. Throws if `from` is not the current owner. Throws
+ /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.
+ /// @param from The current owner of the NFT
+ /// @param tokenId The NFT to transfer
+ /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// or in textual repr: burnFromCross((address,uint256),uint256)
+ function burnFromCross(Tuple6 memory from, uint256 tokenId) public {
+ require(false, stub_error);
+ from;
+ tokenId;
+ dummy = 0;
+ }
+
/// @notice Returns next free NFT ID.
/// @dev EVM selector for this function is: 0x75794a3c,
/// or in textual repr: nextTokenId()
@@ -607,7 +797,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, Tuple6[] memory tokens) public returns (bool) {
+ // function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
// require(false, stub_error);
// to;
// tokens;
@@ -618,11 +808,17 @@
}
/// @dev anonymous struct
-struct Tuple6 {
+struct Tuple8 {
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
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x780e9d63
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -2,12 +2,20 @@
All notable changes to this project will be documented in this file.
+## [v0.2.5] - 2022-20-10
+
+### Change
+
+- Added `set_properties` method for `TokenProperties` interface.
+
## [v0.2.4] - 2022-08-24
### Change
- - Add bound `AsRef<[u8; 32]>` to `T::CrossAccountId`.
+- Add bound `AsRef<[u8; 32]>` to `T::CrossAccountId`.
+
<!-- bureaucrate goes here -->
+
## [v0.2.3] 2022-08-16
### Other changes
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.4"
+version = "0.2.5"
license = "GPLv3"
edition = "2021"
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -30,6 +30,7 @@
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};
@@ -100,7 +101,7 @@
let key = <Vec<u8>>::from(key)
.try_into()
.map_err(|_| "key too long")?;
- let value = value.try_into().map_err(|_| "value too long")?;
+ let value = value.0.try_into().map_err(|_| "value too long")?;
let nesting_budget = self
.recorder
@@ -116,6 +117,47 @@
.map_err(dispatch_to_evm::<T>)
}
+ /// @notice Set token properties value.
+ /// @dev Throws error if `msg.sender` has no permission to edit the property.
+ /// @param tokenId ID of the token.
+ /// @param properties settable properties
+ fn set_properties(
+ &mut self,
+ caller: caller,
+ token_id: uint256,
+ properties: Vec<(string, bytes)>,
+ ) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
+
+ let nesting_budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ let properties = properties
+ .into_iter()
+ .map(|(key, value)| {
+ let key = <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "key too large")?;
+
+ let value = value.0.try_into().map_err(|_| "value too large")?;
+
+ Ok(Property { key, value })
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ <Pallet<T>>::set_token_properties(
+ self,
+ &caller,
+ TokenId(token_id),
+ properties.into_iter(),
+ <Pallet<T>>::token_exists(&self, TokenId(token_id)),
+ &nesting_budget,
+ )
+ .map_err(dispatch_to_evm::<T>)
+ }
+
/// @notice Delete token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
@@ -149,7 +191,7 @@
let props = <TokenProperties<T>>::get((self.id, token_id));
let prop = props.get(&key).ok_or("key not found")?;
- Ok(prop.to_vec())
+ Ok(prop.to_vec().into())
}
}
@@ -194,7 +236,10 @@
}
#[solidity_interface(name = ERC721Metadata)]
-impl<T: Config> RefungibleHandle<T> {
+impl<T: Config> RefungibleHandle<T>
+where
+ T::AccountId: From<[u8; 32]>,
+{
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev real implementation of this function lies in `ERC721UniqueExtensions`
#[solidity(hide, rename_selector = "name")]
@@ -631,7 +676,10 @@
/// @title Unique extensions for ERC721.
#[solidity_interface(name = ERC721UniqueExtensions)]
-impl<T: Config> RefungibleHandle<T> {
+impl<T: Config> RefungibleHandle<T>
+where
+ T::AccountId: From<[u8; 32]>,
+{
/// @notice A descriptive name for a collection of NFTs in this contract
fn name(&self) -> Result<string> {
Ok(decode_utf16(self.name.iter().copied())
@@ -659,14 +707,44 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- let balance = balance(&self, token, &caller)?;
- ensure_single_owner(&self, token, balance)?;
+ let balance = balance(self, token, &caller)?;
+ ensure_single_owner(self, token, balance)?;
<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)
.map_err(dispatch_to_evm::<T>)?;
Ok(())
}
+ /// @notice Transfer ownership of an RFT
+ /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
+ /// is the zero address. Throws if `tokenId` is not a valid RFT.
+ /// Throws if RFT pieces have multiple owners.
+ /// @param to The new owner
+ /// @param tokenId The RFT to transfer
+ #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]
+ fn transfer_from_cross(
+ &mut self,
+ caller: caller,
+ from: (address, uint256),
+ to: (address, uint256),
+ 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 token_id = token_id.try_into()?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ let balance = balance(self, token_id, &from)?;
+ ensure_single_owner(self, token_id, balance)?;
+
+ Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
/// @notice Burns a specific ERC721 token.
/// @dev Throws unless `msg.sender` is the current owner or an authorized
/// operator for this RFT. Throws if `from` is not the current owner. Throws
@@ -683,8 +761,37 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- let balance = balance(&self, token, &caller)?;
- ensure_single_owner(&self, token, balance)?;
+ let balance = balance(self, token, &from)?;
+ ensure_single_owner(self, token, balance)?;
+
+ <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ /// @notice Burns a specific ERC721 token.
+ /// @dev Throws unless `msg.sender` is the current owner or an authorized
+ /// operator for this RFT. Throws if `from` is not the current owner. Throws
+ /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.
+ /// Throws if RFT pieces have multiple owners.
+ /// @param from The current owner of the RFT
+ /// @param tokenId The RFT to transfer
+ #[weight(<SelfWeightOf<T>>::burn_from())]
+ fn burn_from_cross(
+ &mut self,
+ caller: caller,
+ from: (address, uint256),
+ token_id: uint256,
+ ) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = convert_tuple_to_cross_account::<T>(from)?;
+ let token = token_id.try_into()?;
+ let budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ let balance = balance(self, token, &from)?;
+ ensure_single_owner(self, token, balance)?;
<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)
.map_err(dispatch_to_evm::<T>)?;
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -18,7 +18,7 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x41369377
+/// @dev the ERC-165 identifier for this interface is 0x55dba919
contract TokenProperties is Dummy, ERC165 {
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
@@ -61,6 +61,19 @@
dummy = 0;
}
+ /// @notice Set token properties value.
+ /// @dev Throws error if `msg.sender` has no permission to edit the property.
+ /// @param tokenId ID of the token.
+ /// @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 {
+ require(false, stub_error);
+ tokenId;
+ properties;
+ dummy = 0;
+ }
+
/// @notice Delete token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
@@ -91,7 +104,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -106,6 +119,17 @@
dummy = 0;
}
+ /// Set collection properties.
+ ///
+ /// @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 {
+ require(false, stub_error);
+ properties;
+ dummy = 0;
+ }
+
/// Delete collection property.
///
/// @param key Property key.
@@ -117,6 +141,17 @@
dummy = 0;
}
+ /// Delete collection properties.
+ ///
+ /// @param keys Properties keys.
+ /// @dev EVM selector for this function is: 0xee206ee3,
+ /// or in textual repr: deleteCollectionProperties(string[])
+ function deleteCollectionProperties(string[] memory keys) public {
+ require(false, stub_error);
+ keys;
+ dummy = 0;
+ }
+
/// Get collection property.
///
/// @dev Throws error if key not found.
@@ -132,6 +167,19 @@
return hex"";
}
+ /// Get collection properties.
+ ///
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @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) {
+ require(false, stub_error);
+ keys;
+ dummy;
+ return new Tuple19[](0);
+ }
+
/// Set the sponsor of the collection.
///
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
@@ -145,6 +193,19 @@
dummy = 0;
}
+ /// Set the sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// or in textual repr: setCollectionSponsorCross((address,uint256))
+ function setCollectionSponsorCross(Tuple6 memory sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
/// Whether there is a pending sponsor.
/// @dev EVM selector for this function is: 0x058ac185,
/// or in textual repr: hasCollectionPendingSponsor()
@@ -177,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 (Tuple17 memory) {
+ function collectionSponsor() public view returns (Tuple6 memory) {
require(false, stub_error);
dummy;
- return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ return Tuple6(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -228,6 +289,26 @@
}
/// Add collection admin.
+ /// @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 {
+ require(false, stub_error);
+ newAdmin;
+ dummy = 0;
+ }
+
+ /// 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) public {
+ require(false, stub_error);
+ admin;
+ dummy = 0;
+ }
+
+ /// Add collection admin.
/// @param newAdmin Address of the added administrator.
/// @dev EVM selector for this function is: 0x92e462c7,
/// or in textual repr: addCollectionAdmin(address)
@@ -307,6 +388,17 @@
dummy = 0;
}
+ /// Add user to allowed list.
+ ///
+ /// @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 {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -318,6 +410,17 @@
dummy = 0;
}
+ /// Remove user from allowed list.
+ ///
+ /// @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 {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -342,6 +445,19 @@
return false;
}
+ /// Check that account is the owner or admin of the collection
+ ///
+ /// @param user User cross account to verify
+ /// @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) {
+ require(false, stub_error);
+ user;
+ dummy;
+ return false;
+ }
+
/// Returns collection type
///
/// @return `Fungible` or `NFT` or `ReFungible`
@@ -355,14 +471,14 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple 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 (Tuple17 memory) {
+ function collectionOwner() public view returns (Tuple6 memory) {
require(false, stub_error);
dummy;
- return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ return Tuple6(0x0000000000000000000000000000000000000000, 0);
}
/// Changes collection owner to another account
@@ -376,12 +492,36 @@
newOwner;
dummy = 0;
}
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// 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) {
+ require(false, stub_error);
+ dummy;
+ return new Tuple6[](0);
+ }
+
+ /// Changes collection owner to another account
+ ///
+ /// @dev Owner can be changed only by current owner
+ /// @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 {
+ require(false, stub_error);
+ newOwner;
+ dummy = 0;
+ }
}
/// @dev anonymous struct
-struct Tuple17 {
- address field_0;
- uint256 field_1;
+struct Tuple19 {
+ string field_0;
+ bytes field_1;
}
/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
@@ -526,7 +666,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xef1eaacb
+/// @dev the ERC-165 identifier for this interface is 0x81feb398
contract ERC721UniqueExtensions is Dummy, ERC165 {
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev EVM selector for this function is: 0x06fdde03,
@@ -561,6 +701,26 @@
dummy = 0;
}
+ /// @notice Transfer ownership of an RFT
+ /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
+ /// is the zero address. Throws if `tokenId` is not a valid RFT.
+ /// Throws if RFT pieces have multiple owners.
+ /// @param to The new owner
+ /// @param tokenId The RFT to transfer
+ /// @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,
+ uint256 tokenId
+ ) public {
+ require(false, stub_error);
+ from;
+ to;
+ tokenId;
+ dummy = 0;
+ }
+
/// @notice Burns a specific ERC721 token.
/// @dev Throws unless `msg.sender` is the current owner or an authorized
/// operator for this RFT. Throws if `from` is not the current owner. Throws
@@ -577,6 +737,22 @@
dummy = 0;
}
+ /// @notice Burns a specific ERC721 token.
+ /// @dev Throws unless `msg.sender` is the current owner or an authorized
+ /// operator for this RFT. Throws if `from` is not the current owner. Throws
+ /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.
+ /// Throws if RFT pieces have multiple owners.
+ /// @param from The current owner of the RFT
+ /// @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 {
+ require(false, stub_error);
+ from;
+ tokenId;
+ dummy = 0;
+ }
+
/// @notice Returns next free RFT ID.
/// @dev EVM selector for this function is: 0x75794a3c,
/// or in textual repr: nextTokenId()
@@ -608,7 +784,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, Tuple6[] memory tokens) public returns (bool) {
+ // function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
// require(false, stub_error);
// to;
// tokens;
@@ -630,11 +806,17 @@
}
/// @dev anonymous struct
-struct Tuple6 {
+struct Tuple8 {
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
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x780e9d63
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/CHANGELOG.mddiffbeforeafterboth--- a/pallets/unique/CHANGELOG.md
+++ b/pallets/unique/CHANGELOG.md
@@ -4,33 +4,40 @@
<!-- bureaucrate goes here -->
+## [v0.2.1] 2022-10-10
+
+### Changes
+
+- Added `destroyCollection` and `createFTCollection` methods to **CollectionHelpers**.
+
## [v0.2.0] 2022-09-13
### Changes
-- Change **collectionHelper** method `createRefungibleCollection` to `createRFTCollection`,
+- Change **collectionHelper** method `createRefungibleCollection` to `createRFTCollection`,
+
## [v0.1.4] 2022-09-05
### Added
-- Methods `force_set_sponsor` , `force_remove_collection_sponsor` to be able to administer sponsorships with other pallets. Added to implement `AppPromotion` pallet logic.
+- Methods `force_set_sponsor` , `force_remove_collection_sponsor` to be able to administer sponsorships with other pallets. Added to implement `AppPromotion` pallet logic.
## [v0.1.3] 2022-08-16
### Other changes
-- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
+- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
-- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
+- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
-- refactor: Remove `#[transactional]` from extrinsics 7fd36cea2f6e00c02c67ccc1de9649ae404efd31
+- refactor: Remove `#[transactional]` from extrinsics 7fd36cea2f6e00c02c67ccc1de9649ae404efd31
Every extrinsic now runs in transaction implicitly, and
`#[transactional]` on pallet dispatchable is now meaningless
Upstream-Change: https://github.com/paritytech/substrate/issues/10806
-- refactor: Switch to new prefix removal methods 26734e9567589d75cdd99e404eabf11d5a97d975
+- refactor: Switch to new prefix removal methods 26734e9567589d75cdd99e404eabf11d5a97d975
New methods allows to call `remove_prefix` with limit multiple times
in the same block
@@ -39,12 +46,12 @@
Upstream-Change: https://github.com/paritytech/substrate/pull/11490
-- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
+- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
## [v0.1.1] - 2022-07-25
### Added
-- Method for creating `ERC721Metadata` compatible NFT collection.
-- Method for creating `ERC721Metadata` compatible ReFungible collection.
-- Method for creating ReFungible collection.
+- Method for creating `ERC721Metadata` compatible NFT collection.
+- Method for creating `ERC721Metadata` compatible ReFungible collection.
+- Method for creating ReFungible collection.
pallets/unique/Cargo.tomldiffbeforeafterboth--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -9,7 +9,7 @@
license = 'GPLv3'
name = 'pallet-unique'
repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = "0.2.0"
+version = "0.2.1"
[package.metadata.docs.rs]
targets = ['x86_64-unknown-linux-gnu']
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -18,29 +18,29 @@
use core::marker::PhantomData;
use ethereum as _;
-use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};
+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::{
- CollectionHelpersEvents,
- static_property::{key},
- },
+ erc::{static_property::key, CollectionHelpersEvents},
Pallet as PalletCommon,
};
+use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};
-use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
use sp_std::vec;
use up_data_structs::{
- CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
- CollectionMode, PropertyValue, CollectionFlags,
+ CollectionDescription, CollectionMode, CollectionName, CollectionTokenPrefix,
+ CreateCollectionData,
};
-use crate::{Config, SelfWeightOf, weights::WeightInfo};
+use crate::{weights::WeightInfo, Config, SelfWeightOf};
+use alloc::format;
use sp_std::vec::Vec;
-use alloc::format;
/// See [`CollectionHelpersCall`]
pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);
@@ -84,12 +84,12 @@
Ok((caller, name, description, token_prefix))
}
-fn create_refungible_collection_internal<
- T: Config + pallet_nonfungible::Config + pallet_refungible::Config,
->(
+#[inline(always)]
+fn create_collection_internal<T: Config>(
caller: caller,
value: value,
name: string,
+ collection_mode: CollectionMode,
description: string,
token_prefix: string,
) -> Result<address> {
@@ -97,7 +97,7 @@
convert_data::<T>(caller, name, description, token_prefix)?;
let data = CreateCollectionData {
name,
- mode: CollectionMode::ReFungible,
+ mode: collection_mode,
description,
token_prefix,
..Default::default()
@@ -193,7 +193,14 @@
description: string,
token_prefix: string,
) -> Result<address> {
- self.create_nft_collection(caller, value, name, description, token_prefix)
+ create_collection_internal::<T>(
+ caller,
+ value,
+ name,
+ CollectionMode::NFT,
+ description,
+ token_prefix,
+ )
}
#[weight(<SelfWeightOf<T>>::create_collection())]
@@ -206,7 +213,35 @@
description: string,
token_prefix: string,
) -> Result<address> {
- create_refungible_collection_internal::<T>(caller, value, name, description, token_prefix)
+ create_collection_internal::<T>(
+ caller,
+ value,
+ name,
+ CollectionMode::ReFungible,
+ description,
+ token_prefix,
+ )
+ }
+
+ #[weight(<SelfWeightOf<T>>::create_collection())]
+ #[solidity(rename_selector = "createFTCollection")]
+ fn create_fungible_collection(
+ &mut self,
+ caller: caller,
+ value: value,
+ name: string,
+ decimals: uint8,
+ description: string,
+ token_prefix: string,
+ ) -> Result<address> {
+ create_collection_internal::<T>(
+ caller,
+ value,
+ name,
+ CollectionMode::Fungible(decimals),
+ description,
+ token_prefix,
+ )
}
#[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]
@@ -296,6 +331,16 @@
Ok(())
}
+ #[weight(<SelfWeightOf<T>>::destroy_collection())]
+ fn destroy_collection(&mut self, caller: caller, collection_address: address) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+
+ let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)
+ .ok_or("Invalid collection address format")?;
+ <Pallet<T>>::destroy_collection_internal(caller, collection_id)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)
+ }
+
/// Check if a collection exists
/// @param collectionAddress Address of the collection in question
/// @return bool Does the collection exist?
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -20,10 +20,11 @@
/// @dev inlined interface
contract CollectionHelpersEvents {
event CollectionCreated(address indexed owner, address indexed collectionId);
+ event CollectionDestroyed(address indexed collectionId);
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x58918631
+/// @dev the ERC-165 identifier for this interface is 0x7dea03b1
contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
@@ -76,6 +77,23 @@
return 0x0000000000000000000000000000000000000000;
}
+ /// @dev EVM selector for this function is: 0x7335b79f,
+ /// or in textual repr: createFTCollection(string,uint8,string,string)
+ function createFTCollection(
+ string memory name,
+ uint8 decimals,
+ string memory description,
+ string memory tokenPrefix
+ ) public payable returns (address) {
+ require(false, stub_error);
+ name;
+ decimals;
+ description;
+ tokenPrefix;
+ dummy = 0;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
/// @dev EVM selector for this function is: 0x85624258,
/// or in textual repr: makeCollectionERC721MetadataCompatible(address,string)
function makeCollectionERC721MetadataCompatible(address collection, string memory baseUri) public {
@@ -85,6 +103,14 @@
dummy = 0;
}
+ /// @dev EVM selector for this function is: 0x564e321f,
+ /// or in textual repr: destroyCollection(address)
+ function destroyCollection(address collectionAddress) public {
+ require(false, stub_error);
+ collectionAddress;
+ dummy = 0;
+ }
+
/// Check if a collection exists
/// @param collectionAddress Address of the collection in question
/// @return bool Does the collection exist?
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -362,25 +362,8 @@
#[weight = <SelfWeightOf<T>>::destroy_collection()]
pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = <CollectionHandle<T>>::try_get(collection_id)?;
- collection.check_is_internal()?;
-
- // =========
-
- T::CollectionDispatch::destroy(sender, collection)?;
- // TODO: basket cleanup should be moved elsewhere
- // Maybe runtime dispatch.rs should perform it?
-
- let _ = <NftTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);
- let _ = <FungibleTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);
- let _ = <ReFungibleTransferBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);
-
- let _ = <NftApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);
- let _ = <FungibleApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);
- let _ = <RefungibleApproveBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);
-
- Ok(())
+ Self::destroy_collection_internal(sender, collection_id)
}
/// Add an address to allow list.
@@ -1151,4 +1134,28 @@
target_collection.save()
}
+
+ #[inline(always)]
+ pub(crate) fn destroy_collection_internal(
+ sender: T::CrossAccountId,
+ collection_id: CollectionId,
+ ) -> DispatchResult {
+ let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ collection.check_is_internal()?;
+
+ T::CollectionDispatch::destroy(sender, collection)?;
+
+ // TODO: basket cleanup should be moved elsewhere
+ // Maybe runtime dispatch.rs should perform it?
+
+ let _ = <NftTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);
+ let _ = <FungibleTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);
+ let _ = <ReFungibleTransferBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);
+
+ let _ = <NftApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);
+ let _ = <FungibleApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);
+ let _ = <RefungibleApproveBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);
+
+ Ok(())
+ }
}
tests/.vscode/settings.jsondiffbeforeafterboth--- a/tests/.vscode/settings.json
+++ b/tests/.vscode/settings.json
@@ -1,5 +1,12 @@
{
- "mocha.enabled": true,
- "mochaExplorer.files": "**/*.test.ts",
- "mochaExplorer.require": "ts-node/register"
+ "mocha.enabled": true,
+ "mochaExplorer.files": "**/*.test.ts",
+ "mochaExplorer.require": "ts-node/register",
+ "eslint.format.enable": true,
+ "[javascript]": {
+ "editor.defaultFormatter": "dbaeumer.vscode-eslint"
+ },
+ "[typescript]": {
+ "editor.defaultFormatter": "dbaeumer.vscode-eslint"
+ }
}
tests/src/eth/allowlist.test.tsdiffbeforeafterboth--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -89,22 +89,22 @@
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
});
- // TODO: Temprorary off. Need refactor
- // itEth('Collection allowlist can be added and removed by [sub] 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);
-
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
- // await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+ //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;
+ //});
- // await collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).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);
const notOwner = await helper.eth.createAccountWithBalance(donor);
@@ -117,28 +117,27 @@
await expect(collectionEvm.methods.addToCollectionAllowList(user).call({from: notOwner})).to.be.rejectedWith('NoPermission');
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
-
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
await expect(collectionEvm.methods.removeFromCollectionAllowList(user).call({from: notOwner})).to.be.rejectedWith('NoPermission');
expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
});
- // TODO: Temprorary off. Need refactor
- // itEth('Collection allowlist can not be add and remove [sub] 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;
- // await expect(collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
- // await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
-
- // expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
- // await expect(collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).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/CollectionHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -15,10 +15,11 @@
/// @dev inlined interface
interface CollectionHelpersEvents {
event CollectionCreated(address indexed owner, address indexed collectionId);
+ event CollectionDestroyed(address indexed collectionId);
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x58918631
+/// @dev the ERC-165 identifier for this interface is 0x7dea03b1
interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
@@ -50,10 +51,23 @@
string memory tokenPrefix
) external payable returns (address);
+ /// @dev EVM selector for this function is: 0x7335b79f,
+ /// or in textual repr: createFTCollection(string,uint8,string,string)
+ function createFTCollection(
+ string memory name,
+ uint8 decimals,
+ string memory description,
+ string memory tokenPrefix
+ ) external payable returns (address);
+
/// @dev EVM selector for this function is: 0x85624258,
/// or in textual repr: makeCollectionERC721MetadataCompatible(address,string)
function makeCollectionERC721MetadataCompatible(address collection, string memory baseUri) external;
+ /// @dev EVM selector for this function is: 0x564e321f,
+ /// or in textual repr: destroyCollection(address)
+ function destroyCollection(address collectionAddress) external;
+
/// Check if a collection exists
/// @param collectionAddress Address of the collection in question
/// @return bool Does the collection exist?
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -23,6 +23,13 @@
/// or in textual repr: setCollectionProperty(string,bytes)
function setCollectionProperty(string memory key, bytes memory value) external;
+ /// Set collection properties.
+ ///
+ /// @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;
+
/// Delete collection property.
///
/// @param key Property key.
@@ -30,6 +37,13 @@
/// or in textual repr: deleteCollectionProperty(string)
function deleteCollectionProperty(string memory key) external;
+ /// Delete collection properties.
+ ///
+ /// @param keys Properties keys.
+ /// @dev EVM selector for this function is: 0xee206ee3,
+ /// or in textual repr: deleteCollectionProperties(string[])
+ function deleteCollectionProperties(string[] memory keys) external;
+
/// Get collection property.
///
/// @dev Throws error if key not found.
@@ -40,6 +54,14 @@
/// or in textual repr: collectionProperty(string)
function collectionProperty(string memory key) external view returns (bytes memory);
+ /// Get collection properties.
+ ///
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @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);
+
/// Set the sponsor of the collection.
///
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
@@ -49,6 +71,15 @@
/// or in textual repr: setCollectionSponsor(address)
function setCollectionSponsor(address sponsor) external;
+ /// Set the sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// or in textual repr: setCollectionSponsorCross((address,uint256))
+ function setCollectionSponsorCross(Tuple6 memory sponsor) external;
+
/// Whether there is a pending sponsor.
/// @dev EVM selector for this function is: 0x058ac185,
/// or in textual repr: hasCollectionPendingSponsor()
@@ -104,6 +135,18 @@
function contractAddress() external view returns (address);
/// Add collection admin.
+ /// @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;
+
+ /// 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;
+
+ /// Add collection admin.
/// @param newAdmin Address of the added administrator.
/// @dev EVM selector for this function is: 0x92e462c7,
/// or in textual repr: addCollectionAdmin(address)
@@ -153,6 +196,13 @@
/// or in textual repr: addToCollectionAllowList(address)
function addToCollectionAllowList(address user) external;
+ /// Add user to allowed list.
+ ///
+ /// @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;
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -160,6 +210,13 @@
/// or in textual repr: removeFromCollectionAllowList(address)
function removeFromCollectionAllowList(address user) external;
+ /// Remove user from allowed list.
+ ///
+ /// @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;
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -175,6 +232,14 @@
/// or in textual repr: isOwnerOrAdmin(address)
function isOwnerOrAdmin(address user) external view returns (bool);
+ /// Check that account is the owner or admin of the collection
+ ///
+ /// @param user User cross account to verify
+ /// @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);
+
/// Returns collection type
///
/// @return `Fungible` or `NFT` or `ReFungible`
@@ -184,7 +249,7 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple 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()
@@ -197,10 +262,36 @@
/// @dev EVM selector for this function is: 0x4f53e226,
/// or in textual repr: changeCollectionOwner(address)
function changeCollectionOwner(address newOwner) external;
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// 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);
+
+ /// Changes collection owner to another account
+ ///
+ /// @dev Owner can be changed only by current owner
+ /// @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;
}
-/// @dev the ERC-165 identifier for this interface is 0x63034ac5
+/// @dev anonymous struct
+struct Tuple10 {
+ string field_0;
+ bytes field_1;
+}
+
+/// @dev the ERC-165 identifier for this interface is 0x032e5926
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);
+
/// Burn tokens from account
/// @dev Function that burns an `amount` of the tokens of a given account,
/// deducting from the sender's allowance for said account.
@@ -210,11 +301,28 @@
/// or in textual repr: burnFrom(address,uint256)
function burnFrom(address from, uint256 amount) external returns (bool);
+ /// Burn tokens from account
+ /// @dev Function that burns an `amount` of the tokens of a given account,
+ /// deducting from the sender's allowance for said account.
+ /// @param from The account whose tokens will be burnt.
+ /// @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);
+
/// 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);
+
+ /// @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,
+ uint256 amount
+ ) external returns (bool);
}
/// @dev anonymous struct
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -13,7 +13,7 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x41369377
+/// @dev the ERC-165 identifier for this interface is 0x55dba919
interface TokenProperties is Dummy, ERC165 {
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
@@ -43,6 +43,14 @@
bytes memory value
) external;
+ /// @notice Set token properties value.
+ /// @dev Throws error if `msg.sender` has no permission to edit the property.
+ /// @param tokenId ID of the token.
+ /// @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;
+
/// @notice Delete token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
@@ -62,7 +70,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -72,6 +80,13 @@
/// or in textual repr: setCollectionProperty(string,bytes)
function setCollectionProperty(string memory key, bytes memory value) external;
+ /// Set collection properties.
+ ///
+ /// @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;
+
/// Delete collection property.
///
/// @param key Property key.
@@ -79,6 +94,13 @@
/// or in textual repr: deleteCollectionProperty(string)
function deleteCollectionProperty(string memory key) external;
+ /// Delete collection properties.
+ ///
+ /// @param keys Properties keys.
+ /// @dev EVM selector for this function is: 0xee206ee3,
+ /// or in textual repr: deleteCollectionProperties(string[])
+ function deleteCollectionProperties(string[] memory keys) external;
+
/// Get collection property.
///
/// @dev Throws error if key not found.
@@ -89,6 +111,14 @@
/// or in textual repr: collectionProperty(string)
function collectionProperty(string memory key) external view returns (bytes memory);
+ /// Get collection properties.
+ ///
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @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);
+
/// Set the sponsor of the collection.
///
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
@@ -98,6 +128,15 @@
/// or in textual repr: setCollectionSponsor(address)
function setCollectionSponsor(address sponsor) external;
+ /// Set the sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// or in textual repr: setCollectionSponsorCross((address,uint256))
+ function setCollectionSponsorCross(Tuple6 memory sponsor) external;
+
/// Whether there is a pending sponsor.
/// @dev EVM selector for this function is: 0x058ac185,
/// or in textual repr: hasCollectionPendingSponsor()
@@ -120,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 (Tuple17 memory);
+ function collectionSponsor() external view returns (Tuple6 memory);
/// Set limits for the collection.
/// @dev Throws error if limit not found.
@@ -153,6 +192,18 @@
function contractAddress() external view returns (address);
/// Add collection admin.
+ /// @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;
+
+ /// 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;
+
+ /// Add collection admin.
/// @param newAdmin Address of the added administrator.
/// @dev EVM selector for this function is: 0x92e462c7,
/// or in textual repr: addCollectionAdmin(address)
@@ -202,6 +253,13 @@
/// or in textual repr: addToCollectionAllowList(address)
function addToCollectionAllowList(address user) external;
+ /// Add user to allowed list.
+ ///
+ /// @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;
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -209,6 +267,13 @@
/// or in textual repr: removeFromCollectionAllowList(address)
function removeFromCollectionAllowList(address user) external;
+ /// Remove user from allowed list.
+ ///
+ /// @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;
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -224,6 +289,14 @@
/// or in textual repr: isOwnerOrAdmin(address)
function isOwnerOrAdmin(address user) external view returns (bool);
+ /// Check that account is the owner or admin of the collection
+ ///
+ /// @param user User cross account to verify
+ /// @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);
+
/// Returns collection type
///
/// @return `Fungible` or `NFT` or `ReFungible`
@@ -233,11 +306,11 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple 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 (Tuple17 memory);
+ function collectionOwner() external view returns (Tuple6 memory);
/// Changes collection owner to another account
///
@@ -246,12 +319,28 @@
/// @dev EVM selector for this function is: 0x4f53e226,
/// or in textual repr: changeCollectionOwner(address)
function changeCollectionOwner(address newOwner) external;
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// 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);
+
+ /// Changes collection owner to another account
+ ///
+ /// @dev Owner can be changed only by current owner
+ /// @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;
}
/// @dev anonymous struct
-struct Tuple17 {
- address field_0;
- uint256 field_1;
+struct Tuple19 {
+ string field_0;
+ bytes field_1;
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
@@ -349,7 +438,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x4468500d
+/// @dev the ERC-165 identifier for this interface is 0x244543ee
interface ERC721UniqueExtensions is Dummy, ERC165 {
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev EVM selector for this function is: 0x06fdde03,
@@ -361,6 +450,16 @@
/// or in textual repr: symbol()
function symbol() external view returns (string memory);
+ /// @notice Set or reaffirm the approved address for an NFT
+ /// @dev The zero address indicates there is no approved address.
+ /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
+ /// operator of the current owner.
+ /// @param approved The new substrate address approved NFT controller
+ /// @param tokenId The NFT to approve
+ /// @dev EVM selector for this function is: 0x0ecd0ab0,
+ /// or in textual repr: approveCross((address,uint256),uint256)
+ function approveCross(Tuple6 memory approved, uint256 tokenId) external;
+
/// @notice Transfer ownership of an NFT
/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
/// is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -370,6 +469,20 @@
/// or in textual repr: transfer(address,uint256)
function transfer(address to, uint256 tokenId) external;
+ /// @notice Transfer ownership of an NFT from cross account address to cross account address
+ /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
+ /// is the zero address. Throws if `tokenId` is not a valid NFT.
+ /// @param from Cross acccount address of current owner
+ /// @param to Cross acccount address of new owner
+ /// @param tokenId The NFT to transfer
+ /// @dev EVM selector for this function is: 0xd5cf430b,
+ /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+ function transferFromCross(
+ Tuple6 memory from,
+ Tuple6 memory to,
+ uint256 tokenId
+ ) external;
+
/// @notice Burns a specific ERC721 token.
/// @dev Throws unless `msg.sender` is the current owner or an authorized
/// operator for this NFT. Throws if `from` is not the current owner. Throws
@@ -380,6 +493,16 @@
/// or in textual repr: burnFrom(address,uint256)
function burnFrom(address from, uint256 tokenId) external;
+ /// @notice Burns a specific ERC721 token.
+ /// @dev Throws unless `msg.sender` is the current owner or an authorized
+ /// operator for this NFT. Throws if `from` is not the current owner. Throws
+ /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.
+ /// @param from The current owner of the NFT
+ /// @param tokenId The NFT to transfer
+ /// @dev EVM selector for this function is: 0xbb2f5a58,
+ /// or in textual repr: burnFromCross((address,uint256),uint256)
+ function burnFromCross(Tuple6 memory from, uint256 tokenId) external;
+
/// @notice Returns next free NFT ID.
/// @dev EVM selector for this function is: 0x75794a3c,
/// or in textual repr: nextTokenId()
@@ -400,16 +523,22 @@
// /// @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, Tuple6[] memory tokens) external returns (bool);
+ // function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
}
/// @dev anonymous struct
-struct Tuple6 {
+struct Tuple8 {
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
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x780e9d63
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -13,7 +13,7 @@
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x41369377
+/// @dev the ERC-165 identifier for this interface is 0x55dba919
interface TokenProperties is Dummy, ERC165 {
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
@@ -43,6 +43,14 @@
bytes memory value
) external;
+ /// @notice Set token properties value.
+ /// @dev Throws error if `msg.sender` has no permission to edit the property.
+ /// @param tokenId ID of the token.
+ /// @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;
+
/// @notice Delete token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
@@ -62,7 +70,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x62e22290
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -72,6 +80,13 @@
/// or in textual repr: setCollectionProperty(string,bytes)
function setCollectionProperty(string memory key, bytes memory value) external;
+ /// Set collection properties.
+ ///
+ /// @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;
+
/// Delete collection property.
///
/// @param key Property key.
@@ -79,6 +94,13 @@
/// or in textual repr: deleteCollectionProperty(string)
function deleteCollectionProperty(string memory key) external;
+ /// Delete collection properties.
+ ///
+ /// @param keys Properties keys.
+ /// @dev EVM selector for this function is: 0xee206ee3,
+ /// or in textual repr: deleteCollectionProperties(string[])
+ function deleteCollectionProperties(string[] memory keys) external;
+
/// Get collection property.
///
/// @dev Throws error if key not found.
@@ -89,6 +111,14 @@
/// or in textual repr: collectionProperty(string)
function collectionProperty(string memory key) external view returns (bytes memory);
+ /// Get collection properties.
+ ///
+ /// @param keys Properties keys. Empty keys for all propertyes.
+ /// @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);
+
/// Set the sponsor of the collection.
///
/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
@@ -98,6 +128,15 @@
/// or in textual repr: setCollectionSponsor(address)
function setCollectionSponsor(address sponsor) external;
+ /// Set the sponsor of the collection.
+ ///
+ /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+ ///
+ /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
+ /// @dev EVM selector for this function is: 0x84a1d5a8,
+ /// or in textual repr: setCollectionSponsorCross((address,uint256))
+ function setCollectionSponsorCross(Tuple6 memory sponsor) external;
+
/// Whether there is a pending sponsor.
/// @dev EVM selector for this function is: 0x058ac185,
/// or in textual repr: hasCollectionPendingSponsor()
@@ -120,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 (Tuple17 memory);
+ function collectionSponsor() external view returns (Tuple6 memory);
/// Set limits for the collection.
/// @dev Throws error if limit not found.
@@ -153,6 +192,18 @@
function contractAddress() external view returns (address);
/// Add collection admin.
+ /// @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;
+
+ /// 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;
+
+ /// Add collection admin.
/// @param newAdmin Address of the added administrator.
/// @dev EVM selector for this function is: 0x92e462c7,
/// or in textual repr: addCollectionAdmin(address)
@@ -202,6 +253,13 @@
/// or in textual repr: addToCollectionAllowList(address)
function addToCollectionAllowList(address user) external;
+ /// Add user to allowed list.
+ ///
+ /// @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;
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -209,6 +267,13 @@
/// or in textual repr: removeFromCollectionAllowList(address)
function removeFromCollectionAllowList(address user) external;
+ /// Remove user from allowed list.
+ ///
+ /// @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;
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -224,6 +289,14 @@
/// or in textual repr: isOwnerOrAdmin(address)
function isOwnerOrAdmin(address user) external view returns (bool);
+ /// Check that account is the owner or admin of the collection
+ ///
+ /// @param user User cross account to verify
+ /// @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);
+
/// Returns collection type
///
/// @return `Fungible` or `NFT` or `ReFungible`
@@ -233,11 +306,11 @@
/// Get collection owner.
///
- /// @return Tuble with sponsor address and his substrate mirror.
+ /// @return Tuple 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 (Tuple17 memory);
+ function collectionOwner() external view returns (Tuple6 memory);
/// Changes collection owner to another account
///
@@ -246,12 +319,28 @@
/// @dev EVM selector for this function is: 0x4f53e226,
/// or in textual repr: changeCollectionOwner(address)
function changeCollectionOwner(address newOwner) external;
+
+ /// Get collection administrators
+ ///
+ /// @return Vector of tuples with admins address and his substrate mirror.
+ /// 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);
+
+ /// Changes collection owner to another account
+ ///
+ /// @dev Owner can be changed only by current owner
+ /// @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;
}
/// @dev anonymous struct
-struct Tuple17 {
- address field_0;
- uint256 field_1;
+struct Tuple19 {
+ string field_0;
+ bytes field_1;
}
/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
@@ -347,7 +436,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xef1eaacb
+/// @dev the ERC-165 identifier for this interface is 0x81feb398
interface ERC721UniqueExtensions is Dummy, ERC165 {
/// @notice A descriptive name for a collection of NFTs in this contract
/// @dev EVM selector for this function is: 0x06fdde03,
@@ -369,6 +458,20 @@
/// or in textual repr: transfer(address,uint256)
function transfer(address to, uint256 tokenId) external;
+ /// @notice Transfer ownership of an RFT
+ /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
+ /// is the zero address. Throws if `tokenId` is not a valid RFT.
+ /// Throws if RFT pieces have multiple owners.
+ /// @param to The new owner
+ /// @param tokenId The RFT to transfer
+ /// @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,
+ uint256 tokenId
+ ) external;
+
/// @notice Burns a specific ERC721 token.
/// @dev Throws unless `msg.sender` is the current owner or an authorized
/// operator for this RFT. Throws if `from` is not the current owner. Throws
@@ -380,6 +483,17 @@
/// or in textual repr: burnFrom(address,uint256)
function burnFrom(address from, uint256 tokenId) external;
+ /// @notice Burns a specific ERC721 token.
+ /// @dev Throws unless `msg.sender` is the current owner or an authorized
+ /// operator for this RFT. Throws if `from` is not the current owner. Throws
+ /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.
+ /// Throws if RFT pieces have multiple owners.
+ /// @param from The current owner of the RFT
+ /// @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;
+
/// @notice Returns next free RFT ID.
/// @dev EVM selector for this function is: 0x75794a3c,
/// or in textual repr: nextTokenId()
@@ -401,7 +515,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, Tuple6[] memory tokens) external returns (bool);
+ // function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
/// Returns EVM address for refungible token
///
@@ -412,11 +526,17 @@
}
/// @dev anonymous struct
-struct Tuple6 {
+struct Tuple8 {
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
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x780e9d63
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -116,8 +116,8 @@
await checkInterface(helper, '0x780e9d63', true, true);
});
- itEth('ERC721UniqueExtensions - 0x4468500d - support', async ({helper}) => {
- await checkInterface(helper, '0x4468500d', true, true);
+ itEth('ERC721UniqueExtensions - 0x244543ee - support', async ({helper}) => {
+ await checkInterface(helper, '0x244543ee', true, true);
});
itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {
tests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -49,18 +49,38 @@
.to.be.eq(newAdmin.toLocaleLowerCase());
});
- itEth.skip('Add substrate admin by owner', async ({helper}) => {
+ itEth('Add cross account admin by owner', 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 newAdmin = await privateKey('//Bob');
+ const newAdminCross = helper.ethCrossAccount.fromKeyringPair(newAdmin);
+ await collectionEvm.methods.addCollectionAdminCross(newAdminCross).send();
- const [newAdmin] = await helper.arrange.createAccounts([10n], donor);
- await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();
+ const adminList = await helper.collection.getAdmins(collectionId);
+ expect(adminList).to.be.like([{Substrate: newAdmin.address}]);
+ });
- const adminList = await helper.callRpc('api.rpc.unique.adminlist', [collectionId]);
- expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())
- .to.be.eq(newAdmin.address.toLocaleLowerCase());
- });
+ // 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 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 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);
@@ -68,11 +88,31 @@
const newAdmin = helper.eth.createAccount();
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
expect(await collectionEvm.methods.isOwnerOrAdmin(newAdmin).call()).to.be.false;
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);
const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
tests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -19,6 +19,19 @@
"type": "event"
},
{
+ "anonymous": false,
+ "inputs": [
+ {
+ "indexed": true,
+ "internalType": "address",
+ "name": "collectionId",
+ "type": "address"
+ }
+ ],
+ "name": "CollectionDestroyed",
+ "type": "event"
+ },
+ {
"inputs": [],
"name": "collectionCreationFee",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
@@ -28,6 +41,18 @@
{
"inputs": [
{ "internalType": "string", "name": "name", "type": "string" },
+ { "internalType": "uint8", "name": "decimals", "type": "uint8" },
+ { "internalType": "string", "name": "description", "type": "string" },
+ { "internalType": "string", "name": "tokenPrefix", "type": "string" }
+ ],
+ "name": "createFTCollection",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "payable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "string", "name": "name", "type": "string" },
{ "internalType": "string", "name": "description", "type": "string" },
{ "internalType": "string", "name": "tokenPrefix", "type": "string" }
],
@@ -55,6 +80,19 @@
"type": "address"
}
],
+ "name": "destroyCollection",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "internalType": "address",
+ "name": "collectionAddress",
+ "type": "address"
+ }
+ ],
"name": "isCollectionExist",
"outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "view",
tests/src/eth/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -18,6 +18,7 @@
import {Pallets} from '../util';
import {IProperty, ITokenPropertyPermission} from '../util/playgrounds/types';
import {IKeyringPair} from '@polkadot/types/types';
+import {TCollectionMode} from '../util/playgrounds/types';
describe('EVM collection properties', () => {
let donor: IKeyringPair;
@@ -161,3 +162,91 @@
await checkERC721Metadata(helper, 'rft');
});
});
+
+describe('EVM collection property', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_helper, privateKey) => {
+ donor = await privateKey({filename: __filename});
+ });
+ });
+
+ async function testSetReadProperties(helper: EthUniqueHelper, mode: TCollectionMode) {
+ const collection = await helper[mode].mintCollection(donor, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+ const sender = await helper.eth.createAccountWithBalance(donor, 100n);
+ await collection.addAdmin(donor, {Ethereum: sender});
+
+ const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(collectionAddress, mode, sender);
+
+ const keys = ['key0', 'key1'];
+
+ const writeProperties = [
+ helper.ethProperty.property(keys[0], 'value0'),
+ helper.ethProperty.property(keys[1], 'value1'),
+ ];
+
+ await contract.methods.setCollectionProperties(writeProperties).send();
+ const readProperties = await contract.methods.collectionProperties([keys[0], keys[1]]).call();
+ expect(readProperties).to.be.like(writeProperties);
+ }
+
+ itEth('Set/read properties ft', async ({helper}) => {
+ await testSetReadProperties(helper, 'ft');
+ });
+ itEth.ifWithPallets('Set/read properties rft', [Pallets.ReFungible], async ({helper}) => {
+ await testSetReadProperties(helper, 'rft');
+ });
+ itEth('Set/read properties nft', async ({helper}) => {
+ await testSetReadProperties(helper, 'nft');
+ });
+
+ async function testDeleteProperties(helper: EthUniqueHelper, mode: TCollectionMode) {
+ const collection = await helper[mode].mintCollection(donor, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+ const sender = await helper.eth.createAccountWithBalance(donor, 100n);
+ await collection.addAdmin(donor, {Ethereum: sender});
+
+ const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(collectionAddress, mode, sender);
+
+ const keys = ['key0', 'key1', 'key2', 'key3'];
+
+ {
+ const writeProperties = [
+ helper.ethProperty.property(keys[0], 'value0'),
+ helper.ethProperty.property(keys[1], 'value1'),
+ helper.ethProperty.property(keys[2], 'value2'),
+ helper.ethProperty.property(keys[3], 'value3'),
+ ];
+
+ await contract.methods.setCollectionProperties(writeProperties).send();
+ const readProperties = await contract.methods.collectionProperties([keys[0], keys[1], keys[2], keys[3]]).call();
+ expect(readProperties).to.be.like(writeProperties);
+ }
+
+ {
+ const expectProperties = [
+ helper.ethProperty.property(keys[0], 'value0'),
+ helper.ethProperty.property(keys[1], 'value1'),
+ ];
+
+ await contract.methods.deleteCollectionProperties([keys[2], keys[3]]).send();
+ const readProperties = await contract.methods.collectionProperties([]).call();
+ expect(readProperties).to.be.like(expectProperties);
+ }
+ }
+
+ itEth('Delete properties ft', async ({helper}) => {
+ await testDeleteProperties(helper, 'ft');
+ });
+ itEth.ifWithPallets('Delete properties rft', [Pallets.ReFungible], async ({helper}) => {
+ await testDeleteProperties(helper, 'rft');
+ });
+ itEth('Delete properties nft', async ({helper}) => {
+ await testDeleteProperties(helper, 'nft');
+ });
+
+});
tests/src/eth/createFTCollection.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/createFTCollection.test.ts
@@ -0,0 +1,262 @@
+// 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 {evmToAddress} from '@polkadot/util-crypto';
+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;
+ });
+
+ itEth('Set sponsorship', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ const ss58Format = helper.chain.getChainProperties().ss58Format;
+ const {collectionId, collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Sponsor', DECIMALS, 'absolutely anything', 'ENVY');
+
+ const collection = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+ await collection.methods.setCollectionSponsor(sponsor).send();
+
+ let data = (await helper.rft.getData(collectionId))!;
+ expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
+
+ await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+
+ const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);
+ await sponsorCollection.methods.confirmCollectionSponsorship().send();
+
+ data = (await helper.rft.getData(collectionId))!;
+ expect(data.raw.sponsorship.Confirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
+ });
+
+ itEth('Set limits', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionId, collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Limits', DECIMALS, 'absolutely anything', 'INSI');
+ const limits = {
+ accountTokenOwnershipLimit: 1000,
+ sponsoredDataSize: 1024,
+ sponsoredDataRateLimit: 30,
+ tokenLimit: 1000000,
+ sponsorTransferTimeout: 6,
+ sponsorApproveTimeout: 6,
+ ownerCanTransfer: false,
+ ownerCanDestroy: false,
+ transfersEnabled: false,
+ };
+
+ const collection = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+ await collection.methods['setCollectionLimit(string,uint32)']('accountTokenOwnershipLimit', limits.accountTokenOwnershipLimit).send();
+ await collection.methods['setCollectionLimit(string,uint32)']('sponsoredDataSize', limits.sponsoredDataSize).send();
+ await collection.methods['setCollectionLimit(string,uint32)']('sponsoredDataRateLimit', limits.sponsoredDataRateLimit).send();
+ await collection.methods['setCollectionLimit(string,uint32)']('tokenLimit', limits.tokenLimit).send();
+ await collection.methods['setCollectionLimit(string,uint32)']('sponsorTransferTimeout', limits.sponsorTransferTimeout).send();
+ await collection.methods['setCollectionLimit(string,uint32)']('sponsorApproveTimeout', limits.sponsorApproveTimeout).send();
+ await collection.methods['setCollectionLimit(string,bool)']('ownerCanTransfer', limits.ownerCanTransfer).send();
+ await collection.methods['setCollectionLimit(string,bool)']('ownerCanDestroy', limits.ownerCanDestroy).send();
+ await collection.methods['setCollectionLimit(string,bool)']('transfersEnabled', limits.transfersEnabled).send();
+
+ const data = (await helper.rft.getData(collectionId))!;
+ expect(data.raw.limits.accountTokenOwnershipLimit).to.be.eq(limits.accountTokenOwnershipLimit);
+ expect(data.raw.limits.sponsoredDataSize).to.be.eq(limits.sponsoredDataSize);
+ expect(data.raw.limits.sponsoredDataRateLimit.blocks).to.be.eq(limits.sponsoredDataRateLimit);
+ expect(data.raw.limits.tokenLimit).to.be.eq(limits.tokenLimit);
+ expect(data.raw.limits.sponsorTransferTimeout).to.be.eq(limits.sponsorTransferTimeout);
+ expect(data.raw.limits.sponsorApproveTimeout).to.be.eq(limits.sponsorApproveTimeout);
+ expect(data.raw.limits.ownerCanTransfer).to.be.eq(limits.ownerCanTransfer);
+ expect(data.raw.limits.ownerCanDestroy).to.be.eq(limits.ownerCanDestroy);
+ expect(data.raw.limits.transfersEnabled).to.be.eq(limits.transfersEnabled);
+ });
+
+ itEth('Collection address exist', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
+ expect(await helper.ethNativeContract.collectionHelpers(collectionAddressForNonexistentCollection)
+ .methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
+ .to.be.false;
+
+ const {collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Exister', DECIMALS, 'absolutely anything', 'WIWT');
+ expect(await helper.ethNativeContract.collectionHelpers(collectionAddress)
+ .methods.isCollectionExist(collectionAddress).call())
+ .to.be.true;
+ });
+
+ itEth('destroyCollection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Exister', DECIMALS, 'absolutely anything', 'WIWT');
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+
+ const result = await collectionHelper.methods
+ .destroyCollection(collectionAddress)
+ .send({from: owner});
+
+ const events = helper.eth.normalizeEvents(result.events);
+
+ expect(events).to.be.deep.equal([
+ {
+ address: collectionHelper.options.address,
+ event: 'CollectionDestroyed',
+ args: {
+ collectionId: collectionAddress,
+ },
+ },
+ ]);
+
+ expect(await collectionHelper.methods
+ .isCollectionExist(collectionAddress)
+ .call()).to.be.false;
+ });
+});
+
+describe('(!negative tests!) Create FT collection from EVM', () => {
+ let donor: IKeyringPair;
+ let nominal: bigint;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.Fungible]);
+ donor = await privateKey({filename: __filename});
+ nominal = helper.balance.getOneTokenNominal();
+ });
+ });
+
+ itEth('(!negative test!) Create collection (bad lengths)', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+ {
+ const MAX_NAME_LENGTH = 64;
+ const collectionName = 'A'.repeat(MAX_NAME_LENGTH + 1);
+ const description = 'A';
+ const tokenPrefix = 'A';
+
+ await expect(collectionHelper.methods
+ .createFTCollection(collectionName, DECIMALS, description, tokenPrefix)
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
+ }
+ {
+ const MAX_DESCRIPTION_LENGTH = 256;
+ const collectionName = 'A';
+ const description = 'A'.repeat(MAX_DESCRIPTION_LENGTH + 1);
+ const tokenPrefix = 'A';
+ await expect(collectionHelper.methods
+ .createFTCollection(collectionName, DECIMALS, description, tokenPrefix)
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
+ }
+ {
+ const MAX_TOKEN_PREFIX_LENGTH = 16;
+ const collectionName = 'A';
+ const description = 'A';
+ const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
+ await expect(collectionHelper.methods
+ .createFTCollection(collectionName, DECIMALS, description, tokenPrefix)
+ .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
+ }
+ });
+
+ itEth('(!negative test!) Create collection (no funds)', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+ await expect(collectionHelper.methods
+ .createFTCollection('Peasantry', DECIMALS, 'absolutely anything', 'TWIW')
+ .call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+ });
+
+ itEth('(!negative test!) Check owner', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const peasant = helper.eth.createAccount();
+ const {collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Transgressed', DECIMALS, 'absolutely anything', 'YVNE');
+ const peasantCollection = helper.ethNativeContract.collection(collectionAddress, 'ft', peasant);
+ const EXPECTED_ERROR = 'NoPermission';
+ {
+ const sponsor = await helper.eth.createAccountWithBalance(donor);
+ await expect(peasantCollection.methods
+ .setCollectionSponsor(sponsor)
+ .call()).to.be.rejectedWith(EXPECTED_ERROR);
+
+ const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'ft', sponsor);
+ await expect(sponsorCollection.methods
+ .confirmCollectionSponsorship()
+ .call()).to.be.rejectedWith('caller is not set as sponsor');
+ }
+ {
+ await expect(peasantCollection.methods
+ .setCollectionLimit('account_token_ownership_limit', '1000')
+ .call()).to.be.rejectedWith(EXPECTED_ERROR);
+ }
+ });
+
+ itEth('(!negative test!) Set limits', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Limits', DECIMALS, 'absolutely anything', 'ISNI');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+ await expect(collectionEvm.methods
+ .setCollectionLimit('badLimit', 'true')
+ .call()).to.be.rejectedWith('unknown boolean limit "badLimit"');
+ });
+});
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -22,7 +22,7 @@
describe('Create NFT collection from EVM', () => {
let donor: IKeyringPair;
- before(async function() {
+ before(async function () {
await usingEthPlaygrounds(async (_helper, privateKey) => {
donor = await privateKey({filename: __filename});
});
@@ -35,10 +35,28 @@
const description = 'Some description';
const prefix = 'token prefix';
- const {collectionId} = await helper.eth.createNFTCollection(owner, name, description, prefix);
- const data = (await helper.rft.getData(collectionId))!;
+ // 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);
@@ -57,8 +75,19 @@
const prefix = 'token prefix';
const baseUri = 'BaseURI';
- const {collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, name, description, prefix, baseUri);
+ const {collectionId, collectionAddress, events} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, name, description, prefix, baseUri);
+ expect(events).to.be.deep.equal([
+ {
+ address: '0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F',
+ event: 'CollectionCreated',
+ args: {
+ owner: owner,
+ collectionId: collectionAddress,
+ },
+ },
+ ]);
+
const collection = helper.nft.getCollectionObject(collectionId);
const data = (await collection.getData())!;
@@ -95,12 +124,12 @@
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}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const sponsor = await helper.eth.createAccountWithBalance(donor);
@@ -147,7 +176,7 @@
await collection.methods['setCollectionLimit(string,bool)']('ownerCanTransfer', limits.ownerCanTransfer).send();
await collection.methods['setCollectionLimit(string,bool)']('ownerCanDestroy', limits.ownerCanDestroy).send();
await collection.methods['setCollectionLimit(string,bool)']('transfersEnabled', limits.transfersEnabled).send();
-
+
const data = (await helper.nft.getData(collectionId))!;
expect(data.raw.limits.accountTokenOwnershipLimit).to.be.eq(limits.accountTokenOwnershipLimit);
expect(data.raw.limits.sponsoredDataSize).to.be.eq(limits.sponsoredDataSize);
@@ -166,7 +195,7 @@
expect(await helper.ethNativeContract.collectionHelpers(collectionAddressForNonexistentCollection)
.methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
.to.be.false;
-
+
const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Exister', 'absolutely anything', 'EVC');
expect(await helper.ethNativeContract.collectionHelpers(collectionAddress)
.methods.isCollectionExist(collectionAddress).call())
@@ -178,7 +207,7 @@
let donor: IKeyringPair;
let nominal: bigint;
- before(async function() {
+ before(async function () {
await usingEthPlaygrounds(async (helper, privateKey) => {
donor = await privateKey({filename: __filename});
nominal = helper.balance.getOneTokenNominal();
@@ -197,7 +226,7 @@
await expect(collectionHelper.methods
.createNFTCollection(collectionName, description, tokenPrefix)
.call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
-
+
}
{
const MAX_DESCRIPTION_LENGTH = 256;
@@ -218,7 +247,7 @@
.call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
}
});
-
+
itEth('(!negative test!) Create collection (no funds)', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
@@ -238,7 +267,7 @@
await expect(malfeasantCollection.methods
.setCollectionSponsor(sponsor)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
-
+
const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor);
await expect(sponsorCollection.methods
.confirmCollectionSponsorship()
@@ -259,4 +288,31 @@
.setCollectionLimit('badLimit', 'true')
.call()).to.be.rejectedWith('unknown boolean limit "badLimit"');
});
-});
+
+ itEth('destroyCollection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Limits', 'absolutely anything', 'OLF');
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+
+
+ const result = await collectionHelper.methods
+ .destroyCollection(collectionAddress)
+ .send({from: owner});
+
+ const events = helper.eth.normalizeEvents(result.events);
+
+ expect(events).to.be.deep.equal([
+ {
+ address: collectionHelper.options.address,
+ event: 'CollectionDestroyed',
+ args: {
+ collectionId: collectionAddress,
+ },
+ },
+ ]);
+
+ expect(await collectionHelper.methods
+ .isCollectionExist(collectionAddress)
+ .call()).to.be.false;
+ });
+});
\ No newline at end of file
tests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -263,4 +263,18 @@
.setCollectionLimit('badLimit', 'true')
.call()).to.be.rejectedWith('unknown boolean limit "badLimit"');
});
+
+ itEth('destroyCollection', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Limits', 'absolutely anything', 'OLF');
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+
+ await expect(collectionHelper.methods
+ .destroyCollection(collectionAddress)
+ .send({from: owner})).to.be.fulfilled;
+
+ expect(await collectionHelper.methods
+ .isCollectionExist(collectionAddress)
+ .call()).to.be.false;
+ });
});
tests/src/eth/destroyCollection.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/destroyCollection.test.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';
+
+
+describe('Destroy Collection from EVM', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.ReFungible, Pallets.NFT]);
+ donor = await privateKey({filename: __filename});
+ });
+ });
+
+
+ itEth('(!negative test!) RFT', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const signer = await helper.eth.createAccountWithBalance(donor);
+
+ const unexistedCollection = helper.ethAddress.fromCollectionId(1000000);
+
+ const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Limits', 'absolutely anything', 'OLF');
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(signer);
+
+ await expect(collectionHelper.methods
+ .destroyCollection(collectionAddress)
+ .send({from: signer})).to.be.rejected;
+
+ await expect(collectionHelper.methods
+ .destroyCollection(unexistedCollection)
+ .send({from: signer})).to.be.rejected;
+
+ expect(await collectionHelper.methods
+ .isCollectionExist(unexistedCollection)
+ .call()).to.be.false;
+ });
+
+ itEth('(!negative test!) NFT', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const signer = await helper.eth.createAccountWithBalance(donor);
+
+ const unexistedCollection = helper.ethAddress.fromCollectionId(1000000);
+
+ const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Limits', 'absolutely anything', 'OLF');
+ const collectionHelper = helper.ethNativeContract.collectionHelpers(signer);
+
+ await expect(collectionHelper.methods
+ .destroyCollection(collectionAddress)
+ .send({from: signer})).to.be.rejected;
+
+ await expect(collectionHelper.methods
+ .destroyCollection(unexistedCollection)
+ .send({from: signer})).to.be.rejected;
+
+ expect(await collectionHelper.methods
+ .isCollectionExist(unexistedCollection)
+ .call()).to.be.false;
+ });
+});
tests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth--- a/tests/src/eth/fractionalizer/Fractionalizer.sol
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -84,7 +84,11 @@
) external payable onlyOwner {
require(rftCollection == address(0), "RFT collection is already set");
address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;
- rftCollection = CollectionHelpers(collectionHelpers).createRFTCollection{value: msg.value}(_name, _description, _tokenPrefix);
+ rftCollection = CollectionHelpers(collectionHelpers).createRFTCollection{value: msg.value}(
+ _name,
+ _description,
+ _tokenPrefix
+ );
emit RFTCollectionSet(rftCollection);
}
tests/src/eth/fungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -148,6 +148,49 @@
}
});
+ itEth('Can perform burnFromCross()', async ({helper, privateKey}) => {
+ const alice = await privateKey('//Alice');
+ const sender = await helper.eth.createAccountWithBalance(alice, 100n);
+
+ const collection = await helper.ft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);
+
+ await collection.mint(alice, 200n, {Substrate: alice.address});
+ await collection.approveTokens(alice, {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 ownerCross = helper.ethCrossAccount.fromKeyringPair(alice);
+ const result = await contract.methods.burnFromCross(ownerCross, 49).send({from: sender});
+ const events = result.events;
+
+ expect(events).to.be.like({
+ Transfer: {
+ address: helper.ethAddress.fromCollectionId(collection.collectionId),
+ event: 'Transfer',
+ returnValues: {
+ from: helper.address.substrateToEth(alice.address),
+ to: '0x0000000000000000000000000000000000000000',
+ value: '49',
+ },
+ },
+ Approval: {
+ address: helper.ethAddress.fromCollectionId(collection.collectionId),
+ returnValues: {
+ owner: helper.address.substrateToEth(alice.address),
+ spender: sender,
+ value: '51',
+ },
+ event: 'Approval',
+ },
+ });
+
+ const fromBalanceAfter = await collection.getBalance({Substrate: alice.address});
+ expect(fromBalanceBefore - fromBalanceAfter).to.be.eq(49n);
+ });
+
itEth('Can perform transferFrom()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const spender = await helper.eth.createAccountWithBalance(donor);
@@ -216,6 +259,54 @@
expect(+balance).to.equal(50);
}
});
+
+ itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
+ const alice = await privateKey('//Alice');
+ const sender = await helper.eth.createAccountWithBalance(alice, 100n);
+
+ const collection = await helper.ft.mintCollection(alice, {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);
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'ft');
+
+ const from = helper.ethCrossAccount.fromKeyringPair(alice);
+ const to = helper.ethCrossAccount.fromAddress(receiver);
+
+ const fromBalanceBefore = await collection.getBalance({Substrate: alice.address});
+ const toBalanceBefore = await collection.getBalance({Ethereum: receiver});
+
+ const result = await contract.methods.transferFromCross(from, to, 51).send({from: sender});
+
+ expect(result.events).to.be.like({
+ Transfer: {
+ address,
+ event: 'Transfer',
+ returnValues: {
+ from: helper.address.substrateToEth(alice.address),
+ to: receiver,
+ value: '51',
+ },
+ },
+ Approval: {
+ address,
+ event: 'Approval',
+ returnValues: {
+ owner: helper.address.substrateToEth(alice.address),
+ spender: sender,
+ value: '49',
+ },
+ }});
+
+ const fromBalanceAfter = await collection.getBalance({Substrate: alice.address});
+ expect(fromBalanceBefore - fromBalanceAfter).to.be.eq(51n);
+ const toBalanceAfter = await collection.getBalance({Ethereum: receiver});
+ expect(toBalanceAfter - toBalanceBefore).to.be.eq(51n);
+ });
});
describe('Fungible: Fees', () => {
@@ -362,4 +453,44 @@
expect(event.returnValues.to).to.be.equal(receiver);
expect(event.returnValues.value).to.be.equal('51');
});
+
+ itEth('Events emitted for transferFromCross()', async ({helper, privateKey}) => {
+ const alice = await privateKey('//Alice');
+ const sender = await helper.eth.createAccountWithBalance(alice, 100n);
+
+ const collection = await helper.ft.mintCollection(alice, {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);
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'ft');
+
+ const from = helper.ethCrossAccount.fromKeyringPair(alice);
+ const to = helper.ethCrossAccount.fromAddress(receiver);
+
+ const result = await contract.methods.transferFromCross(from, to, 51).send({from: sender});
+
+ expect(result.events).to.be.like({
+ Transfer: {
+ address,
+ event: 'Transfer',
+ returnValues: {
+ from: helper.address.substrateToEth(alice.address),
+ to: receiver,
+ value: '51',
+ },
+ },
+ Approval: {
+ address,
+ event: 'Approval',
+ returnValues: {
+ owner: helper.address.substrateToEth(alice.address),
+ spender: sender,
+ value: '49',
+ },
+ }});
+ });
});
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -60,6 +60,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "newAdmin",
+ "type": "tuple"
+ }
+ ],
+ "name": "addCollectionAdminCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "user", "type": "address" }
],
"name": "addToCollectionAllowList",
@@ -69,6 +86,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "user",
+ "type": "tuple"
+ }
+ ],
+ "name": "addToCollectionAllowListCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "owner", "type": "address" },
{ "internalType": "address", "name": "spender", "type": "address" }
],
@@ -98,6 +132,24 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "spender",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "approveCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "owner", "type": "address" }
],
"name": "balanceOf",
@@ -117,6 +169,24 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "from",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "burnFromCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "newOwner", "type": "address" }
],
"name": "changeCollectionOwner",
@@ -126,6 +196,23 @@
},
{
"inputs": [],
+ "name": "collectionAdmins",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "collectionOwner",
"outputs": [
{
@@ -142,6 +229,25 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "string[]", "name": "keys", "type": "string[]" }
+ ],
+ "name": "collectionProperties",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ ],
+ "internalType": "struct Tuple10[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "collectionProperty",
"outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
@@ -187,6 +293,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "string[]", "name": "keys", "type": "string[]" }
+ ],
+ "name": "deleteCollectionProperties",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "deleteCollectionProperty",
"outputs": [],
@@ -211,6 +326,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "user",
+ "type": "tuple"
+ }
+ ],
+ "name": "isOwnerOrAdminCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "amount", "type": "uint256" }
],
@@ -253,6 +385,23 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "admin",
+ "type": "tuple"
+ }
+ ],
+ "name": "removeCollectionAdminCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "removeCollectionSponsor",
"outputs": [],
@@ -269,6 +418,23 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "user",
+ "type": "tuple"
+ }
+ ],
+ "name": "removeFromCollectionAllowListCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "uint8", "name": "mode", "type": "uint8" }],
"name": "setCollectionAccess",
"outputs": [],
@@ -325,6 +491,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ ],
+ "internalType": "struct Tuple10[]",
+ "name": "properties",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "setCollectionProperties",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "string", "name": "key", "type": "string" },
{ "internalType": "bytes", "name": "value", "type": "bytes" }
],
@@ -344,6 +527,40 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "sponsor",
+ "type": "tuple"
+ }
+ ],
+ "name": "setCollectionSponsorCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "newOwner",
+ "type": "tuple"
+ }
+ ],
+ "name": "setOwnerCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
],
"name": "supportsInterface",
@@ -387,6 +604,33 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "from",
+ "type": "tuple"
+ },
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "to",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "transferFromCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "uniqueCollectionType",
"outputs": [{ "internalType": "string", "name": "", "type": "string" }],
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -246,6 +246,64 @@
}
});
+ 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'});
+
+ const owner = await privateKey('//Bob');
+ const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+
+ const token = await collection.mintToken(alice, {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 result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender});
+ const events = result.events.Transfer;
+
+ expect(events).to.be.like({
+ address,
+ event: 'Transfer',
+ returnValues: {
+ from: helper.address.substrateToEth(owner.address),
+ to: '0x0000000000000000000000000000000000000000',
+ tokenId: token.tokenId.toString(),
+ },
+ });
+ }
+ });
+
+ 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'});
+
+ const owner = await helper.eth.createAccountWithBalance(alice, 100n);
+ const receiver = await privateKey('//Charlie');
+
+ const token = await collection.mintToken(alice, {Ethereum: owner});
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'nft');
+
+ {
+ const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+ const result = await contract.methods.approveCross(recieverCross, token.tokenId).send({from: owner});
+ const event = result.events.Approval;
+ expect(event).to.be.like({
+ address: helper.ethAddress.fromCollectionId(collection.collectionId),
+ event: 'Approval',
+ returnValues: {
+ owner,
+ approved: helper.address.substrateToEth(receiver.address),
+ tokenId: token.tokenId.toString(),
+ },
+ });
+ }
+ });
+
itEth('Can perform transferFrom()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const spender = await helper.eth.createAccountWithBalance(donor);
@@ -351,6 +409,40 @@
expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
});
+ 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 owner = await privateKey('//Bob');
+ const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+ const receiver = await privateKey('//Charlie');
+
+ const token = await collection.mintToken(alice, {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('transfer() call fee is less than 0.2UNQ', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -91,6 +91,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "newAdmin",
+ "type": "tuple"
+ }
+ ],
+ "name": "addCollectionAdminCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "user", "type": "address" }
],
"name": "addToCollectionAllowList",
@@ -100,6 +117,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "user",
+ "type": "tuple"
+ }
+ ],
+ "name": "addToCollectionAllowListCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "user", "type": "address" }
],
"name": "allowed",
@@ -119,6 +153,24 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "approved",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "approveCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "owner", "type": "address" }
],
"name": "balanceOf",
@@ -147,6 +199,24 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "from",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "burnFromCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "newOwner", "type": "address" }
],
"name": "changeCollectionOwner",
@@ -156,6 +226,23 @@
},
{
"inputs": [],
+ "name": "collectionAdmins",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "collectionOwner",
"outputs": [
{
@@ -163,7 +250,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple17",
+ "internalType": "struct Tuple6",
"name": "",
"type": "tuple"
}
@@ -172,6 +259,25 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "string[]", "name": "keys", "type": "string[]" }
+ ],
+ "name": "collectionProperties",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ ],
+ "internalType": "struct Tuple19[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "collectionProperty",
"outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
@@ -187,7 +293,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple17",
+ "internalType": "struct Tuple6",
"name": "",
"type": "tuple"
}
@@ -210,6 +316,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "string[]", "name": "keys", "type": "string[]" }
+ ],
+ "name": "deleteCollectionProperties",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "deleteCollectionProperty",
"outputs": [],
@@ -269,6 +384,23 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "user",
+ "type": "tuple"
+ }
+ ],
+ "name": "isOwnerOrAdminCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
"name": "mint",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
@@ -335,6 +467,23 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "admin",
+ "type": "tuple"
+ }
+ ],
+ "name": "removeCollectionAdminCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "removeCollectionSponsor",
"outputs": [],
@@ -352,6 +501,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "user",
+ "type": "tuple"
+ }
+ ],
+ "name": "removeFromCollectionAllowListCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "from", "type": "address" },
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
@@ -440,6 +606,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ ],
+ "internalType": "struct Tuple19[]",
+ "name": "properties",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "setCollectionProperties",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "string", "name": "key", "type": "string" },
{ "internalType": "bytes", "name": "value", "type": "bytes" }
],
@@ -459,6 +642,58 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "sponsor",
+ "type": "tuple"
+ }
+ ],
+ "name": "setCollectionSponsorCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "newOwner",
+ "type": "tuple"
+ }
+ ],
+ "name": "setOwnerCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ ],
+ "internalType": "struct Tuple19[]",
+ "name": "properties",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "setProperties",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{ "internalType": "string", "name": "key", "type": "string" },
{ "internalType": "bytes", "name": "value", "type": "bytes" }
@@ -553,6 +788,33 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "from",
+ "type": "tuple"
+ },
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "to",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "transferFromCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "uniqueCollectionType",
"outputs": [{ "internalType": "string", "name": "", "type": "string" }],
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -227,6 +227,108 @@
}
});
+ 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'});
+
+ const owner = await helper.eth.createAccountWithBalance(alice, 100n);
+ const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+
+ const token = await collection.mintToken(alice, 100n, {Ethereum: owner});
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'rft');
+
+ const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);
+ const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, owner);
+ await tokenContract.methods.repartition(15).send();
+ await tokenContract.methods.approve(spender, 15).send();
+
+ {
+ const result = await contract.methods.burnFrom(owner, 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: owner,
+ to: '0x0000000000000000000000000000000000000000',
+ tokenId: token.tokenId.toString(),
+ },
+ });
+ }
+
+ 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);
+
+ const token = await collection.mintToken(alice, 100n, {Substrate: owner.address});
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'rft');
+
+ await token.repartition(owner, 15n);
+ await token.approve(owner, {Ethereum: spender}, 15n);
+
+ {
+ const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);
+ const result = await contract.methods.burnFromCross(ownerCross, 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: '0x0000000000000000000000000000000000000000',
+ tokenId: token.tokenId.toString(),
+ },
+ });
+ }
+
+ 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'});
+
+ const owner = await privateKey('//Bob');
+ const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+ const receiver = await privateKey('//Charlie');
+
+ const token = await collection.mintToken(alice, 100n, {Substrate: owner.address});
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'rft');
+
+ await token.repartition(owner, 15n);
+ await token.approve(owner, {Ethereum: spender}, 15n);
+
+ {
+ 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.getTop10Owners()).to.be.like([{Substrate: receiver.address}]);
+ });
+
itEth('Can perform transfer()', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -91,6 +91,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "newAdmin",
+ "type": "tuple"
+ }
+ ],
+ "name": "addCollectionAdminCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "user", "type": "address" }
],
"name": "addToCollectionAllowList",
@@ -100,6 +117,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "user",
+ "type": "tuple"
+ }
+ ],
+ "name": "addToCollectionAllowListCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "user", "type": "address" }
],
"name": "allowed",
@@ -147,6 +181,24 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "from",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "burnFromCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "newOwner", "type": "address" }
],
"name": "changeCollectionOwner",
@@ -156,6 +208,23 @@
},
{
"inputs": [],
+ "name": "collectionAdmins",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "collectionOwner",
"outputs": [
{
@@ -163,7 +232,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple17",
+ "internalType": "struct Tuple6",
"name": "",
"type": "tuple"
}
@@ -172,6 +241,25 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "string[]", "name": "keys", "type": "string[]" }
+ ],
+ "name": "collectionProperties",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ ],
+ "internalType": "struct Tuple19[]",
+ "name": "",
+ "type": "tuple[]"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "collectionProperty",
"outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
@@ -187,7 +275,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple17",
+ "internalType": "struct Tuple6",
"name": "",
"type": "tuple"
}
@@ -210,6 +298,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "string[]", "name": "keys", "type": "string[]" }
+ ],
+ "name": "deleteCollectionProperties",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "deleteCollectionProperty",
"outputs": [],
@@ -269,6 +366,23 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "user",
+ "type": "tuple"
+ }
+ ],
+ "name": "isOwnerOrAdminCross",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
"name": "mint",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
@@ -335,6 +449,23 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "admin",
+ "type": "tuple"
+ }
+ ],
+ "name": "removeCollectionAdminCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "removeCollectionSponsor",
"outputs": [],
@@ -352,6 +483,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "user",
+ "type": "tuple"
+ }
+ ],
+ "name": "removeFromCollectionAllowListCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "from", "type": "address" },
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
@@ -440,6 +588,23 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ ],
+ "internalType": "struct Tuple19[]",
+ "name": "properties",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "setCollectionProperties",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "string", "name": "key", "type": "string" },
{ "internalType": "bytes", "name": "value", "type": "bytes" }
],
@@ -459,6 +624,58 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "sponsor",
+ "type": "tuple"
+ }
+ ],
+ "name": "setCollectionSponsorCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "newOwner",
+ "type": "tuple"
+ }
+ ],
+ "name": "setOwnerCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
+ {
+ "components": [
+ { "internalType": "string", "name": "field_0", "type": "string" },
+ { "internalType": "bytes", "name": "field_1", "type": "bytes" }
+ ],
+ "internalType": "struct Tuple19[]",
+ "name": "properties",
+ "type": "tuple[]"
+ }
+ ],
+ "name": "setProperties",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{ "internalType": "string", "name": "key", "type": "string" },
{ "internalType": "bytes", "name": "value", "type": "bytes" }
@@ -562,6 +779,33 @@
"type": "function"
},
{
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "from",
+ "type": "tuple"
+ },
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "to",
+ "type": "tuple"
+ },
+ { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
+ ],
+ "name": "transferFromCross",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [],
"name": "uniqueCollectionType",
"outputs": [{ "internalType": "string", "name": "", "type": "string" }],
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -16,6 +16,8 @@
import {itEth, usingEthPlaygrounds, expect} from './util';
import {IKeyringPair} from '@polkadot/types/types';
+import {ITokenPropertyPermission} from '../util/playgrounds/types';
+import {Pallets} from '../util';
describe('EVM token properties', () => {
let donor: IKeyringPair;
@@ -68,6 +70,64 @@
const [{value}] = await token.getProperties(['testKey']);
expect(value).to.equal('testValue');
});
+
+ itEth('Can be multiple set for NFT ', async({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+
+ const properties = Array(5).fill(0).map((_, i) => { return {field_0: `key_${i}`, field_1: Buffer.from(`value_${i}`)}; });
+ const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.field_0, permission: {tokenOwner: true,
+ collectionAdmin: true,
+ mutable: true}}; });
+
+ const collection = await helper.nft.mintCollection(alice, {
+ tokenPrefix: 'ethp',
+ tokenPropertyPermissions: permissions,
+ });
+
+ const token = await collection.mintToken(alice);
+
+ const valuesBefore = await token.getProperties(properties.map(p => p.field_0));
+ expect(valuesBefore).to.be.deep.equal([]);
+
+ await collection.addAdmin(alice, {Ethereum: caller});
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'nft', caller);
+
+ await contract.methods.setProperties(token.tokenId, properties).send({from: caller});
+
+ const values = await token.getProperties(properties.map(p => p.field_0));
+ expect(values).to.be.deep.equal(properties.map(p => { return {key: p.field_0, value: p.field_1.toString()}; }));
+ });
+
+ itEth.ifWithPallets('Can be multiple set for RFT ', [Pallets.ReFungible], async({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+
+ const properties = Array(5).fill(0).map((_, i) => { return {field_0: `key_${i}`, field_1: Buffer.from(`value_${i}`)}; });
+ const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.field_0, permission: {tokenOwner: true,
+ collectionAdmin: true,
+ mutable: true}}; });
+
+ const collection = await helper.rft.mintCollection(alice, {
+ tokenPrefix: 'ethp',
+ tokenPropertyPermissions: permissions,
+ });
+
+ const token = await collection.mintToken(alice);
+
+ const valuesBefore = await token.getProperties(properties.map(p => p.field_0));
+ expect(valuesBefore).to.be.deep.equal([]);
+
+ await collection.addAdmin(alice, {Ethereum: caller});
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = helper.ethNativeContract.collection(address, 'rft', caller);
+
+ await contract.methods.setProperties(token.tokenId, properties).send({from: caller});
+
+ const values = await token.getProperties(properties.map(p => p.field_0));
+ expect(values).to.be.deep.equal(properties.map(p => { return {key: p.field_0, value: p.field_1.toString()}; }));
+ });
itEth('Can be deleted', async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
tests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -13,3 +13,12 @@
event: string,
args: { [key: string]: string }
};
+export interface TEthCrossAccount {
+ readonly 0: string,
+ readonly 1: string | Uint8Array,
+ readonly field_0: string,
+ readonly field_1: 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
@@ -18,7 +18,7 @@
import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';
-import {ContractImports, CompiledContract, NormalizedEvent} from './types';
+import {ContractImports, CompiledContract, TEthCrossAccount, NormalizedEvent, EthProperty} from './types';
// Native contracts ABI
import collectionHelpersAbi from '../../collectionHelpersAbi.json';
@@ -28,6 +28,7 @@
import refungibleTokenAbi from '../../reFungibleTokenAbi.json';
import contractHelpersAbi from './../contractHelpersAbi.json';
import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';
+import {TCollectionMode} from '../../../util/playgrounds/types';
class EthGroupBase {
helper: EthUniqueHelper;
@@ -107,7 +108,7 @@
return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});
}
- collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {
+ collection(address: string, mode: TCollectionMode, caller?: string): Contract {
const abi = {
'nft': nonFungibleAbi,
'rft': refungibleAbi,
@@ -173,49 +174,59 @@
async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {
return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);
}
-
- async createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+
+ async createCollecion(functionName: string, signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
+
+ const result = await collectionHelper.methods[functionName](name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
- const result = await collectionHelper.methods.createNFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
-
const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
-
- return {collectionId, collectionAddress};
+ const events = this.helper.eth.normalizeEvents(result.events);
+
+ return {collectionId, collectionAddress, events};
+ }
+
+ async createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
+ return this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);
}
- async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+ async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
- const {collectionId, collectionAddress} = await this.createNFTCollection(signer, name, description, tokenPrefix);
+ const {collectionId, collectionAddress, events} = await this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);
await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
- return {collectionId, collectionAddress};
+ return {collectionId, collectionAddress, events};
}
- async createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+ async createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {
+ return this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);
+ }
+
+ async createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {
const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
-
- const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
-
+
+ const result = await collectionHelper.methods.createFTCollection(name, decimals, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
-
- return {collectionId, collectionAddress};
+
+ const events = this.helper.eth.normalizeEvents(result.events);
+
+ return {collectionId, collectionAddress, events};
}
-
- async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+
+ async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
- const {collectionId, collectionAddress} = await this.createRFTCollection(signer, name, description, tokenPrefix);
+ const {collectionId, collectionAddress, events} = await this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);
await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
- return {collectionId, collectionAddress};
+ return {collectionId, collectionAddress, events};
}
async deployCollectorContract(signer: string): Promise<Contract> {
@@ -339,10 +350,38 @@
normalizeAddress(address: string): string {
return '0x' + address.substring(address.length - 40);
}
+}
+
+export class EthPropertyGroup extends EthGroupBase {
+ property(key: string, value: string): EthProperty {
+ return [
+ key,
+ '0x'+Buffer.from(value).toString('hex'),
+ ];
+ }
}
-
export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;
+export class EthCrossAccountGroup extends EthGroupBase {
+ fromAddress(address: TEthereumAccount): TEthCrossAccount {
+ return {
+ 0: address,
+ 1: '0',
+ field_0: address,
+ field_1: '0',
+ };
+ }
+
+ fromKeyringPair(keyring: IKeyringPair): TEthCrossAccount {
+ return {
+ 0: '0x0000000000000000000000000000000000000000',
+ 1: keyring.addressRaw,
+ field_0: '0x0000000000000000000000000000000000000000',
+ field_1: keyring.addressRaw,
+ };
+ }
+}
+
export class EthUniqueHelper extends DevUniqueHelper {
web3: Web3 | null = null;
web3Provider: WebsocketProvider | null = null;
@@ -351,6 +390,8 @@
ethAddress: EthAddressGroup;
ethNativeContract: NativeContractGroup;
ethContract: ContractGroup;
+ ethCrossAccount: EthCrossAccountGroup;
+ ethProperty: EthPropertyGroup;
constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
options.helperBase = options.helperBase ?? EthUniqueHelper;
@@ -358,8 +399,10 @@
super(logger, options);
this.eth = new EthGroup(this);
this.ethAddress = new EthAddressGroup(this);
+ this.ethCrossAccount = new EthCrossAccountGroup(this);
this.ethNativeContract = new NativeContractGroup(this);
this.ethContract = new ContractGroup(this);
+ this.ethProperty = new EthPropertyGroup(this);
}
getWeb3(): Web3 {
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -70,6 +70,13 @@
ethereum?: TEthereumAccount;
}
+export interface IEthCrossAccountId {
+ 0: TEthereumAccount;
+ 1: TSubstrateAccount;
+ field_0: TEthereumAccount;
+ field_1: TSubstrateAccount;
+}
+
export interface ICollectionLimits {
accountTokenOwnershipLimit?: number | null;
sponsoredDataSize?: number | null;
@@ -217,3 +224,4 @@
export type TRelayNetworks = 'rococo' | 'westend';
export type TNetworks = TUniqueNetworks | TSiblingNetworkds | TRelayNetworks;
export type TSigner = IKeyringPair; // | 'string'
+export type TCollectionMode = 'nft' | 'rft' | 'ft';
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 {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 // If ith character is 8 to f then make it uppercase84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255256 static bigIntToDecimals(number: bigint, decimals = 18) {257 const numberStr = number.toString();258 const dotPos = numberStr.length - decimals;259 260 if (dotPos <= 0) {261 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;262 } else {263 const intPart = numberStr.substring(0, dotPos);264 const fractPart = numberStr.substring(dotPos);265 return intPart + '.' + fractPart;266 }267 }268}269270class UniqueEventHelper {271 private static extractIndex(index: any): [number, number] | string {272 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];273 return index.toJSON();274 }275276 private static extractSub(data: any, subTypes: any): {[key: string]: any} {277 let obj: any = {};278 let index = 0;279280 if (data.entries) {281 for(const [key, value] of data.entries()) {282 obj[key] = this.extractData(value, subTypes[index]);283 index++;284 }285 } else obj = data.toJSON();286287 return obj;288 }289 290 private static extractData(data: any, type: any): any {291 if(!type) return data.toHuman();292 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();293 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();294 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);295 return data.toHuman();296 }297298 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {299 const parsedEvents: IEvent[] = [];300301 events.forEach((record) => {302 const {event, phase} = record;303 const types = event.typeDef;304305 const eventData: IEvent = {306 section: event.section.toString(),307 method: event.method.toString(),308 index: this.extractIndex(event.index),309 data: [],310 phase: phase.toJSON(),311 };312313 event.data.forEach((val: any, index: number) => {314 eventData.data.push(this.extractData(val, types[index]));315 });316317 parsedEvents.push(eventData);318 });319320 return parsedEvents;321 }322}323324export class ChainHelperBase {325 helperBase: any;326327 transactionStatus = UniqueUtil.transactionStatus;328 chainLogType = UniqueUtil.chainLogType;329 util: typeof UniqueUtil;330 eventHelper: typeof UniqueEventHelper;331 logger: ILogger;332 api: ApiPromise | null;333 forcedNetwork: TNetworks | null;334 network: TNetworks | null;335 chainLog: IUniqueHelperLog[];336 children: ChainHelperBase[];337 address: AddressGroup;338 chain: ChainGroup;339340 constructor(logger?: ILogger, helperBase?: any) {341 this.helperBase = helperBase;342343 this.util = UniqueUtil;344 this.eventHelper = UniqueEventHelper;345 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();346 this.logger = logger;347 this.api = null;348 this.forcedNetwork = null;349 this.network = null;350 this.chainLog = [];351 this.children = [];352 this.address = new AddressGroup(this);353 this.chain = new ChainGroup(this);354 }355356 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {357 Object.setPrototypeOf(helperCls.prototype, this);358 const newHelper = new helperCls(this.logger, options);359360 newHelper.api = this.api;361 newHelper.network = this.network;362 newHelper.forceNetwork = this.forceNetwork;363364 this.children.push(newHelper);365366 return newHelper;367 }368369 getApi(): ApiPromise {370 if(this.api === null) throw Error('API not initialized');371 return this.api;372 }373374 clearChainLog(): void {375 this.chainLog = [];376 }377378 forceNetwork(value: TNetworks): void {379 this.forcedNetwork = value;380 }381382 async connect(wsEndpoint: string, listeners?: IApiListeners) {383 if (this.api !== null) throw Error('Already connected');384 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);385 this.api = api;386 this.network = network;387 }388389 async disconnect() {390 for (const child of this.children) {391 child.clearApi();392 }393394 if (this.api === null) return;395 await this.api.disconnect();396 this.clearApi();397 }398399 clearApi() {400 this.api = null;401 this.network = null;402 }403404 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {405 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;406 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];407408 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;409410 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;411 return 'opal';412 }413414 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {415 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});416 await api.isReady;417418 const network = await this.detectNetwork(api);419420 await api.disconnect();421422 return network;423 }424425 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{426 api: ApiPromise;427 network: TNetworks;428 }> {429 if(typeof network === 'undefined' || network === null) network = 'opal';430 const supportedRPC = {431 opal: {432 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,433 },434 quartz: {435 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,436 },437 unique: {438 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,439 },440 rococo: {},441 westend: {},442 moonbeam: {},443 moonriver: {},444 acala: {},445 karura: {},446 westmint: {},447 };448 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);449 const rpc = supportedRPC[network];450451 // TODO: investigate how to replace rpc in runtime452 // api._rpcCore.addUserInterfaces(rpc);453454 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});455456 await api.isReadyOrError;457458 if (typeof listeners === 'undefined') listeners = {};459 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {460 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;461 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);462 }463464 return {api, network};465 }466467 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {468 const {events, status} = data;469 if (status.isReady) {470 return this.transactionStatus.NOT_READY;471 }472 if (status.isBroadcast) {473 return this.transactionStatus.NOT_READY;474 }475 if (status.isInBlock || status.isFinalized) {476 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');477 if (errors.length > 0) {478 return this.transactionStatus.FAIL;479 }480 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {481 return this.transactionStatus.SUCCESS;482 }483 }484485 return this.transactionStatus.FAIL;486 }487488 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {489 const sign = (callback: any) => {490 if(options !== null) return transaction.signAndSend(sender, options, callback);491 return transaction.signAndSend(sender, callback);492 };493 // eslint-disable-next-line no-async-promise-executor494 return new Promise(async (resolve, reject) => {495 try {496 const unsub = await sign((result: any) => {497 const status = this.getTransactionStatus(result);498499 if (status === this.transactionStatus.SUCCESS) {500 this.logger.log(`${label} successful`);501 unsub();502 resolve({result, status});503 } else if (status === this.transactionStatus.FAIL) {504 let moduleError = null;505506 if (result.hasOwnProperty('dispatchError')) {507 const dispatchError = result['dispatchError'];508509 if (dispatchError) {510 if (dispatchError.isModule) {511 const modErr = dispatchError.asModule;512 const errorMeta = dispatchError.registry.findMetaError(modErr);513514 moduleError = `${errorMeta.section}.${errorMeta.name}`;515 } else {516 moduleError = dispatchError.toHuman();517 }518 } else {519 this.logger.log(result, this.logger.level.ERROR);520 }521 }522523 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);524 unsub();525 reject({status, moduleError, result});526 }527 });528 } catch (e) {529 this.logger.log(e, this.logger.level.ERROR);530 reject(e);531 }532 });533 }534535 constructApiCall(apiCall: string, params: any[]) {536 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);537 let call = this.getApi() as any;538 for(const part of apiCall.slice(4).split('.')) {539 call = call[part];540 }541 return call(...params);542 }543544 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {545 if(this.api === null) throw Error('API not initialized');546 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);547548 const startTime = (new Date()).getTime();549 let result: ITransactionResult;550 let events: IEvent[] = [];551 try {552 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;553 events = this.eventHelper.extractEvents(result.result.events);554 }555 catch(e) {556 if(!(e as object).hasOwnProperty('status')) throw e;557 result = e as ITransactionResult;558 }559560 const endTime = (new Date()).getTime();561562 const log = {563 executedAt: endTime,564 executionTime: endTime - startTime,565 type: this.chainLogType.EXTRINSIC,566 status: result.status,567 call: extrinsic,568 signer: this.getSignerAddress(sender),569 params,570 } as IUniqueHelperLog;571572 if(result.status !== this.transactionStatus.SUCCESS) {573 if (result.moduleError) log.moduleError = result.moduleError;574 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;575 }576 if(events.length > 0) log.events = events;577578 this.chainLog.push(log);579580 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {581 if (result.moduleError) throw Error(`${result.moduleError}`);582 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));583 }584 return result;585 }586587 async callRpc(rpc: string, params?: any[]) {588 if(typeof params === 'undefined') params = [];589 if(this.api === null) throw Error('API not initialized');590 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);591592 const startTime = (new Date()).getTime();593 let result;594 let error = null;595 const log = {596 type: this.chainLogType.RPC,597 call: rpc,598 params,599 } as IUniqueHelperLog;600601 try {602 result = await this.constructApiCall(rpc, params);603 }604 catch(e) {605 error = e;606 }607608 const endTime = (new Date()).getTime();609610 log.executedAt = endTime;611 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';612 log.executionTime = endTime - startTime;613614 this.chainLog.push(log);615616 if(error !== null) throw error;617618 return result;619 }620621 getSignerAddress(signer: IKeyringPair | string): string {622 if(typeof signer === 'string') return signer;623 return signer.address;624 }625626 fetchAllPalletNames(): string[] {627 if(this.api === null) throw Error('API not initialized');628 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());629 }630631 fetchMissingPalletNames(requiredPallets: string[]): string[] {632 const palletNames = this.fetchAllPalletNames();633 return requiredPallets.filter(p => !palletNames.includes(p));634 }635}636637638class HelperGroup<T extends ChainHelperBase> {639 helper: T;640641 constructor(uniqueHelper: T) {642 this.helper = uniqueHelper;643 }644}645646647class CollectionGroup extends HelperGroup<UniqueHelper> {648 /**649 * Get number of blocks when sponsored transaction is available.650 *651 * @param collectionId ID of collection652 * @param tokenId ID of token653 * @param addressObj address for which the sponsorship is checked654 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});655 * @returns number of blocks or null if sponsorship hasn't been set656 */657 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {658 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();659 }660661 /**662 * Get the number of created collections.663 *664 * @returns number of created collections665 */666 async getTotalCount(): Promise<number> {667 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();668 }669670 /**671 * Get information about the collection with additional data,672 * including the number of tokens it contains, its administrators,673 * the normalized address of the collection's owner, and decoded name and description.674 *675 * @param collectionId ID of collection676 * @example await getData(2)677 * @returns collection information object678 */679 async getData(collectionId: number): Promise<{680 id: number;681 name: string;682 description: string;683 tokensCount: number;684 admins: CrossAccountId[];685 normalizedOwner: TSubstrateAccount;686 raw: any687 } | null> {688 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);689 const humanCollection = collection.toHuman(), collectionData = {690 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],691 raw: humanCollection,692 } as any, jsonCollection = collection.toJSON();693 if (humanCollection === null) return null;694 collectionData.raw.limits = jsonCollection.limits;695 collectionData.raw.permissions = jsonCollection.permissions;696 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);697 for (const key of ['name', 'description']) {698 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);699 }700701 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))702 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)703 : 0;704 collectionData.admins = await this.getAdmins(collectionId);705706 return collectionData;707 }708709 /**710 * Get the addresses of the collection's administrators, optionally normalized.711 *712 * @param collectionId ID of collection713 * @param normalize whether to normalize the addresses to the default ss58 format714 * @example await getAdmins(1)715 * @returns array of administrators716 */717 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {718 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();719720 return normalize721 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())722 : admins;723 }724725 /**726 * Get the addresses added to the collection allow-list, optionally normalized.727 * @param collectionId ID of collection728 * @param normalize whether to normalize the addresses to the default ss58 format729 * @example await getAllowList(1)730 * @returns array of allow-listed addresses731 */732 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {733 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();734 return normalize735 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())736 : allowListed;737 }738739 /**740 * Get the effective limits of the collection instead of null for default values741 *742 * @param collectionId ID of collection743 * @example await getEffectiveLimits(2)744 * @returns object of collection limits745 */746 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {747 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();748 }749750 /**751 * Burns the collection if the signer has sufficient permissions and collection is empty.752 *753 * @param signer keyring of signer754 * @param collectionId ID of collection755 * @example await helper.collection.burn(aliceKeyring, 3);756 * @returns ```true``` if extrinsic success, otherwise ```false```757 */758 async burn(signer: TSigner, collectionId: number): Promise<boolean> {759 const result = await this.helper.executeExtrinsic(760 signer,761 'api.tx.unique.destroyCollection', [collectionId],762 true,763 );764765 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');766 }767768 /**769 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.770 *771 * @param signer keyring of signer772 * @param collectionId ID of collection773 * @param sponsorAddress Sponsor substrate address774 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")775 * @returns ```true``` if extrinsic success, otherwise ```false```776 */777 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {778 const result = await this.helper.executeExtrinsic(779 signer,780 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],781 true,782 );783784 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');785 }786787 /**788 * Confirms consent to sponsor the collection on behalf of the signer.789 *790 * @param signer keyring of signer791 * @param collectionId ID of collection792 * @example confirmSponsorship(aliceKeyring, 10)793 * @returns ```true``` if extrinsic success, otherwise ```false```794 */795 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {796 const result = await this.helper.executeExtrinsic(797 signer,798 'api.tx.unique.confirmSponsorship', [collectionId],799 true,800 );801802 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');803 }804805 /**806 * Removes the sponsor of a collection, regardless if it consented or not.807 *808 * @param signer keyring of signer809 * @param collectionId ID of collection810 * @example removeSponsor(aliceKeyring, 10)811 * @returns ```true``` if extrinsic success, otherwise ```false```812 */813 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {814 const result = await this.helper.executeExtrinsic(815 signer,816 'api.tx.unique.removeCollectionSponsor', [collectionId],817 true,818 );819820 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');821 }822823 /**824 * Sets the limits of the collection. At least one limit must be specified for a correct call.825 *826 * @param signer keyring of signer827 * @param collectionId ID of collection828 * @param limits collection limits object829 * @example830 * await setLimits(831 * aliceKeyring,832 * 10,833 * {834 * sponsorTransferTimeout: 0,835 * ownerCanDestroy: false836 * }837 * )838 * @returns ```true``` if extrinsic success, otherwise ```false```839 */840 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {841 const result = await this.helper.executeExtrinsic(842 signer,843 'api.tx.unique.setCollectionLimits', [collectionId, limits],844 true,845 );846847 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');848 }849850 /**851 * Changes the owner of the collection to the new Substrate address.852 *853 * @param signer keyring of signer854 * @param collectionId ID of collection855 * @param ownerAddress substrate address of new owner856 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")857 * @returns ```true``` if extrinsic success, otherwise ```false```858 */859 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {860 const result = await this.helper.executeExtrinsic(861 signer,862 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],863 true,864 );865866 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');867 }868869 /**870 * Adds a collection administrator.871 *872 * @param signer keyring of signer873 * @param collectionId ID of collection874 * @param adminAddressObj Administrator address (substrate or ethereum)875 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})876 * @returns ```true``` if extrinsic success, otherwise ```false```877 */878 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {879 const result = await this.helper.executeExtrinsic(880 signer,881 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],882 true,883 );884885 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');886 }887888 /**889 * Removes a collection administrator.890 *891 * @param signer keyring of signer892 * @param collectionId ID of collection893 * @param adminAddressObj Administrator address (substrate or ethereum)894 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})895 * @returns ```true``` if extrinsic success, otherwise ```false```896 */897 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {898 const result = await this.helper.executeExtrinsic(899 signer,900 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],901 true,902 );903904 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');905 }906907 /**908 * Check if user is in allow list.909 * 910 * @param collectionId ID of collection911 * @param user Account to check912 * @example await getAdmins(1)913 * @returns is user in allow list914 */915 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {916 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();917 }918919 /**920 * Adds an address to allow list921 * @param signer keyring of signer922 * @param collectionId ID of collection923 * @param addressObj address to add to the allow list924 * @returns ```true``` if extrinsic success, otherwise ```false```925 */926 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {927 const result = await this.helper.executeExtrinsic(928 signer,929 'api.tx.unique.addToAllowList', [collectionId, addressObj],930 true,931 );932933 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');934 }935936 /**937 * Removes an address from allow list938 *939 * @param signer keyring of signer940 * @param collectionId ID of collection941 * @param addressObj address to remove from the allow list942 * @returns ```true``` if extrinsic success, otherwise ```false```943 */944 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {945 const result = await this.helper.executeExtrinsic(946 signer,947 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],948 true,949 );950951 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');952 }953954 /**955 * Sets onchain permissions for selected collection.956 *957 * @param signer keyring of signer958 * @param collectionId ID of collection959 * @param permissions collection permissions object960 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});961 * @returns ```true``` if extrinsic success, otherwise ```false```962 */963 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {964 const result = await this.helper.executeExtrinsic(965 signer,966 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],967 true,968 );969970 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');971 }972973 /**974 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.975 *976 * @param signer keyring of signer977 * @param collectionId ID of collection978 * @param permissions nesting permissions object979 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});980 * @returns ```true``` if extrinsic success, otherwise ```false```981 */982 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {983 return await this.setPermissions(signer, collectionId, {nesting: permissions});984 }985986 /**987 * Disables nesting for selected collection.988 *989 * @param signer keyring of signer990 * @param collectionId ID of collection991 * @example disableNesting(aliceKeyring, 10);992 * @returns ```true``` if extrinsic success, otherwise ```false```993 */994 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {995 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});996 }997998 /**999 * Sets onchain properties to the collection.1000 *1001 * @param signer keyring of signer1002 * @param collectionId ID of collection1003 * @param properties array of property objects1004 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1005 * @returns ```true``` if extrinsic success, otherwise ```false```1006 */1007 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1008 const result = await this.helper.executeExtrinsic(1009 signer,1010 'api.tx.unique.setCollectionProperties', [collectionId, properties],1011 true,1012 );10131014 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1015 }10161017 /**1018 * Get collection properties.1019 * 1020 * @param collectionId ID of collection1021 * @param propertyKeys optionally filter the returned properties to only these keys1022 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1023 * @returns array of key-value pairs1024 */1025 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1026 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1027 }10281029 async getCollectionOptions(collectionId: number) {1030 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1031 }10321033 /**1034 * Deletes onchain properties from the collection.1035 *1036 * @param signer keyring of signer1037 * @param collectionId ID of collection1038 * @param propertyKeys array of property keys to delete1039 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1040 * @returns ```true``` if extrinsic success, otherwise ```false```1041 */1042 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1043 const result = await this.helper.executeExtrinsic(1044 signer,1045 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1046 true,1047 );10481049 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1050 }10511052 /**1053 * Changes the owner of the token.1054 *1055 * @param signer keyring of signer1056 * @param collectionId ID of collection1057 * @param tokenId ID of token1058 * @param addressObj address of a new owner1059 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1060 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1061 * @returns true if the token success, otherwise false1062 */1063 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1064 const result = await this.helper.executeExtrinsic(1065 signer,1066 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1067 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1068 );10691070 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1071 }10721073 /**1074 *1075 * Change ownership of a token(s) on behalf of the owner.1076 *1077 * @param signer keyring of signer1078 * @param collectionId ID of collection1079 * @param tokenId ID of token1080 * @param fromAddressObj address on behalf of which the token will be sent1081 * @param toAddressObj new token owner1082 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1083 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1084 * @returns true if the token success, otherwise false1085 */1086 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1087 const result = await this.helper.executeExtrinsic(1088 signer,1089 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1090 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1091 );1092 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1093 }10941095 /**1096 *1097 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1098 *1099 * @param signer keyring of signer1100 * @param collectionId ID of collection1101 * @param tokenId ID of token1102 * @param amount amount of tokens to be burned. For NFT must be set to 1n1103 * @example burnToken(aliceKeyring, 10, 5);1104 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1105 */1106 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1107 const burnResult = await this.helper.executeExtrinsic(1108 signer,1109 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1110 true, // `Unable to burn token for ${label}`,1111 );1112 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1113 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1114 return burnedTokens.success;1115 }11161117 /**1118 * Destroys a concrete instance of NFT on behalf of the owner1119 *1120 * @param signer keyring of signer1121 * @param collectionId ID of collection1122 * @param tokenId ID of token1123 * @param fromAddressObj address on behalf of which the token will be burnt1124 * @param amount amount of tokens to be burned. For NFT must be set to 1n1125 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1126 * @returns ```true``` if extrinsic success, otherwise ```false```1127 */1128 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1129 const burnResult = await this.helper.executeExtrinsic(1130 signer,1131 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1132 true, // `Unable to burn token from for ${label}`,1133 );1134 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1135 return burnedTokens.success && burnedTokens.tokens.length > 0;1136 }11371138 /**1139 * Set, change, or remove approved address to transfer the ownership of the NFT.1140 *1141 * @param signer keyring of signer1142 * @param collectionId ID of collection1143 * @param tokenId ID of token1144 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1145 * @param amount amount of token to be approved. For NFT must be set to 1n1146 * @returns ```true``` if extrinsic success, otherwise ```false```1147 */1148 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1149 const approveResult = await this.helper.executeExtrinsic(1150 signer,1151 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1152 true, // `Unable to approve token for ${label}`,1153 );11541155 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1156 }11571158 /**1159 * Get the amount of token pieces approved to transfer or burn. Normally 0.1160 *1161 * @param collectionId ID of collection1162 * @param tokenId ID of token1163 * @param toAccountObj address which is approved to use token pieces1164 * @param fromAccountObj address which may have allowed the use of its owned tokens1165 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1166 * @returns number of approved to transfer pieces1167 */1168 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1169 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1170 }11711172 /**1173 * Get the last created token ID in a collection1174 *1175 * @param collectionId ID of collection1176 * @example getLastTokenId(10);1177 * @returns id of the last created token1178 */1179 async getLastTokenId(collectionId: number): Promise<number> {1180 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1181 }11821183 /**1184 * Check if token exists1185 *1186 * @param collectionId ID of collection1187 * @param tokenId ID of token1188 * @example doesTokenExist(10, 20);1189 * @returns true if the token exists, otherwise false1190 */1191 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1192 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1193 }1194}11951196class NFTnRFT extends CollectionGroup {1197 /**1198 * Get tokens owned by account1199 *1200 * @param collectionId ID of collection1201 * @param addressObj tokens owner1202 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1203 * @returns array of token ids owned by account1204 */1205 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1206 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1207 }12081209 /**1210 * Get token data1211 *1212 * @param collectionId ID of collection1213 * @param tokenId ID of token1214 * @param propertyKeys optionally filter the token properties to only these keys1215 * @param blockHashAt optionally query the data at some block with this hash1216 * @example getToken(10, 5);1217 * @returns human readable token data1218 */1219 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1220 properties: IProperty[];1221 owner: CrossAccountId;1222 normalizedOwner: CrossAccountId;1223 }| null> {1224 let tokenData;1225 if(typeof blockHashAt === 'undefined') {1226 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1227 }1228 else {1229 if(propertyKeys.length == 0) {1230 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1231 if(!collection) return null;1232 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1233 }1234 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1235 }1236 tokenData = tokenData.toHuman();1237 if (tokenData === null || tokenData.owner === null) return null;1238 const owner = {} as any;1239 for (const key of Object.keys(tokenData.owner)) {1240 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1241 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1242 : tokenData.owner[key];1243 }1244 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1245 return tokenData;1246 }12471248 /**1249 * Set permissions to change token properties1250 *1251 * @param signer keyring of signer1252 * @param collectionId ID of collection1253 * @param permissions permissions to change a property by the collection admin or token owner1254 * @example setTokenPropertyPermissions(1255 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1256 * )1257 * @returns true if extrinsic success otherwise false1258 */1259 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1260 const result = await this.helper.executeExtrinsic(1261 signer,1262 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1263 true,1264 );12651266 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1267 }12681269 /**1270 * Get token property permissions.1271 * 1272 * @param collectionId ID of collection1273 * @param propertyKeys optionally filter the returned property permissions to only these keys1274 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1275 * @returns array of key-permission pairs1276 */1277 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1278 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1279 }12801281 /**1282 * Set token properties1283 *1284 * @param signer keyring of signer1285 * @param collectionId ID of collection1286 * @param tokenId ID of token1287 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1288 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1289 * @returns ```true``` if extrinsic success, otherwise ```false```1290 */1291 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1292 const result = await this.helper.executeExtrinsic(1293 signer,1294 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1295 true,1296 );12971298 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1299 }13001301 /**1302 * Get properties, metadata assigned to a token.1303 * 1304 * @param collectionId ID of collection1305 * @param tokenId ID of token1306 * @param propertyKeys optionally filter the returned properties to only these keys1307 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1308 * @returns array of key-value pairs1309 */1310 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1311 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1312 }13131314 /**1315 * Delete the provided properties of a token1316 * @param signer keyring of signer1317 * @param collectionId ID of collection1318 * @param tokenId ID of token1319 * @param propertyKeys property keys to be deleted1320 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1321 * @returns ```true``` if extrinsic success, otherwise ```false```1322 */1323 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1324 const result = await this.helper.executeExtrinsic(1325 signer,1326 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1327 true,1328 );13291330 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1331 }13321333 /**1334 * Mint new collection1335 *1336 * @param signer keyring of signer1337 * @param collectionOptions basic collection options and properties1338 * @param mode NFT or RFT type of a collection1339 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1340 * @returns object of the created collection1341 */1342 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1343 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1344 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1345 for (const key of ['name', 'description', 'tokenPrefix']) {1346 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);1347 }1348 const creationResult = await this.helper.executeExtrinsic(1349 signer,1350 'api.tx.unique.createCollectionEx', [collectionOptions],1351 true, // errorLabel,1352 );1353 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1354 }13551356 getCollectionObject(_collectionId: number): any {1357 return null;1358 }13591360 getTokenObject(_collectionId: number, _tokenId: number): any {1361 return null;1362 }1363}136413651366class NFTGroup extends NFTnRFT {1367 /**1368 * Get collection object1369 * @param collectionId ID of collection1370 * @example getCollectionObject(2);1371 * @returns instance of UniqueNFTCollection1372 */1373 getCollectionObject(collectionId: number): UniqueNFTCollection {1374 return new UniqueNFTCollection(collectionId, this.helper);1375 }13761377 /**1378 * Get token object1379 * @param collectionId ID of collection1380 * @param tokenId ID of token1381 * @example getTokenObject(10, 5);1382 * @returns instance of UniqueNFTToken1383 */1384 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1385 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1386 }13871388 /**1389 * Get token's owner1390 * @param collectionId ID of collection1391 * @param tokenId ID of token1392 * @param blockHashAt optionally query the data at the block with this hash1393 * @example getTokenOwner(10, 5);1394 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1395 */1396 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1397 let owner;1398 if (typeof blockHashAt === 'undefined') {1399 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1400 } else {1401 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1402 }1403 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1404 }14051406 /**1407 * Is token approved to transfer1408 * @param collectionId ID of collection1409 * @param tokenId ID of token1410 * @param toAccountObj address to be approved1411 * @returns ```true``` if extrinsic success, otherwise ```false```1412 */1413 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1414 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1415 }14161417 /**1418 * Changes the owner of the token.1419 *1420 * @param signer keyring of signer1421 * @param collectionId ID of collection1422 * @param tokenId ID of token1423 * @param addressObj address of a new owner1424 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1425 * @returns ```true``` if extrinsic success, otherwise ```false```1426 */1427 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1428 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1429 }14301431 /**1432 *1433 * Change ownership of a NFT on behalf of the owner.1434 *1435 * @param signer keyring of signer1436 * @param collectionId ID of collection1437 * @param tokenId ID of token1438 * @param fromAddressObj address on behalf of which the token will be sent1439 * @param toAddressObj new token owner1440 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1441 * @returns ```true``` if extrinsic success, otherwise ```false```1442 */1443 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1444 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1445 }14461447 /**1448 * Recursively find the address that owns the token1449 * @param collectionId ID of collection1450 * @param tokenId ID of token1451 * @param blockHashAt1452 * @example getTokenTopmostOwner(10, 5);1453 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1454 */1455 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1456 let owner;1457 if (typeof blockHashAt === 'undefined') {1458 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1459 } else {1460 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1461 }14621463 if (owner === null) return null;14641465 return owner.toHuman();1466 }14671468 /**1469 * Get tokens nested in the provided token1470 * @param collectionId ID of collection1471 * @param tokenId ID of token1472 * @param blockHashAt optionally query the data at the block with this hash1473 * @example getTokenChildren(10, 5);1474 * @returns tokens whose depth of nesting is <= 51475 */1476 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1477 let children;1478 if(typeof blockHashAt === 'undefined') {1479 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1480 } else {1481 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1482 }14831484 return children.toJSON().map((x: any) => {1485 return {collectionId: x.collection, tokenId: x.token};1486 });1487 }14881489 /**1490 * Nest one token into another1491 * @param signer keyring of signer1492 * @param tokenObj token to be nested1493 * @param rootTokenObj token to be parent1494 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1495 * @returns ```true``` if extrinsic success, otherwise ```false```1496 */1497 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1498 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1499 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1500 if(!result) {1501 throw Error('Unable to nest token!');1502 }1503 return result;1504 }15051506 /**1507 * Remove token from nested state1508 * @param signer keyring of signer1509 * @param tokenObj token to unnest1510 * @param rootTokenObj parent of a token1511 * @param toAddressObj address of a new token owner1512 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1513 * @returns ```true``` if extrinsic success, otherwise ```false```1514 */1515 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1516 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1517 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1518 if(!result) {1519 throw Error('Unable to unnest token!');1520 }1521 return result;1522 }15231524 /**1525 * Mint new collection1526 * @param signer keyring of signer1527 * @param collectionOptions Collection options1528 * @example1529 * mintCollection(aliceKeyring, {1530 * name: 'New',1531 * description: 'New collection',1532 * tokenPrefix: 'NEW',1533 * })1534 * @returns object of the created collection1535 */1536 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1537 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1538 }15391540 /**1541 * Mint new token1542 * @param signer keyring of signer1543 * @param data token data1544 * @returns created token object1545 */1546 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1547 const creationResult = await this.helper.executeExtrinsic(1548 signer,1549 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1550 nft: {1551 properties: data.properties,1552 },1553 }],1554 true,1555 );1556 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1557 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1558 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1559 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1560 }15611562 /**1563 * Mint multiple NFT tokens1564 * @param signer keyring of signer1565 * @param collectionId ID of collection1566 * @param tokens array of tokens with owner and properties1567 * @example1568 * mintMultipleTokens(aliceKeyring, 10, [{1569 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1570 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1571 * },{1572 * owner: {Ethereum: "0x9F0583DbB855d..."},1573 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1574 * }]);1575 * @returns ```true``` if extrinsic success, otherwise ```false```1576 */1577 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1578 const creationResult = await this.helper.executeExtrinsic(1579 signer,1580 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1581 true,1582 );1583 const collection = this.getCollectionObject(collectionId);1584 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1585 }15861587 /**1588 * Mint multiple NFT tokens with one owner1589 * @param signer keyring of signer1590 * @param collectionId ID of collection1591 * @param owner tokens owner1592 * @param tokens array of tokens with owner and properties1593 * @example1594 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1595 * properties: [{1596 * key: "gender",1597 * value: "female",1598 * },{1599 * key: "age",1600 * value: "33",1601 * }],1602 * }]);1603 * @returns array of newly created tokens1604 */1605 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1606 const rawTokens = [];1607 for (const token of tokens) {1608 const raw = {NFT: {properties: token.properties}};1609 rawTokens.push(raw);1610 }1611 const creationResult = await this.helper.executeExtrinsic(1612 signer,1613 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1614 true,1615 );1616 const collection = this.getCollectionObject(collectionId);1617 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1618 }16191620 /**1621 * Set, change, or remove approved address to transfer the ownership of the NFT.1622 *1623 * @param signer keyring of signer1624 * @param collectionId ID of collection1625 * @param tokenId ID of token1626 * @param toAddressObj address to approve1627 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1628 * @returns ```true``` if extrinsic success, otherwise ```false```1629 */1630 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1631 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1632 }1633}163416351636class RFTGroup extends NFTnRFT {1637 /**1638 * Get collection object1639 * @param collectionId ID of collection1640 * @example getCollectionObject(2);1641 * @returns instance of UniqueRFTCollection1642 */1643 getCollectionObject(collectionId: number): UniqueRFTCollection {1644 return new UniqueRFTCollection(collectionId, this.helper);1645 }16461647 /**1648 * Get token object1649 * @param collectionId ID of collection1650 * @param tokenId ID of token1651 * @example getTokenObject(10, 5);1652 * @returns instance of UniqueNFTToken1653 */1654 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1655 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1656 }16571658 /**1659 * Get top 10 token owners with the largest number of pieces1660 * @param collectionId ID of collection1661 * @param tokenId ID of token1662 * @example getTokenTop10Owners(10, 5);1663 * @returns array of top 10 owners1664 */1665 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1666 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1667 }16681669 /**1670 * Get number of pieces owned by address1671 * @param collectionId ID of collection1672 * @param tokenId ID of token1673 * @param addressObj address token owner1674 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1675 * @returns number of pieces ownerd by address1676 */1677 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1678 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1679 }16801681 /**1682 * Transfer pieces of token to another address1683 * @param signer keyring of signer1684 * @param collectionId ID of collection1685 * @param tokenId ID of token1686 * @param addressObj address of a new owner1687 * @param amount number of pieces to be transfered1688 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1689 * @returns ```true``` if extrinsic success, otherwise ```false```1690 */1691 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1692 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1693 }16941695 /**1696 * Change ownership of some pieces of RFT on behalf of the owner.1697 * @param signer keyring of signer1698 * @param collectionId ID of collection1699 * @param tokenId ID of token1700 * @param fromAddressObj address on behalf of which the token will be sent1701 * @param toAddressObj new token owner1702 * @param amount number of pieces to be transfered1703 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1704 * @returns ```true``` if extrinsic success, otherwise ```false```1705 */1706 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1707 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1708 }17091710 /**1711 * Mint new collection1712 * @param signer keyring of signer1713 * @param collectionOptions Collection options1714 * @example1715 * mintCollection(aliceKeyring, {1716 * name: 'New',1717 * description: 'New collection',1718 * tokenPrefix: 'NEW',1719 * })1720 * @returns object of the created collection1721 */1722 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1723 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1724 }17251726 /**1727 * Mint new token1728 * @param signer keyring of signer1729 * @param data token data1730 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1731 * @returns created token object1732 */1733 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1734 const creationResult = await this.helper.executeExtrinsic(1735 signer,1736 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1737 refungible: {1738 pieces: data.pieces,1739 properties: data.properties,1740 },1741 }],1742 true,1743 );1744 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1745 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1746 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1747 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1748 }17491750 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1751 throw Error('Not implemented');1752 const creationResult = await this.helper.executeExtrinsic(1753 signer,1754 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1755 true, // `Unable to mint RFT tokens for ${label}`,1756 );1757 const collection = this.getCollectionObject(collectionId);1758 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1759 }17601761 /**1762 * Mint multiple RFT tokens with one owner1763 * @param signer keyring of signer1764 * @param collectionId ID of collection1765 * @param owner tokens owner1766 * @param tokens array of tokens with properties and pieces1767 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1768 * @returns array of newly created RFT tokens1769 */1770 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1771 const rawTokens = [];1772 for (const token of tokens) {1773 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1774 rawTokens.push(raw);1775 }1776 const creationResult = await this.helper.executeExtrinsic(1777 signer,1778 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1779 true,1780 );1781 const collection = this.getCollectionObject(collectionId);1782 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1783 }17841785 /**1786 * Destroys a concrete instance of RFT.1787 * @param signer keyring of signer1788 * @param collectionId ID of collection1789 * @param tokenId ID of token1790 * @param amount number of pieces to be burnt1791 * @example burnToken(aliceKeyring, 10, 5);1792 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1793 */1794 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1795 return await super.burnToken(signer, collectionId, tokenId, amount);1796 }17971798 /**1799 * Destroys a concrete instance of RFT on behalf of the owner.1800 * @param signer keyring of signer1801 * @param collectionId ID of collection1802 * @param tokenId ID of token1803 * @param fromAddressObj address on behalf of which the token will be burnt1804 * @param amount number of pieces to be burnt1805 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1806 * @returns ```true``` if extrinsic success, otherwise ```false```1807 */1808 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1809 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1810 }18111812 /**1813 * Set, change, or remove approved address to transfer the ownership of the RFT.1814 *1815 * @param signer keyring of signer1816 * @param collectionId ID of collection1817 * @param tokenId ID of token1818 * @param toAddressObj address to approve1819 * @param amount number of pieces to be approved1820 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1821 * @returns true if the token success, otherwise false1822 */1823 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1824 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1825 }18261827 /**1828 * Get total number of pieces1829 * @param collectionId ID of collection1830 * @param tokenId ID of token1831 * @example getTokenTotalPieces(10, 5);1832 * @returns number of pieces1833 */1834 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1835 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1836 }18371838 /**1839 * Change number of token pieces. Signer must be the owner of all token pieces.1840 * @param signer keyring of signer1841 * @param collectionId ID of collection1842 * @param tokenId ID of token1843 * @param amount new number of pieces1844 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1845 * @returns true if the repartion was success, otherwise false1846 */1847 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1848 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1849 const repartitionResult = await this.helper.executeExtrinsic(1850 signer,1851 'api.tx.unique.repartition', [collectionId, tokenId, amount],1852 true,1853 );1854 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1855 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1856 }1857}185818591860class FTGroup extends CollectionGroup {1861 /**1862 * Get collection object1863 * @param collectionId ID of collection1864 * @example getCollectionObject(2);1865 * @returns instance of UniqueFTCollection1866 */1867 getCollectionObject(collectionId: number): UniqueFTCollection {1868 return new UniqueFTCollection(collectionId, this.helper);1869 }18701871 /**1872 * Mint new fungible collection1873 * @param signer keyring of signer1874 * @param collectionOptions Collection options1875 * @param decimalPoints number of token decimals1876 * @example1877 * mintCollection(aliceKeyring, {1878 * name: 'New',1879 * description: 'New collection',1880 * tokenPrefix: 'NEW',1881 * }, 18)1882 * @returns newly created fungible collection1883 */1884 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1885 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1886 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1887 collectionOptions.mode = {fungible: decimalPoints};1888 for (const key of ['name', 'description', 'tokenPrefix']) {1889 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);1890 }1891 const creationResult = await this.helper.executeExtrinsic(1892 signer,1893 'api.tx.unique.createCollectionEx', [collectionOptions],1894 true,1895 );1896 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1897 }18981899 /**1900 * Mint tokens1901 * @param signer keyring of signer1902 * @param collectionId ID of collection1903 * @param owner address owner of new tokens1904 * @param amount amount of tokens to be meanted1905 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1906 * @returns ```true``` if extrinsic success, otherwise ```false```1907 */1908 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1909 const creationResult = await this.helper.executeExtrinsic(1910 signer,1911 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1912 fungible: {1913 value: amount,1914 },1915 }],1916 true, // `Unable to mint fungible tokens for ${label}`,1917 );1918 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1919 }19201921 /**1922 * Mint multiple Fungible tokens with one owner1923 * @param signer keyring of signer1924 * @param collectionId ID of collection1925 * @param owner tokens owner1926 * @param tokens array of tokens with properties and pieces1927 * @returns ```true``` if extrinsic success, otherwise ```false```1928 */1929 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1930 const rawTokens = [];1931 for (const token of tokens) {1932 const raw = {Fungible: {Value: token.value}};1933 rawTokens.push(raw);1934 }1935 const creationResult = await this.helper.executeExtrinsic(1936 signer,1937 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1938 true,1939 );1940 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1941 }19421943 /**1944 * Get the top 10 owners with the largest balance for the Fungible collection1945 * @param collectionId ID of collection1946 * @example getTop10Owners(10);1947 * @returns array of ```ICrossAccountId```1948 */1949 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1950 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1951 }19521953 /**1954 * Get account balance1955 * @param collectionId ID of collection1956 * @param addressObj address of owner1957 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1958 * @returns amount of fungible tokens owned by address1959 */1960 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1961 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1962 }19631964 /**1965 * Transfer tokens to address1966 * @param signer keyring of signer1967 * @param collectionId ID of collection1968 * @param toAddressObj address recipient1969 * @param amount amount of tokens to be sent1970 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1971 * @returns ```true``` if extrinsic success, otherwise ```false```1972 */1973 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1974 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1975 }19761977 /**1978 * Transfer some tokens on behalf of the owner.1979 * @param signer keyring of signer1980 * @param collectionId ID of collection1981 * @param fromAddressObj address on behalf of which tokens will be sent1982 * @param toAddressObj address where token to be sent1983 * @param amount number of tokens to be sent1984 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1985 * @returns ```true``` if extrinsic success, otherwise ```false```1986 */1987 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1988 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1989 }19901991 /**1992 * Destroy some amount of tokens1993 * @param signer keyring of signer1994 * @param collectionId ID of collection1995 * @param amount amount of tokens to be destroyed1996 * @example burnTokens(aliceKeyring, 10, 1000n);1997 * @returns ```true``` if extrinsic success, otherwise ```false```1998 */1999 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2000 return await super.burnToken(signer, collectionId, 0, amount);2001 }20022003 /**2004 * Burn some tokens on behalf of the owner.2005 * @param signer keyring of signer2006 * @param collectionId ID of collection2007 * @param fromAddressObj address on behalf of which tokens will be burnt2008 * @param amount amount of tokens to be burnt2009 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2010 * @returns ```true``` if extrinsic success, otherwise ```false```2011 */2012 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2013 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2014 }20152016 /**2017 * Get total collection supply2018 * @param collectionId2019 * @returns2020 */2021 async getTotalPieces(collectionId: number): Promise<bigint> {2022 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2023 }20242025 /**2026 * Set, change, or remove approved address to transfer tokens.2027 *2028 * @param signer keyring of signer2029 * @param collectionId ID of collection2030 * @param toAddressObj address to be approved2031 * @param amount amount of tokens to be approved2032 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2033 * @returns ```true``` if extrinsic success, otherwise ```false```2034 */2035 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2036 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2037 }20382039 /**2040 * Get amount of fungible tokens approved to transfer2041 * @param collectionId ID of collection2042 * @param fromAddressObj owner of tokens2043 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2044 * @returns number of tokens approved for the transfer2045 */2046 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2047 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2048 }2049}205020512052class ChainGroup extends HelperGroup<ChainHelperBase> {2053 /**2054 * Get system properties of a chain2055 * @example getChainProperties();2056 * @returns ss58Format, token decimals, and token symbol2057 */2058 getChainProperties(): IChainProperties {2059 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2060 return {2061 ss58Format: properties.ss58Format.toJSON(),2062 tokenDecimals: properties.tokenDecimals.toJSON(),2063 tokenSymbol: properties.tokenSymbol.toJSON(),2064 };2065 }20662067 /**2068 * Get chain header2069 * @example getLatestBlockNumber();2070 * @returns the number of the last block2071 */2072 async getLatestBlockNumber(): Promise<number> {2073 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2074 }20752076 /**2077 * Get block hash by block number2078 * @param blockNumber number of block2079 * @example getBlockHashByNumber(12345);2080 * @returns hash of a block2081 */2082 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2083 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2084 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2085 return blockHash;2086 }20872088 // TODO add docs2089 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2090 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2091 if (!blockHash) return null;2092 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2093 }20942095 /**2096 * Get account nonce2097 * @param address substrate address2098 * @example getNonce("5GrwvaEF5zXb26Fz...");2099 * @returns number, account's nonce2100 */2101 async getNonce(address: TSubstrateAccount): Promise<number> {2102 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2103 }2104}21052106class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2107 /**2108 * Get substrate address balance2109 * @param address substrate address2110 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2111 * @returns amount of tokens on address2112 */2113 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2114 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2115 }21162117 /**2118 * Transfer tokens to substrate address2119 * @param signer keyring of signer2120 * @param address substrate address of a recipient2121 * @param amount amount of tokens to be transfered2122 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2123 * @returns ```true``` if extrinsic success, otherwise ```false```2124 */2125 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2126 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}`*/);21272128 let transfer = {from: null, to: null, amount: 0n} as any;2129 result.result.events.forEach(({event: {data, method, section}}) => {2130 if ((section === 'balances') && (method === 'Transfer')) {2131 transfer = {2132 from: this.helper.address.normalizeSubstrate(data[0]),2133 to: this.helper.address.normalizeSubstrate(data[1]),2134 amount: BigInt(data[2]),2135 };2136 }2137 });2138 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2139 && this.helper.address.normalizeSubstrate(address) === transfer.to 2140 && BigInt(amount) === transfer.amount;2141 return isSuccess;2142 }21432144 /**2145 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2146 * @param address substrate address2147 * @returns2148 */2149 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2150 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2151 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2152 }2153}21542155class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2156 /**2157 * Get ethereum address balance2158 * @param address ethereum address2159 * @example getEthereum("0x9F0583DbB855d...")2160 * @returns amount of tokens on address2161 */2162 async getEthereum(address: TEthereumAccount): Promise<bigint> {2163 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2164 }21652166 /**2167 * Transfer tokens to address2168 * @param signer keyring of signer2169 * @param address Ethereum address of a recipient2170 * @param amount amount of tokens to be transfered2171 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2172 * @returns ```true``` if extrinsic success, otherwise ```false```2173 */2174 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2175 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21762177 let transfer = {from: null, to: null, amount: 0n} as any;2178 result.result.events.forEach(({event: {data, method, section}}) => {2179 if ((section === 'balances') && (method === 'Transfer')) {2180 transfer = {2181 from: data[0].toString(),2182 to: data[1].toString(),2183 amount: BigInt(data[2]),2184 };2185 }2186 });2187 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2188 && address === transfer.to 2189 && BigInt(amount) === transfer.amount;2190 return isSuccess;2191 }2192}21932194class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2195 subBalanceGroup: SubstrateBalanceGroup<T>;2196 ethBalanceGroup: EthereumBalanceGroup<T>;21972198 constructor(helper: T) {2199 super(helper);2200 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2201 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2202 }22032204 getCollectionCreationPrice(): bigint {2205 return 2n * this.getOneTokenNominal();2206 }2207 /**2208 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2209 * @example getOneTokenNominal()2210 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2211 */2212 getOneTokenNominal(): bigint {2213 const chainProperties = this.helper.chain.getChainProperties();2214 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2215 }22162217 /**2218 * Get substrate address balance2219 * @param address substrate address2220 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2221 * @returns amount of tokens on address2222 */2223 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2224 return this.subBalanceGroup.getSubstrate(address);2225 }22262227 /**2228 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2229 * @param address substrate address2230 * @returns2231 */2232 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2233 return this.subBalanceGroup.getSubstrateFull(address);2234 }22352236 /**2237 * Get ethereum address balance2238 * @param address ethereum address2239 * @example getEthereum("0x9F0583DbB855d...")2240 * @returns amount of tokens on address2241 */2242 async getEthereum(address: TEthereumAccount): Promise<bigint> {2243 return this.ethBalanceGroup.getEthereum(address);2244 }22452246 /**2247 * Transfer tokens to substrate address2248 * @param signer keyring of signer2249 * @param address substrate address of a recipient2250 * @param amount amount of tokens to be transfered2251 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2252 * @returns ```true``` if extrinsic success, otherwise ```false```2253 */2254 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2255 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2256 }2257}22582259class AddressGroup extends HelperGroup<ChainHelperBase> {2260 /**2261 * Normalizes the address to the specified ss58 format, by default ```42```.2262 * @param address substrate address2263 * @param ss58Format format for address conversion, by default ```42```2264 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2265 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2266 */2267 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2268 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2269 }22702271 /**2272 * Get address in the connected chain format2273 * @param address substrate address2274 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2275 * @returns address in chain format2276 */2277 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2278 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2279 }22802281 /**2282 * Get substrate mirror of an ethereum address2283 * @param ethAddress ethereum address2284 * @param toChainFormat false for normalized account2285 * @example ethToSubstrate('0x9F0583DbB855d...')2286 * @returns substrate mirror of a provided ethereum address2287 */2288 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2289 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2290 }22912292 /**2293 * Get ethereum mirror of a substrate address2294 * @param subAddress substrate account2295 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2296 * @returns ethereum mirror of a provided substrate address2297 */2298 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2299 return CrossAccountId.translateSubToEth(subAddress);2300 }23012302 paraSiblingSovereignAccount(paraid: number) {2303 // We are getting a *sibling* parachain sovereign account,2304 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2305 const siblingPrefix = '0x7369626c';23062307 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2308 const suffix = '000000000000000000000000000000000000000000000000';23092310 return siblingPrefix + encodedParaId + suffix;2311 }2312}23132314class StakingGroup extends HelperGroup<UniqueHelper> {2315 /**2316 * Stake tokens for App Promotion2317 * @param signer keyring of signer2318 * @param amountToStake amount of tokens to stake2319 * @param label extra label for log2320 * @returns2321 */2322 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2323 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2324 const _stakeResult = await this.helper.executeExtrinsic(2325 signer, 'api.tx.appPromotion.stake',2326 [amountToStake], true,2327 );2328 // TODO extract info from stakeResult2329 return true;2330 }23312332 /**2333 * Unstake tokens for App Promotion2334 * @param signer keyring of signer2335 * @param amountToUnstake amount of tokens to unstake2336 * @param label extra label for log2337 * @returns block number where balances will be unlocked2338 */2339 async unstake(signer: TSigner, label?: string): Promise<number> {2340 if(typeof label === 'undefined') label = `${signer.address}`;2341 const _unstakeResult = await this.helper.executeExtrinsic(2342 signer, 'api.tx.appPromotion.unstake',2343 [], true,2344 );2345 // TODO extract block number fron events2346 return 1;2347 }23482349 /**2350 * Get total staked amount for address2351 * @param address substrate or ethereum address2352 * @returns total staked amount2353 */2354 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2355 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2356 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2357 }23582359 /**2360 * Get total staked per block2361 * @param address substrate or ethereum address2362 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2363 */2364 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2365 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2366 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2367 return { 2368 block: block.toBigInt(),2369 amount: amount.toBigInt(),2370 };2371 });2372 }23732374 /**2375 * Get total pending unstake amount for address2376 * @param address substrate or ethereum address2377 * @returns total pending unstake amount2378 */2379 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2380 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2381 }23822383 /**2384 * Get pending unstake amount per block for address2385 * @param address substrate or ethereum address2386 * @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 block2387 */2388 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2389 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2390 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2391 return {2392 block: block.toBigInt(),2393 amount: amount.toBigInt(),2394 };2395 });2396 return result;2397 }2398}23992400class SchedulerGroup extends HelperGroup<UniqueHelper> {2401 constructor(helper: UniqueHelper) {2402 super(helper);2403 }24042405 async cancelScheduled(signer: TSigner, scheduledId: string) {2406 return this.helper.executeExtrinsic(2407 signer,2408 'api.tx.scheduler.cancelNamed',2409 [scheduledId],2410 true,2411 );2412 }24132414 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2415 return this.helper.executeExtrinsic(2416 signer,2417 'api.tx.scheduler.changeNamedPriority',2418 [scheduledId, priority],2419 true,2420 );2421 }24222423 scheduleAt<T extends UniqueHelper>(2424 scheduledId: string,2425 executionBlockNumber: number,2426 options: ISchedulerOptions = {},2427 ) {2428 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2429 }24302431 scheduleAfter<T extends UniqueHelper>(2432 scheduledId: string,2433 blocksBeforeExecution: number,2434 options: ISchedulerOptions = {},2435 ) {2436 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2437 }24382439 schedule<T extends UniqueHelper>(2440 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2441 scheduledId: string,2442 blocksNum: number,2443 options: ISchedulerOptions = {},2444 ) {2445 // eslint-disable-next-line @typescript-eslint/naming-convention2446 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2447 return this.helper.clone(ScheduledHelperType, {2448 scheduleFn,2449 scheduledId,2450 blocksNum,2451 options,2452 }) as T;2453 }2454}24552456class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2457 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2458 await this.helper.executeExtrinsic(2459 signer,2460 'api.tx.foreignAssets.registerForeignAsset',2461 [ownerAddress, location, metadata],2462 true,2463 );2464 }24652466 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2467 await this.helper.executeExtrinsic(2468 signer,2469 'api.tx.foreignAssets.updateForeignAsset',2470 [foreignAssetId, location, metadata],2471 true,2472 );2473 }2474}24752476class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2477 palletName: string;24782479 constructor(helper: T, palletName: string) {2480 super(helper);24812482 this.palletName = palletName;2483 }24842485 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2486 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2487 }2488}24892490class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2491 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2492 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2493 }24942495 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2496 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2497 }24982499 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2500 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2501 }2502}25032504class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2505 async accounts(address: string, currencyId: any) {2506 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2507 return BigInt(free);2508 }2509}25102511class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2512 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2513 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2514 }25152516 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2517 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2518 }25192520 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2521 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2522 }25232524 async account(assetId: string | number, address: string) {2525 const accountAsset = (2526 await this.helper.callRpc('api.query.assets.account', [assetId, address])2527 ).toJSON()! as any;25282529 if (accountAsset !== null) {2530 return BigInt(accountAsset['balance']);2531 } else {2532 return null;2533 }2534 }2535}25362537class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2538 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2539 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2540 }2541}25422543class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2544 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2545 const apiPrefix = 'api.tx.assetManager.';25462547 const registerTx = this.helper.constructApiCall(2548 apiPrefix + 'registerForeignAsset',2549 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2550 );25512552 const setUnitsTx = this.helper.constructApiCall(2553 apiPrefix + 'setAssetUnitsPerSecond',2554 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2555 );25562557 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2558 const encodedProposal = batchCall?.method.toHex() || '';2559 return encodedProposal;2560 }25612562 async assetTypeId(location: any) {2563 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2564 }2565}25662567class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2568 async notePreimage(signer: TSigner, encodedProposal: string) {2569 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2570 }25712572 externalProposeMajority(proposalHash: string) {2573 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2574 }25752576 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2577 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2578 }25792580 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2581 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2582 }2583}25842585class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2586 collective: string;25872588 constructor(helper: MoonbeamHelper, collective: string) {2589 super(helper);25902591 this.collective = collective;2592 }25932594 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2595 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2596 }25972598 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2599 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2600 }26012602 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2603 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2604 }26052606 async proposalCount() {2607 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2608 }2609}26102611export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2612export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26132614export class UniqueHelper extends ChainHelperBase {2615 balance: BalanceGroup<UniqueHelper>;2616 collection: CollectionGroup;2617 nft: NFTGroup;2618 rft: RFTGroup;2619 ft: FTGroup;2620 staking: StakingGroup;2621 scheduler: SchedulerGroup;2622 foreignAssets: ForeignAssetsGroup;2623 xcm: XcmGroup<UniqueHelper>;2624 xTokens: XTokensGroup<UniqueHelper>;2625 tokens: TokensGroup<UniqueHelper>;26262627 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2628 super(logger, options.helperBase ?? UniqueHelper);26292630 this.balance = new BalanceGroup(this);2631 this.collection = new CollectionGroup(this);2632 this.nft = new NFTGroup(this);2633 this.rft = new RFTGroup(this);2634 this.ft = new FTGroup(this);2635 this.staking = new StakingGroup(this);2636 this.scheduler = new SchedulerGroup(this);2637 this.foreignAssets = new ForeignAssetsGroup(this);2638 this.xcm = new XcmGroup(this, 'polkadotXcm');2639 this.xTokens = new XTokensGroup(this);2640 this.tokens = new TokensGroup(this);2641 }26422643 getSudo<T extends UniqueHelper>() {2644 // eslint-disable-next-line @typescript-eslint/naming-convention2645 const SudoHelperType = SudoHelper(this.helperBase);2646 return this.clone(SudoHelperType) as T;2647 }2648}26492650export class XcmChainHelper extends ChainHelperBase {2651 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2652 const wsProvider = new WsProvider(wsEndpoint);2653 this.api = new ApiPromise({2654 provider: wsProvider,2655 });2656 await this.api.isReadyOrError;2657 this.network = await UniqueHelper.detectNetwork(this.api);2658 }2659}26602661export class RelayHelper extends XcmChainHelper {2662 xcm: XcmGroup<RelayHelper>;26632664 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2665 super(logger, options.helperBase ?? RelayHelper);26662667 this.xcm = new XcmGroup(this, 'xcmPallet');2668 }2669}26702671export class WestmintHelper extends XcmChainHelper {2672 balance: SubstrateBalanceGroup<WestmintHelper>;2673 xcm: XcmGroup<WestmintHelper>;2674 assets: AssetsGroup<WestmintHelper>;2675 xTokens: XTokensGroup<WestmintHelper>;26762677 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2678 super(logger, options.helperBase ?? WestmintHelper);26792680 this.balance = new SubstrateBalanceGroup(this);2681 this.xcm = new XcmGroup(this, 'polkadotXcm');2682 this.assets = new AssetsGroup(this);2683 this.xTokens = new XTokensGroup(this);2684 }2685}26862687export class MoonbeamHelper extends XcmChainHelper {2688 balance: EthereumBalanceGroup<MoonbeamHelper>;2689 assetManager: MoonbeamAssetManagerGroup;2690 assets: AssetsGroup<MoonbeamHelper>;2691 xTokens: XTokensGroup<MoonbeamHelper>;2692 democracy: MoonbeamDemocracyGroup;2693 collective: {2694 council: MoonbeamCollectiveGroup,2695 techCommittee: MoonbeamCollectiveGroup,2696 };26972698 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2699 super(logger, options.helperBase ?? MoonbeamHelper);27002701 this.balance = new EthereumBalanceGroup(this);2702 this.assetManager = new MoonbeamAssetManagerGroup(this);2703 this.assets = new AssetsGroup(this);2704 this.xTokens = new XTokensGroup(this);2705 this.democracy = new MoonbeamDemocracyGroup(this);2706 this.collective = {2707 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2708 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2709 };2710 }2711}27122713export class AcalaHelper extends XcmChainHelper {2714 balance: SubstrateBalanceGroup<AcalaHelper>;2715 assetRegistry: AcalaAssetRegistryGroup;2716 xTokens: XTokensGroup<AcalaHelper>;2717 tokens: TokensGroup<AcalaHelper>;27182719 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2720 super(logger, options.helperBase ?? AcalaHelper);27212722 this.balance = new SubstrateBalanceGroup(this);2723 this.assetRegistry = new AcalaAssetRegistryGroup(this);2724 this.xTokens = new XTokensGroup(this);2725 this.tokens = new TokensGroup(this);2726 }27272728 getSudo<T extends AcalaHelper>() {2729 // eslint-disable-next-line @typescript-eslint/naming-convention2730 const SudoHelperType = SudoHelper(this.helperBase);2731 return this.clone(SudoHelperType) as T;2732 }2733}27342735// eslint-disable-next-line @typescript-eslint/naming-convention2736function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2737 return class extends Base {2738 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2739 scheduledId: string;2740 blocksNum: number;2741 options: ISchedulerOptions;27422743 constructor(...args: any[]) {2744 const logger = args[0] as ILogger;2745 const options = args[1] as {2746 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2747 scheduledId: string,2748 blocksNum: number,2749 options: ISchedulerOptions2750 };27512752 super(logger);27532754 this.scheduleFn = options.scheduleFn;2755 this.scheduledId = options.scheduledId;2756 this.blocksNum = options.blocksNum;2757 this.options = options.options;2758 }27592760 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2761 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2762 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27632764 return super.executeExtrinsic(2765 sender,2766 extrinsic,2767 [2768 this.scheduledId,2769 this.blocksNum,2770 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2771 this.options.priority ?? null,2772 {Value: scheduledTx},2773 ],2774 expectSuccess,2775 );2776 }2777 };2778}27792780// eslint-disable-next-line @typescript-eslint/naming-convention2781function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2782 return class extends Base {2783 constructor(...args: any[]) {2784 super(...args);2785 }27862787 executeExtrinsic (2788 sender: IKeyringPair,2789 extrinsic: string,2790 params: any[],2791 expectSuccess?: boolean,2792 ): Promise<ITransactionResult> {2793 const call = this.constructApiCall(extrinsic, params);27942795 return super.executeExtrinsic(2796 sender,2797 'api.tx.sudo.sudo',2798 [call],2799 expectSuccess,2800 );2801 }2802 };2803}28042805export class UniqueBaseCollection {2806 helper: UniqueHelper;2807 collectionId: number;28082809 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2810 this.collectionId = collectionId;2811 this.helper = uniqueHelper;2812 }28132814 async getData() {2815 return await this.helper.collection.getData(this.collectionId);2816 }28172818 async getLastTokenId() {2819 return await this.helper.collection.getLastTokenId(this.collectionId);2820 }28212822 async doesTokenExist(tokenId: number) {2823 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2824 }28252826 async getAdmins() {2827 return await this.helper.collection.getAdmins(this.collectionId);2828 }28292830 async getAllowList() {2831 return await this.helper.collection.getAllowList(this.collectionId);2832 }28332834 async getEffectiveLimits() {2835 return await this.helper.collection.getEffectiveLimits(this.collectionId);2836 }28372838 async getProperties(propertyKeys?: string[] | null) {2839 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2840 }28412842 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2843 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2844 }28452846 async getOptions() {2847 return await this.helper.collection.getCollectionOptions(this.collectionId);2848 }28492850 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2851 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2852 }28532854 async confirmSponsorship(signer: TSigner) {2855 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2856 }28572858 async removeSponsor(signer: TSigner) {2859 return await this.helper.collection.removeSponsor(signer, this.collectionId);2860 }28612862 async setLimits(signer: TSigner, limits: ICollectionLimits) {2863 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2864 }28652866 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2867 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2868 }28692870 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2871 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2872 }28732874 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2875 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2876 }28772878 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2879 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2880 }28812882 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2883 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2884 }28852886 async setProperties(signer: TSigner, properties: IProperty[]) {2887 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2888 }28892890 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2891 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2892 }28932894 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2895 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2896 }28972898 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2899 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2900 }29012902 async disableNesting(signer: TSigner) {2903 return await this.helper.collection.disableNesting(signer, this.collectionId);2904 }29052906 async burn(signer: TSigner) {2907 return await this.helper.collection.burn(signer, this.collectionId);2908 }29092910 scheduleAt<T extends UniqueHelper>(2911 scheduledId: string,2912 executionBlockNumber: number,2913 options: ISchedulerOptions = {},2914 ) {2915 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2916 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2917 }29182919 scheduleAfter<T extends UniqueHelper>(2920 scheduledId: string,2921 blocksBeforeExecution: number,2922 options: ISchedulerOptions = {},2923 ) {2924 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2925 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2926 }29272928 getSudo<T extends UniqueHelper>() {2929 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2930 }2931}293229332934export class UniqueNFTCollection extends UniqueBaseCollection {2935 getTokenObject(tokenId: number) {2936 return new UniqueNFToken(tokenId, this);2937 }29382939 async getTokensByAddress(addressObj: ICrossAccountId) {2940 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2941 }29422943 async getToken(tokenId: number, blockHashAt?: string) {2944 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2945 }29462947 async getTokenOwner(tokenId: number, blockHashAt?: string) {2948 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2949 }29502951 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2952 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2953 }29542955 async getTokenChildren(tokenId: number, blockHashAt?: string) {2956 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2957 }29582959 async getPropertyPermissions(propertyKeys: string[] | null = null) {2960 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2961 }29622963 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2964 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2965 }29662967 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2968 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2969 }29702971 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2972 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2973 }29742975 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2976 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2977 }29782979 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2980 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2981 }29822983 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2984 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2985 }29862987 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2988 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2989 }29902991 async burnToken(signer: TSigner, tokenId: number) {2992 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2993 }29942995 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2996 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2997 }29982999 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3000 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3001 }30023003 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3004 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3005 }30063007 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3008 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3009 }30103011 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3012 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3013 }30143015 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3016 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3017 }30183019 scheduleAt<T extends UniqueHelper>(3020 scheduledId: string,3021 executionBlockNumber: number,3022 options: ISchedulerOptions = {},3023 ) {3024 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3025 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3026 }30273028 scheduleAfter<T extends UniqueHelper>(3029 scheduledId: string,3030 blocksBeforeExecution: number,3031 options: ISchedulerOptions = {},3032 ) {3033 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3034 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3035 }30363037 getSudo<T extends UniqueHelper>() {3038 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3039 }3040}304130423043export class UniqueRFTCollection extends UniqueBaseCollection {3044 getTokenObject(tokenId: number) {3045 return new UniqueRFToken(tokenId, this);3046 }30473048 async getToken(tokenId: number, blockHashAt?: string) {3049 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3050 }30513052 async getTokensByAddress(addressObj: ICrossAccountId) {3053 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3054 }30553056 async getTop10TokenOwners(tokenId: number) {3057 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3058 }30593060 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3061 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3062 }30633064 async getTokenTotalPieces(tokenId: number) {3065 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3066 }30673068 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3069 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3070 }30713072 async getPropertyPermissions(propertyKeys: string[] | null = null) {3073 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3074 }30753076 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3077 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3078 }30793080 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3081 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3082 }30833084 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3085 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3086 }30873088 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3089 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3090 }30913092 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3093 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3094 }30953096 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3097 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3098 }30993100 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3101 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3102 }31033104 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3105 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3106 }31073108 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3109 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3110 }31113112 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3113 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3114 }31153116 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3117 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3118 }31193120 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3121 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3122 }31233124 scheduleAt<T extends UniqueHelper>(3125 scheduledId: string,3126 executionBlockNumber: number,3127 options: ISchedulerOptions = {},3128 ) {3129 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3130 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3131 }31323133 scheduleAfter<T extends UniqueHelper>(3134 scheduledId: string,3135 blocksBeforeExecution: number,3136 options: ISchedulerOptions = {},3137 ) {3138 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3139 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3140 }31413142 getSudo<T extends UniqueHelper>() {3143 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3144 }3145}314631473148export class UniqueFTCollection extends UniqueBaseCollection {3149 async getBalance(addressObj: ICrossAccountId) {3150 return await this.helper.ft.getBalance(this.collectionId, addressObj);3151 }31523153 async getTotalPieces() {3154 return await this.helper.ft.getTotalPieces(this.collectionId);3155 }31563157 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3158 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3159 }31603161 async getTop10Owners() {3162 return await this.helper.ft.getTop10Owners(this.collectionId);3163 }31643165 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3166 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3167 }31683169 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3170 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3171 }31723173 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3174 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3175 }31763177 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3178 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3179 }31803181 async burnTokens(signer: TSigner, amount=1n) {3182 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3183 }31843185 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3186 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3187 }31883189 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3190 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3191 }31923193 scheduleAt<T extends UniqueHelper>(3194 scheduledId: string,3195 executionBlockNumber: number,3196 options: ISchedulerOptions = {},3197 ) {3198 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3199 return new UniqueFTCollection(this.collectionId, scheduledHelper);3200 }32013202 scheduleAfter<T extends UniqueHelper>(3203 scheduledId: string,3204 blocksBeforeExecution: number,3205 options: ISchedulerOptions = {},3206 ) {3207 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3208 return new UniqueFTCollection(this.collectionId, scheduledHelper);3209 }32103211 getSudo<T extends UniqueHelper>() {3212 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3213 }3214}321532163217export class UniqueBaseToken {3218 collection: UniqueNFTCollection | UniqueRFTCollection;3219 collectionId: number;3220 tokenId: number;32213222 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3223 this.collection = collection;3224 this.collectionId = collection.collectionId;3225 this.tokenId = tokenId;3226 }32273228 async getNextSponsored(addressObj: ICrossAccountId) {3229 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3230 }32313232 async getProperties(propertyKeys?: string[] | null) {3233 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3234 }32353236 async setProperties(signer: TSigner, properties: IProperty[]) {3237 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3238 }32393240 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3241 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3242 }32433244 async doesExist() {3245 return await this.collection.doesTokenExist(this.tokenId);3246 }32473248 nestingAccount() {3249 return this.collection.helper.util.getTokenAccount(this);3250 }32513252 scheduleAt<T extends UniqueHelper>(3253 scheduledId: string,3254 executionBlockNumber: number,3255 options: ISchedulerOptions = {},3256 ) {3257 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3258 return new UniqueBaseToken(this.tokenId, scheduledCollection);3259 }32603261 scheduleAfter<T extends UniqueHelper>(3262 scheduledId: string,3263 blocksBeforeExecution: number,3264 options: ISchedulerOptions = {},3265 ) {3266 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3267 return new UniqueBaseToken(this.tokenId, scheduledCollection);3268 }32693270 getSudo<T extends UniqueHelper>() {3271 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3272 }3273}327432753276export class UniqueNFToken extends UniqueBaseToken {3277 collection: UniqueNFTCollection;32783279 constructor(tokenId: number, collection: UniqueNFTCollection) {3280 super(tokenId, collection);3281 this.collection = collection;3282 }32833284 async getData(blockHashAt?: string) {3285 return await this.collection.getToken(this.tokenId, blockHashAt);3286 }32873288 async getOwner(blockHashAt?: string) {3289 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3290 }32913292 async getTopmostOwner(blockHashAt?: string) {3293 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3294 }32953296 async getChildren(blockHashAt?: string) {3297 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3298 }32993300 async nest(signer: TSigner, toTokenObj: IToken) {3301 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3302 }33033304 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3305 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3306 }33073308 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3309 return await this.collection.transferToken(signer, this.tokenId, addressObj);3310 }33113312 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3313 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3314 }33153316 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3317 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3318 }33193320 async isApproved(toAddressObj: ICrossAccountId) {3321 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3322 }33233324 async burn(signer: TSigner) {3325 return await this.collection.burnToken(signer, this.tokenId);3326 }33273328 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3329 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3330 }33313332 scheduleAt<T extends UniqueHelper>(3333 scheduledId: string,3334 executionBlockNumber: number,3335 options: ISchedulerOptions = {},3336 ) {3337 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3338 return new UniqueNFToken(this.tokenId, scheduledCollection);3339 }33403341 scheduleAfter<T extends UniqueHelper>(3342 scheduledId: string,3343 blocksBeforeExecution: number,3344 options: ISchedulerOptions = {},3345 ) {3346 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3347 return new UniqueNFToken(this.tokenId, scheduledCollection);3348 }33493350 getSudo<T extends UniqueHelper>() {3351 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3352 }3353}33543355export class UniqueRFToken extends UniqueBaseToken {3356 collection: UniqueRFTCollection;33573358 constructor(tokenId: number, collection: UniqueRFTCollection) {3359 super(tokenId, collection);3360 this.collection = collection;3361 }33623363 async getData(blockHashAt?: string) {3364 return await this.collection.getToken(this.tokenId, blockHashAt);3365 }33663367 async getTop10Owners() {3368 return await this.collection.getTop10TokenOwners(this.tokenId);3369 }33703371 async getBalance(addressObj: ICrossAccountId) {3372 return await this.collection.getTokenBalance(this.tokenId, addressObj);3373 }33743375 async getTotalPieces() {3376 return await this.collection.getTokenTotalPieces(this.tokenId);3377 }33783379 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3380 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3381 }33823383 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3384 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3385 }33863387 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3388 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3389 }33903391 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3392 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3393 }33943395 async repartition(signer: TSigner, amount: bigint) {3396 return await this.collection.repartitionToken(signer, this.tokenId, amount);3397 }33983399 async burn(signer: TSigner, amount=1n) {3400 return await this.collection.burnToken(signer, this.tokenId, amount);3401 }34023403 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3404 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3405 }34063407 scheduleAt<T extends UniqueHelper>(3408 scheduledId: string,3409 executionBlockNumber: number,3410 options: ISchedulerOptions = {},3411 ) {3412 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3413 return new UniqueRFToken(this.tokenId, scheduledCollection);3414 }34153416 scheduleAfter<T extends UniqueHelper>(3417 scheduledId: string,3418 blocksBeforeExecution: number,3419 options: ISchedulerOptions = {},3420 ) {3421 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3422 return new UniqueRFToken(this.tokenId, scheduledCollection);3423 }34243425 getSudo<T extends UniqueHelper>() {3426 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3427 }3428}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} 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';4243export class CrossAccountId implements ICrossAccountId {44 Substrate?: TSubstrateAccount;45 Ethereum?: TEthereumAccount;4647 constructor(account: ICrossAccountId) {48 if (account.Substrate) this.Substrate = account.Substrate;49 if (account.Ethereum) this.Ethereum = account.Ethereum;50 }5152 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {53 switch (domain) {54 case 'Substrate': return new CrossAccountId({Substrate: account.address});55 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();56 }57 }5859 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {60 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});61 }6263 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {64 return encodeAddress(decodeAddress(address), ss58Format);65 }6667 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {68 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});69 }70 71 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {72 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);73 return this;74 }7576 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {77 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));78 }7980 toEthereum(): CrossAccountId {81 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});82 return this;83 }8485 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {86 return evmToAddress(address, ss58Format);87 }8889 toSubstrate(ss58Format?: number): CrossAccountId {90 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});91 return this;92 }93 94 toLowerCase(): CrossAccountId {95 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();96 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();97 return this;98 }99}100101const nesting = {102 toChecksumAddress(address: string): string {103 if (typeof address === 'undefined') return '';104105 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);106107 address = address.toLowerCase().replace(/^0x/i,'');108 const addressHash = keccakAsHex(address).replace(/^0x/i,'');109 const checksumAddress = ['0x'];110111 for (let i = 0; i < address.length; i++) {112 // If ith character is 8 to f then make it uppercase113 if (parseInt(addressHash[i], 16) > 7) {114 checksumAddress.push(address[i].toUpperCase());115 } else {116 checksumAddress.push(address[i]);117 }118 }119 return checksumAddress.join('');120 },121 tokenIdToAddress(collectionId: number, tokenId: number) {122 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);123 },124};125126class UniqueUtil {127 static transactionStatus = {128 NOT_READY: 'NotReady',129 FAIL: 'Fail',130 SUCCESS: 'Success',131 };132133 static chainLogType = {134 EXTRINSIC: 'extrinsic',135 RPC: 'rpc',136 };137138 static getTokenAccount(token: IToken): CrossAccountId {139 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});140 }141142 static getTokenAddress(token: IToken): string {143 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);144 }145146 static getDefaultLogger(): ILogger {147 return {148 log(msg: any, level = 'INFO') {149 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));150 },151 level: {152 ERROR: 'ERROR',153 WARNING: 'WARNING',154 INFO: 'INFO',155 },156 };157 }158159 static vec2str(arr: string[] | number[]) {160 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');161 }162163 static str2vec(string: string) {164 if (typeof string !== 'string') return string;165 return Array.from(string).map(x => x.charCodeAt(0));166 }167168 static fromSeed(seed: string, ss58Format = 42) {169 const keyring = new Keyring({type: 'sr25519', ss58Format});170 return keyring.addFromUri(seed);171 }172173 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {174 if (creationResult.status !== this.transactionStatus.SUCCESS) {175 throw Error('Unable to create collection!');176 }177178 let collectionId = null;179 creationResult.result.events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'CollectionCreated')) {181 collectionId = parseInt(data[0].toString(), 10);182 }183 });184185 if (collectionId === null) {186 throw Error('No CollectionCreated event was found!');187 }188189 return collectionId;190 }191192 static extractTokensFromCreationResult(creationResult: ITransactionResult): {193 success: boolean, 194 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],195 } {196 if (creationResult.status !== this.transactionStatus.SUCCESS) {197 throw Error('Unable to create tokens!');198 }199 let success = false;200 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];201 creationResult.result.events.forEach(({event: {data, method, section}}) => {202 if (method === 'ExtrinsicSuccess') {203 success = true;204 } else if ((section === 'common') && (method === 'ItemCreated')) {205 tokens.push({206 collectionId: parseInt(data[0].toString(), 10),207 tokenId: parseInt(data[1].toString(), 10),208 owner: data[2].toHuman(),209 amount: data[3].toBigInt(),210 });211 }212 });213 return {success, tokens};214 }215216 static extractTokensFromBurnResult(burnResult: ITransactionResult): {217 success: boolean, 218 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],219 } {220 if (burnResult.status !== this.transactionStatus.SUCCESS) {221 throw Error('Unable to burn tokens!');222 }223 let success = false;224 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];225 burnResult.result.events.forEach(({event: {data, method, section}}) => {226 if (method === 'ExtrinsicSuccess') {227 success = true;228 } else if ((section === 'common') && (method === 'ItemDestroyed')) {229 tokens.push({230 collectionId: parseInt(data[0].toString(), 10),231 tokenId: parseInt(data[1].toString(), 10),232 owner: data[2].toHuman(),233 amount: data[3].toBigInt(),234 });235 }236 });237 return {success, tokens};238 }239240 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {241 let eventId = null;242 events.forEach(({event: {data, method, section}}) => {243 if ((section === expectedSection) && (method === expectedMethod)) {244 eventId = parseInt(data[0].toString(), 10);245 }246 });247248 if (eventId === null) {249 throw Error(`No ${expectedMethod} event was found!`);250 }251 return eventId === collectionId;252 }253254 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {255 const normalizeAddress = (address: string | ICrossAccountId) => {256 if(typeof address === 'string') return address;257 const obj = {} as any;258 Object.keys(address).forEach(k => {259 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];260 });261 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);262 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();263 return address;264 };265 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;266 events.forEach(({event: {data, method, section}}) => {267 if ((section === 'common') && (method === 'Transfer')) {268 const hData = (data as any).toJSON();269 transfer = {270 collectionId: hData[0],271 tokenId: hData[1],272 from: normalizeAddress(hData[2]),273 to: normalizeAddress(hData[3]),274 amount: BigInt(hData[4]),275 };276 }277 });278 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;279 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);280 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);281 isSuccess = isSuccess && amount === transfer.amount;282 return isSuccess;283 }284285 static bigIntToDecimals(number: bigint, decimals = 18) {286 const numberStr = number.toString();287 const dotPos = numberStr.length - decimals;288 289 if (dotPos <= 0) {290 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;291 } else {292 const intPart = numberStr.substring(0, dotPos);293 const fractPart = numberStr.substring(dotPos);294 return intPart + '.' + fractPart;295 }296 }297}298299class UniqueEventHelper {300 private static extractIndex(index: any): [number, number] | string {301 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];302 return index.toJSON();303 }304305 private static extractSub(data: any, subTypes: any): {[key: string]: any} {306 let obj: any = {};307 let index = 0;308309 if (data.entries) {310 for(const [key, value] of data.entries()) {311 obj[key] = this.extractData(value, subTypes[index]);312 index++;313 }314 } else obj = data.toJSON();315316 return obj;317 }318 319 private static extractData(data: any, type: any): any {320 if(!type) return data.toHuman();321 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();322 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();323 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);324 return data.toHuman();325 }326327 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {328 const parsedEvents: IEvent[] = [];329330 events.forEach((record) => {331 const {event, phase} = record;332 const types = event.typeDef;333334 const eventData: IEvent = {335 section: event.section.toString(),336 method: event.method.toString(),337 index: this.extractIndex(event.index),338 data: [],339 phase: phase.toJSON(),340 };341342 event.data.forEach((val: any, index: number) => {343 eventData.data.push(this.extractData(val, types[index]));344 });345346 parsedEvents.push(eventData);347 });348349 return parsedEvents;350 }351}352353export class ChainHelperBase {354 helperBase: any;355356 transactionStatus = UniqueUtil.transactionStatus;357 chainLogType = UniqueUtil.chainLogType;358 util: typeof UniqueUtil;359 eventHelper: typeof UniqueEventHelper;360 logger: ILogger;361 api: ApiPromise | null;362 forcedNetwork: TNetworks | null;363 network: TNetworks | null;364 chainLog: IUniqueHelperLog[];365 children: ChainHelperBase[];366 address: AddressGroup;367 chain: ChainGroup;368369 constructor(logger?: ILogger, helperBase?: any) {370 this.helperBase = helperBase;371372 this.util = UniqueUtil;373 this.eventHelper = UniqueEventHelper;374 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();375 this.logger = logger;376 this.api = null;377 this.forcedNetwork = null;378 this.network = null;379 this.chainLog = [];380 this.children = [];381 this.address = new AddressGroup(this);382 this.chain = new ChainGroup(this);383 }384385 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {386 Object.setPrototypeOf(helperCls.prototype, this);387 const newHelper = new helperCls(this.logger, options);388389 newHelper.api = this.api;390 newHelper.network = this.network;391 newHelper.forceNetwork = this.forceNetwork;392393 this.children.push(newHelper);394395 return newHelper;396 }397398 getApi(): ApiPromise {399 if(this.api === null) throw Error('API not initialized');400 return this.api;401 }402403 clearChainLog(): void {404 this.chainLog = [];405 }406407 forceNetwork(value: TNetworks): void {408 this.forcedNetwork = value;409 }410411 async connect(wsEndpoint: string, listeners?: IApiListeners) {412 if (this.api !== null) throw Error('Already connected');413 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);414 this.api = api;415 this.network = network;416 }417418 async disconnect() {419 for (const child of this.children) {420 child.clearApi();421 }422423 if (this.api === null) return;424 await this.api.disconnect();425 this.clearApi();426 }427428 clearApi() {429 this.api = null;430 this.network = null;431 }432433 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {434 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;435 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];436437 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;438439 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;440 return 'opal';441 }442443 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {444 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});445 await api.isReady;446447 const network = await this.detectNetwork(api);448449 await api.disconnect();450451 return network;452 }453454 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{455 api: ApiPromise;456 network: TNetworks;457 }> {458 if(typeof network === 'undefined' || network === null) network = 'opal';459 const supportedRPC = {460 opal: {461 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,462 },463 quartz: {464 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,465 },466 unique: {467 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,468 },469 rococo: {},470 westend: {},471 moonbeam: {},472 moonriver: {},473 acala: {},474 karura: {},475 westmint: {},476 };477 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);478 const rpc = supportedRPC[network];479480 // TODO: investigate how to replace rpc in runtime481 // api._rpcCore.addUserInterfaces(rpc);482483 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});484485 await api.isReadyOrError;486487 if (typeof listeners === 'undefined') listeners = {};488 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {489 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;490 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);491 }492493 return {api, network};494 }495496 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {497 const {events, status} = data;498 if (status.isReady) {499 return this.transactionStatus.NOT_READY;500 }501 if (status.isBroadcast) {502 return this.transactionStatus.NOT_READY;503 }504 if (status.isInBlock || status.isFinalized) {505 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');506 if (errors.length > 0) {507 return this.transactionStatus.FAIL;508 }509 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {510 return this.transactionStatus.SUCCESS;511 }512 }513514 return this.transactionStatus.FAIL;515 }516517 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {518 const sign = (callback: any) => {519 if(options !== null) return transaction.signAndSend(sender, options, callback);520 return transaction.signAndSend(sender, callback);521 };522 // eslint-disable-next-line no-async-promise-executor523 return new Promise(async (resolve, reject) => {524 try {525 const unsub = await sign((result: any) => {526 const status = this.getTransactionStatus(result);527528 if (status === this.transactionStatus.SUCCESS) {529 this.logger.log(`${label} successful`);530 unsub();531 resolve({result, status});532 } else if (status === this.transactionStatus.FAIL) {533 let moduleError = null;534535 if (result.hasOwnProperty('dispatchError')) {536 const dispatchError = result['dispatchError'];537538 if (dispatchError) {539 if (dispatchError.isModule) {540 const modErr = dispatchError.asModule;541 const errorMeta = dispatchError.registry.findMetaError(modErr);542543 moduleError = `${errorMeta.section}.${errorMeta.name}`;544 } else {545 moduleError = dispatchError.toHuman();546 }547 } else {548 this.logger.log(result, this.logger.level.ERROR);549 }550 }551552 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);553 unsub();554 reject({status, moduleError, result});555 }556 });557 } catch (e) {558 this.logger.log(e, this.logger.level.ERROR);559 reject(e);560 }561 });562 }563564 constructApiCall(apiCall: string, params: any[]) {565 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);566 let call = this.getApi() as any;567 for(const part of apiCall.slice(4).split('.')) {568 call = call[part];569 }570 return call(...params);571 }572573 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {574 if(this.api === null) throw Error('API not initialized');575 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);576577 const startTime = (new Date()).getTime();578 let result: ITransactionResult;579 let events: IEvent[] = [];580 try {581 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;582 events = this.eventHelper.extractEvents(result.result.events);583 }584 catch(e) {585 if(!(e as object).hasOwnProperty('status')) throw e;586 result = e as ITransactionResult;587 }588589 const endTime = (new Date()).getTime();590591 const log = {592 executedAt: endTime,593 executionTime: endTime - startTime,594 type: this.chainLogType.EXTRINSIC,595 status: result.status,596 call: extrinsic,597 signer: this.getSignerAddress(sender),598 params,599 } as IUniqueHelperLog;600601 if(result.status !== this.transactionStatus.SUCCESS) {602 if (result.moduleError) log.moduleError = result.moduleError;603 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;604 }605 if(events.length > 0) log.events = events;606607 this.chainLog.push(log);608609 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {610 if (result.moduleError) throw Error(`${result.moduleError}`);611 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));612 }613 return result;614 }615616 async callRpc(rpc: string, params?: any[]) {617 if(typeof params === 'undefined') params = [];618 if(this.api === null) throw Error('API not initialized');619 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);620621 const startTime = (new Date()).getTime();622 let result;623 let error = null;624 const log = {625 type: this.chainLogType.RPC,626 call: rpc,627 params,628 } as IUniqueHelperLog;629630 try {631 result = await this.constructApiCall(rpc, params);632 }633 catch(e) {634 error = e;635 }636637 const endTime = (new Date()).getTime();638639 log.executedAt = endTime;640 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';641 log.executionTime = endTime - startTime;642643 this.chainLog.push(log);644645 if(error !== null) throw error;646647 return result;648 }649650 getSignerAddress(signer: IKeyringPair | string): string {651 if(typeof signer === 'string') return signer;652 return signer.address;653 }654655 fetchAllPalletNames(): string[] {656 if(this.api === null) throw Error('API not initialized');657 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());658 }659660 fetchMissingPalletNames(requiredPallets: string[]): string[] {661 const palletNames = this.fetchAllPalletNames();662 return requiredPallets.filter(p => !palletNames.includes(p));663 }664}665666667class HelperGroup<T extends ChainHelperBase> {668 helper: T;669670 constructor(uniqueHelper: T) {671 this.helper = uniqueHelper;672 }673}674675676class CollectionGroup extends HelperGroup<UniqueHelper> {677 /**678 * Get number of blocks when sponsored transaction is available.679 *680 * @param collectionId ID of collection681 * @param tokenId ID of token682 * @param addressObj address for which the sponsorship is checked683 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});684 * @returns number of blocks or null if sponsorship hasn't been set685 */686 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {687 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();688 }689690 /**691 * Get the number of created collections.692 *693 * @returns number of created collections694 */695 async getTotalCount(): Promise<number> {696 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();697 }698699 /**700 * Get information about the collection with additional data,701 * including the number of tokens it contains, its administrators,702 * the normalized address of the collection's owner, and decoded name and description.703 *704 * @param collectionId ID of collection705 * @example await getData(2)706 * @returns collection information object707 */708 async getData(collectionId: number): Promise<{709 id: number;710 name: string;711 description: string;712 tokensCount: number;713 admins: CrossAccountId[];714 normalizedOwner: TSubstrateAccount;715 raw: any716 } | null> {717 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);718 const humanCollection = collection.toHuman(), collectionData = {719 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],720 raw: humanCollection,721 } as any, jsonCollection = collection.toJSON();722 if (humanCollection === null) return null;723 collectionData.raw.limits = jsonCollection.limits;724 collectionData.raw.permissions = jsonCollection.permissions;725 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);726 for (const key of ['name', 'description']) {727 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);728 }729730 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))731 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)732 : 0;733 collectionData.admins = await this.getAdmins(collectionId);734735 return collectionData;736 }737738 /**739 * Get the addresses of the collection's administrators, optionally normalized.740 *741 * @param collectionId ID of collection742 * @param normalize whether to normalize the addresses to the default ss58 format743 * @example await getAdmins(1)744 * @returns array of administrators745 */746 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {747 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();748749 return normalize750 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())751 : admins;752 }753754 /**755 * Get the addresses added to the collection allow-list, optionally normalized.756 * @param collectionId ID of collection757 * @param normalize whether to normalize the addresses to the default ss58 format758 * @example await getAllowList(1)759 * @returns array of allow-listed addresses760 */761 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {762 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();763 return normalize764 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())765 : allowListed;766 }767768 /**769 * Get the effective limits of the collection instead of null for default values770 *771 * @param collectionId ID of collection772 * @example await getEffectiveLimits(2)773 * @returns object of collection limits774 */775 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {776 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();777 }778779 /**780 * Burns the collection if the signer has sufficient permissions and collection is empty.781 *782 * @param signer keyring of signer783 * @param collectionId ID of collection784 * @example await helper.collection.burn(aliceKeyring, 3);785 * @returns ```true``` if extrinsic success, otherwise ```false```786 */787 async burn(signer: TSigner, collectionId: number): Promise<boolean> {788 const result = await this.helper.executeExtrinsic(789 signer,790 'api.tx.unique.destroyCollection', [collectionId],791 true,792 );793794 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');795 }796797 /**798 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.799 *800 * @param signer keyring of signer801 * @param collectionId ID of collection802 * @param sponsorAddress Sponsor substrate address803 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")804 * @returns ```true``` if extrinsic success, otherwise ```false```805 */806 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {807 const result = await this.helper.executeExtrinsic(808 signer,809 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],810 true,811 );812813 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');814 }815816 /**817 * Confirms consent to sponsor the collection on behalf of the signer.818 *819 * @param signer keyring of signer820 * @param collectionId ID of collection821 * @example confirmSponsorship(aliceKeyring, 10)822 * @returns ```true``` if extrinsic success, otherwise ```false```823 */824 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {825 const result = await this.helper.executeExtrinsic(826 signer,827 'api.tx.unique.confirmSponsorship', [collectionId],828 true,829 );830831 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');832 }833834 /**835 * Removes the sponsor of a collection, regardless if it consented or not.836 *837 * @param signer keyring of signer838 * @param collectionId ID of collection839 * @example removeSponsor(aliceKeyring, 10)840 * @returns ```true``` if extrinsic success, otherwise ```false```841 */842 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {843 const result = await this.helper.executeExtrinsic(844 signer,845 'api.tx.unique.removeCollectionSponsor', [collectionId],846 true,847 );848849 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');850 }851852 /**853 * Sets the limits of the collection. At least one limit must be specified for a correct call.854 *855 * @param signer keyring of signer856 * @param collectionId ID of collection857 * @param limits collection limits object858 * @example859 * await setLimits(860 * aliceKeyring,861 * 10,862 * {863 * sponsorTransferTimeout: 0,864 * ownerCanDestroy: false865 * }866 * )867 * @returns ```true``` if extrinsic success, otherwise ```false```868 */869 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.setCollectionLimits', [collectionId, limits],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');877 }878879 /**880 * Changes the owner of the collection to the new Substrate address.881 *882 * @param signer keyring of signer883 * @param collectionId ID of collection884 * @param ownerAddress substrate address of new owner885 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")886 * @returns ```true``` if extrinsic success, otherwise ```false```887 */888 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {889 const result = await this.helper.executeExtrinsic(890 signer,891 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],892 true,893 );894895 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');896 }897898 /**899 * Adds a collection administrator.900 *901 * @param signer keyring of signer902 * @param collectionId ID of collection903 * @param adminAddressObj Administrator address (substrate or ethereum)904 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})905 * @returns ```true``` if extrinsic success, otherwise ```false```906 */907 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {908 const result = await this.helper.executeExtrinsic(909 signer,910 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],911 true,912 );913914 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');915 }916917 /**918 * Removes a collection administrator.919 *920 * @param signer keyring of signer921 * @param collectionId ID of collection922 * @param adminAddressObj Administrator address (substrate or ethereum)923 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})924 * @returns ```true``` if extrinsic success, otherwise ```false```925 */926 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {927 const result = await this.helper.executeExtrinsic(928 signer,929 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],930 true,931 );932933 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');934 }935936 /**937 * Check if user is in allow list.938 * 939 * @param collectionId ID of collection940 * @param user Account to check941 * @example await getAdmins(1)942 * @returns is user in allow list943 */944 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {945 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();946 }947948 /**949 * Adds an address to allow list950 * @param signer keyring of signer951 * @param collectionId ID of collection952 * @param addressObj address to add to the allow list953 * @returns ```true``` if extrinsic success, otherwise ```false```954 */955 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {956 const result = await this.helper.executeExtrinsic(957 signer,958 'api.tx.unique.addToAllowList', [collectionId, addressObj],959 true,960 );961962 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');963 }964965 /**966 * Removes an address from allow list967 *968 * @param signer keyring of signer969 * @param collectionId ID of collection970 * @param addressObj address to remove from the allow list971 * @returns ```true``` if extrinsic success, otherwise ```false```972 */973 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {974 const result = await this.helper.executeExtrinsic(975 signer,976 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],977 true,978 );979980 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');981 }982983 /**984 * Sets onchain permissions for selected collection.985 *986 * @param signer keyring of signer987 * @param collectionId ID of collection988 * @param permissions collection permissions object989 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});990 * @returns ```true``` if extrinsic success, otherwise ```false```991 */992 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {993 const result = await this.helper.executeExtrinsic(994 signer,995 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],996 true,997 );998999 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1000 }10011002 /**1003 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1004 *1005 * @param signer keyring of signer1006 * @param collectionId ID of collection1007 * @param permissions nesting permissions object1008 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1009 * @returns ```true``` if extrinsic success, otherwise ```false```1010 */1011 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1012 return await this.setPermissions(signer, collectionId, {nesting: permissions});1013 }10141015 /**1016 * Disables nesting for selected collection.1017 *1018 * @param signer keyring of signer1019 * @param collectionId ID of collection1020 * @example disableNesting(aliceKeyring, 10);1021 * @returns ```true``` if extrinsic success, otherwise ```false```1022 */1023 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1024 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1025 }10261027 /**1028 * Sets onchain properties to the collection.1029 *1030 * @param signer keyring of signer1031 * @param collectionId ID of collection1032 * @param properties array of property objects1033 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1034 * @returns ```true``` if extrinsic success, otherwise ```false```1035 */1036 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1037 const result = await this.helper.executeExtrinsic(1038 signer,1039 'api.tx.unique.setCollectionProperties', [collectionId, properties],1040 true,1041 );10421043 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1044 }10451046 /**1047 * Get collection properties.1048 * 1049 * @param collectionId ID of collection1050 * @param propertyKeys optionally filter the returned properties to only these keys1051 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1052 * @returns array of key-value pairs1053 */1054 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1055 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1056 }10571058 async getCollectionOptions(collectionId: number) {1059 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1060 }10611062 /**1063 * Deletes onchain properties from the collection.1064 *1065 * @param signer keyring of signer1066 * @param collectionId ID of collection1067 * @param propertyKeys array of property keys to delete1068 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1069 * @returns ```true``` if extrinsic success, otherwise ```false```1070 */1071 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1072 const result = await this.helper.executeExtrinsic(1073 signer,1074 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1075 true,1076 );10771078 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1079 }10801081 /**1082 * Changes the owner of the token.1083 *1084 * @param signer keyring of signer1085 * @param collectionId ID of collection1086 * @param tokenId ID of token1087 * @param addressObj address of a new owner1088 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1089 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1090 * @returns true if the token success, otherwise false1091 */1092 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1093 const result = await this.helper.executeExtrinsic(1094 signer,1095 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1096 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1097 );10981099 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1100 }11011102 /**1103 *1104 * Change ownership of a token(s) on behalf of the owner.1105 *1106 * @param signer keyring of signer1107 * @param collectionId ID of collection1108 * @param tokenId ID of token1109 * @param fromAddressObj address on behalf of which the token will be sent1110 * @param toAddressObj new token owner1111 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1112 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1113 * @returns true if the token success, otherwise false1114 */1115 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1116 const result = await this.helper.executeExtrinsic(1117 signer,1118 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1119 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1120 );1121 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1122 }11231124 /**1125 *1126 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1127 *1128 * @param signer keyring of signer1129 * @param collectionId ID of collection1130 * @param tokenId ID of token1131 * @param amount amount of tokens to be burned. For NFT must be set to 1n1132 * @example burnToken(aliceKeyring, 10, 5);1133 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1134 */1135 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1136 const burnResult = await this.helper.executeExtrinsic(1137 signer,1138 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1139 true, // `Unable to burn token for ${label}`,1140 );1141 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1142 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1143 return burnedTokens.success;1144 }11451146 /**1147 * Destroys a concrete instance of NFT on behalf of the owner1148 *1149 * @param signer keyring of signer1150 * @param collectionId ID of collection1151 * @param tokenId ID of token1152 * @param fromAddressObj address on behalf of which the token will be burnt1153 * @param amount amount of tokens to be burned. For NFT must be set to 1n1154 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1155 * @returns ```true``` if extrinsic success, otherwise ```false```1156 */1157 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1158 const burnResult = await this.helper.executeExtrinsic(1159 signer,1160 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1161 true, // `Unable to burn token from for ${label}`,1162 );1163 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1164 return burnedTokens.success && burnedTokens.tokens.length > 0;1165 }11661167 /**1168 * Set, change, or remove approved address to transfer the ownership of the NFT.1169 *1170 * @param signer keyring of signer1171 * @param collectionId ID of collection1172 * @param tokenId ID of token1173 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1174 * @param amount amount of token to be approved. For NFT must be set to 1n1175 * @returns ```true``` if extrinsic success, otherwise ```false```1176 */1177 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1178 const approveResult = await this.helper.executeExtrinsic(1179 signer,1180 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1181 true, // `Unable to approve token for ${label}`,1182 );11831184 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1185 }11861187 /**1188 * Get the amount of token pieces approved to transfer or burn. Normally 0.1189 *1190 * @param collectionId ID of collection1191 * @param tokenId ID of token1192 * @param toAccountObj address which is approved to use token pieces1193 * @param fromAccountObj address which may have allowed the use of its owned tokens1194 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1195 * @returns number of approved to transfer pieces1196 */1197 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1198 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1199 }12001201 /**1202 * Get the last created token ID in a collection1203 *1204 * @param collectionId ID of collection1205 * @example getLastTokenId(10);1206 * @returns id of the last created token1207 */1208 async getLastTokenId(collectionId: number): Promise<number> {1209 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1210 }12111212 /**1213 * Check if token exists1214 *1215 * @param collectionId ID of collection1216 * @param tokenId ID of token1217 * @example doesTokenExist(10, 20);1218 * @returns true if the token exists, otherwise false1219 */1220 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1221 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1222 }1223}12241225class NFTnRFT extends CollectionGroup {1226 /**1227 * Get tokens owned by account1228 *1229 * @param collectionId ID of collection1230 * @param addressObj tokens owner1231 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1232 * @returns array of token ids owned by account1233 */1234 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1235 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1236 }12371238 /**1239 * Get token data1240 *1241 * @param collectionId ID of collection1242 * @param tokenId ID of token1243 * @param propertyKeys optionally filter the token properties to only these keys1244 * @param blockHashAt optionally query the data at some block with this hash1245 * @example getToken(10, 5);1246 * @returns human readable token data1247 */1248 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1249 properties: IProperty[];1250 owner: CrossAccountId;1251 normalizedOwner: CrossAccountId;1252 }| null> {1253 let tokenData;1254 if(typeof blockHashAt === 'undefined') {1255 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1256 }1257 else {1258 if(propertyKeys.length == 0) {1259 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1260 if(!collection) return null;1261 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1262 }1263 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1264 }1265 tokenData = tokenData.toHuman();1266 if (tokenData === null || tokenData.owner === null) return null;1267 const owner = {} as any;1268 for (const key of Object.keys(tokenData.owner)) {1269 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1270 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1271 : tokenData.owner[key];1272 }1273 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1274 return tokenData;1275 }12761277 /**1278 * Set permissions to change token properties1279 *1280 * @param signer keyring of signer1281 * @param collectionId ID of collection1282 * @param permissions permissions to change a property by the collection admin or token owner1283 * @example setTokenPropertyPermissions(1284 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1285 * )1286 * @returns true if extrinsic success otherwise false1287 */1288 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1289 const result = await this.helper.executeExtrinsic(1290 signer,1291 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1292 true,1293 );12941295 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1296 }12971298 /**1299 * Get token property permissions.1300 * 1301 * @param collectionId ID of collection1302 * @param propertyKeys optionally filter the returned property permissions to only these keys1303 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1304 * @returns array of key-permission pairs1305 */1306 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1307 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1308 }13091310 /**1311 * Set token properties1312 *1313 * @param signer keyring of signer1314 * @param collectionId ID of collection1315 * @param tokenId ID of token1316 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1317 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1318 * @returns ```true``` if extrinsic success, otherwise ```false```1319 */1320 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1321 const result = await this.helper.executeExtrinsic(1322 signer,1323 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1324 true,1325 );13261327 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1328 }13291330 /**1331 * Get properties, metadata assigned to a token.1332 * 1333 * @param collectionId ID of collection1334 * @param tokenId ID of token1335 * @param propertyKeys optionally filter the returned properties to only these keys1336 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1337 * @returns array of key-value pairs1338 */1339 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1340 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1341 }13421343 /**1344 * Delete the provided properties of a token1345 * @param signer keyring of signer1346 * @param collectionId ID of collection1347 * @param tokenId ID of token1348 * @param propertyKeys property keys to be deleted1349 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1350 * @returns ```true``` if extrinsic success, otherwise ```false```1351 */1352 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1353 const result = await this.helper.executeExtrinsic(1354 signer,1355 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1356 true,1357 );13581359 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1360 }13611362 /**1363 * Mint new collection1364 *1365 * @param signer keyring of signer1366 * @param collectionOptions basic collection options and properties1367 * @param mode NFT or RFT type of a collection1368 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1369 * @returns object of the created collection1370 */1371 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1372 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1373 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1374 for (const key of ['name', 'description', 'tokenPrefix']) {1375 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);1376 }1377 const creationResult = await this.helper.executeExtrinsic(1378 signer,1379 'api.tx.unique.createCollectionEx', [collectionOptions],1380 true, // errorLabel,1381 );1382 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1383 }13841385 getCollectionObject(_collectionId: number): any {1386 return null;1387 }13881389 getTokenObject(_collectionId: number, _tokenId: number): any {1390 return null;1391 }1392}139313941395class NFTGroup extends NFTnRFT {1396 /**1397 * Get collection object1398 * @param collectionId ID of collection1399 * @example getCollectionObject(2);1400 * @returns instance of UniqueNFTCollection1401 */1402 getCollectionObject(collectionId: number): UniqueNFTCollection {1403 return new UniqueNFTCollection(collectionId, this.helper);1404 }14051406 /**1407 * Get token object1408 * @param collectionId ID of collection1409 * @param tokenId ID of token1410 * @example getTokenObject(10, 5);1411 * @returns instance of UniqueNFTToken1412 */1413 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1414 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1415 }14161417 /**1418 * Get token's owner1419 * @param collectionId ID of collection1420 * @param tokenId ID of token1421 * @param blockHashAt optionally query the data at the block with this hash1422 * @example getTokenOwner(10, 5);1423 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1424 */1425 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1426 let owner;1427 if (typeof blockHashAt === 'undefined') {1428 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1429 } else {1430 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1431 }1432 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1433 }14341435 /**1436 * Is token approved to transfer1437 * @param collectionId ID of collection1438 * @param tokenId ID of token1439 * @param toAccountObj address to be approved1440 * @returns ```true``` if extrinsic success, otherwise ```false```1441 */1442 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1443 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1444 }14451446 /**1447 * Changes the owner of the token.1448 *1449 * @param signer keyring of signer1450 * @param collectionId ID of collection1451 * @param tokenId ID of token1452 * @param addressObj address of a new owner1453 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1454 * @returns ```true``` if extrinsic success, otherwise ```false```1455 */1456 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1457 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1458 }14591460 /**1461 *1462 * Change ownership of a NFT on behalf of the owner.1463 *1464 * @param signer keyring of signer1465 * @param collectionId ID of collection1466 * @param tokenId ID of token1467 * @param fromAddressObj address on behalf of which the token will be sent1468 * @param toAddressObj new token owner1469 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1470 * @returns ```true``` if extrinsic success, otherwise ```false```1471 */1472 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1473 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1474 }14751476 /**1477 * Recursively find the address that owns the token1478 * @param collectionId ID of collection1479 * @param tokenId ID of token1480 * @param blockHashAt1481 * @example getTokenTopmostOwner(10, 5);1482 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1483 */1484 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1485 let owner;1486 if (typeof blockHashAt === 'undefined') {1487 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1488 } else {1489 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1490 }14911492 if (owner === null) return null;14931494 return owner.toHuman();1495 }14961497 /**1498 * Get tokens nested in the provided token1499 * @param collectionId ID of collection1500 * @param tokenId ID of token1501 * @param blockHashAt optionally query the data at the block with this hash1502 * @example getTokenChildren(10, 5);1503 * @returns tokens whose depth of nesting is <= 51504 */1505 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1506 let children;1507 if(typeof blockHashAt === 'undefined') {1508 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1509 } else {1510 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1511 }15121513 return children.toJSON().map((x: any) => {1514 return {collectionId: x.collection, tokenId: x.token};1515 });1516 }15171518 /**1519 * Nest one token into another1520 * @param signer keyring of signer1521 * @param tokenObj token to be nested1522 * @param rootTokenObj token to be parent1523 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1524 * @returns ```true``` if extrinsic success, otherwise ```false```1525 */1526 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1527 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1528 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1529 if(!result) {1530 throw Error('Unable to nest token!');1531 }1532 return result;1533 }15341535 /**1536 * Remove token from nested state1537 * @param signer keyring of signer1538 * @param tokenObj token to unnest1539 * @param rootTokenObj parent of a token1540 * @param toAddressObj address of a new token owner1541 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1542 * @returns ```true``` if extrinsic success, otherwise ```false```1543 */1544 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1545 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1546 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1547 if(!result) {1548 throw Error('Unable to unnest token!');1549 }1550 return result;1551 }15521553 /**1554 * Mint new collection1555 * @param signer keyring of signer1556 * @param collectionOptions Collection options1557 * @example1558 * mintCollection(aliceKeyring, {1559 * name: 'New',1560 * description: 'New collection',1561 * tokenPrefix: 'NEW',1562 * })1563 * @returns object of the created collection1564 */1565 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1566 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1567 }15681569 /**1570 * Mint new token1571 * @param signer keyring of signer1572 * @param data token data1573 * @returns created token object1574 */1575 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1576 const creationResult = await this.helper.executeExtrinsic(1577 signer,1578 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1579 nft: {1580 properties: data.properties,1581 },1582 }],1583 true,1584 );1585 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1586 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1587 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1588 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1589 }15901591 /**1592 * Mint multiple NFT tokens1593 * @param signer keyring of signer1594 * @param collectionId ID of collection1595 * @param tokens array of tokens with owner and properties1596 * @example1597 * mintMultipleTokens(aliceKeyring, 10, [{1598 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1599 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1600 * },{1601 * owner: {Ethereum: "0x9F0583DbB855d..."},1602 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1603 * }]);1604 * @returns ```true``` if extrinsic success, otherwise ```false```1605 */1606 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1607 const creationResult = await this.helper.executeExtrinsic(1608 signer,1609 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1610 true,1611 );1612 const collection = this.getCollectionObject(collectionId);1613 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1614 }16151616 /**1617 * Mint multiple NFT tokens with one owner1618 * @param signer keyring of signer1619 * @param collectionId ID of collection1620 * @param owner tokens owner1621 * @param tokens array of tokens with owner and properties1622 * @example1623 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1624 * properties: [{1625 * key: "gender",1626 * value: "female",1627 * },{1628 * key: "age",1629 * value: "33",1630 * }],1631 * }]);1632 * @returns array of newly created tokens1633 */1634 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1635 const rawTokens = [];1636 for (const token of tokens) {1637 const raw = {NFT: {properties: token.properties}};1638 rawTokens.push(raw);1639 }1640 const creationResult = await this.helper.executeExtrinsic(1641 signer,1642 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1643 true,1644 );1645 const collection = this.getCollectionObject(collectionId);1646 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1647 }16481649 /**1650 * Set, change, or remove approved address to transfer the ownership of the NFT.1651 *1652 * @param signer keyring of signer1653 * @param collectionId ID of collection1654 * @param tokenId ID of token1655 * @param toAddressObj address to approve1656 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1657 * @returns ```true``` if extrinsic success, otherwise ```false```1658 */1659 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1660 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1661 }1662}166316641665class RFTGroup extends NFTnRFT {1666 /**1667 * Get collection object1668 * @param collectionId ID of collection1669 * @example getCollectionObject(2);1670 * @returns instance of UniqueRFTCollection1671 */1672 getCollectionObject(collectionId: number): UniqueRFTCollection {1673 return new UniqueRFTCollection(collectionId, this.helper);1674 }16751676 /**1677 * Get token object1678 * @param collectionId ID of collection1679 * @param tokenId ID of token1680 * @example getTokenObject(10, 5);1681 * @returns instance of UniqueNFTToken1682 */1683 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1684 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1685 }16861687 /**1688 * Get top 10 token owners with the largest number of pieces1689 * @param collectionId ID of collection1690 * @param tokenId ID of token1691 * @example getTokenTop10Owners(10, 5);1692 * @returns array of top 10 owners1693 */1694 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1695 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1696 }16971698 /**1699 * Get number of pieces owned by address1700 * @param collectionId ID of collection1701 * @param tokenId ID of token1702 * @param addressObj address token owner1703 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1704 * @returns number of pieces ownerd by address1705 */1706 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1707 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1708 }17091710 /**1711 * Transfer pieces of token to another address1712 * @param signer keyring of signer1713 * @param collectionId ID of collection1714 * @param tokenId ID of token1715 * @param addressObj address of a new owner1716 * @param amount number of pieces to be transfered1717 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1718 * @returns ```true``` if extrinsic success, otherwise ```false```1719 */1720 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1721 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1722 }17231724 /**1725 * Change ownership of some pieces of RFT on behalf of the owner.1726 * @param signer keyring of signer1727 * @param collectionId ID of collection1728 * @param tokenId ID of token1729 * @param fromAddressObj address on behalf of which the token will be sent1730 * @param toAddressObj new token owner1731 * @param amount number of pieces to be transfered1732 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1733 * @returns ```true``` if extrinsic success, otherwise ```false```1734 */1735 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1736 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1737 }17381739 /**1740 * Mint new collection1741 * @param signer keyring of signer1742 * @param collectionOptions Collection options1743 * @example1744 * mintCollection(aliceKeyring, {1745 * name: 'New',1746 * description: 'New collection',1747 * tokenPrefix: 'NEW',1748 * })1749 * @returns object of the created collection1750 */1751 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1752 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1753 }17541755 /**1756 * Mint new token1757 * @param signer keyring of signer1758 * @param data token data1759 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1760 * @returns created token object1761 */1762 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1763 const creationResult = await this.helper.executeExtrinsic(1764 signer,1765 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1766 refungible: {1767 pieces: data.pieces,1768 properties: data.properties,1769 },1770 }],1771 true,1772 );1773 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1774 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1775 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1776 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1777 }17781779 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1780 throw Error('Not implemented');1781 const creationResult = await this.helper.executeExtrinsic(1782 signer,1783 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1784 true, // `Unable to mint RFT tokens for ${label}`,1785 );1786 const collection = this.getCollectionObject(collectionId);1787 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1788 }17891790 /**1791 * Mint multiple RFT tokens with one owner1792 * @param signer keyring of signer1793 * @param collectionId ID of collection1794 * @param owner tokens owner1795 * @param tokens array of tokens with properties and pieces1796 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1797 * @returns array of newly created RFT tokens1798 */1799 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1800 const rawTokens = [];1801 for (const token of tokens) {1802 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1803 rawTokens.push(raw);1804 }1805 const creationResult = await this.helper.executeExtrinsic(1806 signer,1807 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1808 true,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 * Destroys a concrete instance of RFT.1816 * @param signer keyring of signer1817 * @param collectionId ID of collection1818 * @param tokenId ID of token1819 * @param amount number of pieces to be burnt1820 * @example burnToken(aliceKeyring, 10, 5);1821 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1822 */1823 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1824 return await super.burnToken(signer, collectionId, tokenId, amount);1825 }18261827 /**1828 * Destroys a concrete instance of RFT on behalf of the owner.1829 * @param signer keyring of signer1830 * @param collectionId ID of collection1831 * @param tokenId ID of token1832 * @param fromAddressObj address on behalf of which the token will be burnt1833 * @param amount number of pieces to be burnt1834 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1835 * @returns ```true``` if extrinsic success, otherwise ```false```1836 */1837 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1838 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1839 }18401841 /**1842 * Set, change, or remove approved address to transfer the ownership of the RFT.1843 *1844 * @param signer keyring of signer1845 * @param collectionId ID of collection1846 * @param tokenId ID of token1847 * @param toAddressObj address to approve1848 * @param amount number of pieces to be approved1849 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1850 * @returns true if the token success, otherwise false1851 */1852 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1853 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1854 }18551856 /**1857 * Get total number of pieces1858 * @param collectionId ID of collection1859 * @param tokenId ID of token1860 * @example getTokenTotalPieces(10, 5);1861 * @returns number of pieces1862 */1863 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1864 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1865 }18661867 /**1868 * Change number of token pieces. Signer must be the owner of all token pieces.1869 * @param signer keyring of signer1870 * @param collectionId ID of collection1871 * @param tokenId ID of token1872 * @param amount new number of pieces1873 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1874 * @returns true if the repartion was success, otherwise false1875 */1876 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1877 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1878 const repartitionResult = await this.helper.executeExtrinsic(1879 signer,1880 'api.tx.unique.repartition', [collectionId, tokenId, amount],1881 true,1882 );1883 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1884 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1885 }1886}188718881889class FTGroup extends CollectionGroup {1890 /**1891 * Get collection object1892 * @param collectionId ID of collection1893 * @example getCollectionObject(2);1894 * @returns instance of UniqueFTCollection1895 */1896 getCollectionObject(collectionId: number): UniqueFTCollection {1897 return new UniqueFTCollection(collectionId, this.helper);1898 }18991900 /**1901 * Mint new fungible collection1902 * @param signer keyring of signer1903 * @param collectionOptions Collection options1904 * @param decimalPoints number of token decimals1905 * @example1906 * mintCollection(aliceKeyring, {1907 * name: 'New',1908 * description: 'New collection',1909 * tokenPrefix: 'NEW',1910 * }, 18)1911 * @returns newly created fungible collection1912 */1913 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1914 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1915 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1916 collectionOptions.mode = {fungible: decimalPoints};1917 for (const key of ['name', 'description', 'tokenPrefix']) {1918 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);1919 }1920 const creationResult = await this.helper.executeExtrinsic(1921 signer,1922 'api.tx.unique.createCollectionEx', [collectionOptions],1923 true,1924 );1925 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1926 }19271928 /**1929 * Mint tokens1930 * @param signer keyring of signer1931 * @param collectionId ID of collection1932 * @param owner address owner of new tokens1933 * @param amount amount of tokens to be meanted1934 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1935 * @returns ```true``` if extrinsic success, otherwise ```false```1936 */1937 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1938 const creationResult = await this.helper.executeExtrinsic(1939 signer,1940 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1941 fungible: {1942 value: amount,1943 },1944 }],1945 true, // `Unable to mint fungible tokens for ${label}`,1946 );1947 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1948 }19491950 /**1951 * Mint multiple Fungible tokens with one owner1952 * @param signer keyring of signer1953 * @param collectionId ID of collection1954 * @param owner tokens owner1955 * @param tokens array of tokens with properties and pieces1956 * @returns ```true``` if extrinsic success, otherwise ```false```1957 */1958 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1959 const rawTokens = [];1960 for (const token of tokens) {1961 const raw = {Fungible: {Value: token.value}};1962 rawTokens.push(raw);1963 }1964 const creationResult = await this.helper.executeExtrinsic(1965 signer,1966 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1967 true,1968 );1969 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1970 }19711972 /**1973 * Get the top 10 owners with the largest balance for the Fungible collection1974 * @param collectionId ID of collection1975 * @example getTop10Owners(10);1976 * @returns array of ```ICrossAccountId```1977 */1978 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1979 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1980 }19811982 /**1983 * Get account balance1984 * @param collectionId ID of collection1985 * @param addressObj address of owner1986 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1987 * @returns amount of fungible tokens owned by address1988 */1989 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1990 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1991 }19921993 /**1994 * Transfer tokens to address1995 * @param signer keyring of signer1996 * @param collectionId ID of collection1997 * @param toAddressObj address recipient1998 * @param amount amount of tokens to be sent1999 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2000 * @returns ```true``` if extrinsic success, otherwise ```false```2001 */2002 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2003 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2004 }20052006 /**2007 * Transfer some tokens on behalf of the owner.2008 * @param signer keyring of signer2009 * @param collectionId ID of collection2010 * @param fromAddressObj address on behalf of which tokens will be sent2011 * @param toAddressObj address where token to be sent2012 * @param amount number of tokens to be sent2013 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2014 * @returns ```true``` if extrinsic success, otherwise ```false```2015 */2016 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2017 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2018 }20192020 /**2021 * Destroy some amount of tokens2022 * @param signer keyring of signer2023 * @param collectionId ID of collection2024 * @param amount amount of tokens to be destroyed2025 * @example burnTokens(aliceKeyring, 10, 1000n);2026 * @returns ```true``` if extrinsic success, otherwise ```false```2027 */2028 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2029 return await super.burnToken(signer, collectionId, 0, amount);2030 }20312032 /**2033 * Burn some tokens on behalf of the owner.2034 * @param signer keyring of signer2035 * @param collectionId ID of collection2036 * @param fromAddressObj address on behalf of which tokens will be burnt2037 * @param amount amount of tokens to be burnt2038 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2039 * @returns ```true``` if extrinsic success, otherwise ```false```2040 */2041 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2042 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2043 }20442045 /**2046 * Get total collection supply2047 * @param collectionId2048 * @returns2049 */2050 async getTotalPieces(collectionId: number): Promise<bigint> {2051 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2052 }20532054 /**2055 * Set, change, or remove approved address to transfer tokens.2056 *2057 * @param signer keyring of signer2058 * @param collectionId ID of collection2059 * @param toAddressObj address to be approved2060 * @param amount amount of tokens to be approved2061 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2062 * @returns ```true``` if extrinsic success, otherwise ```false```2063 */2064 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2065 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2066 }20672068 /**2069 * Get amount of fungible tokens approved to transfer2070 * @param collectionId ID of collection2071 * @param fromAddressObj owner of tokens2072 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2073 * @returns number of tokens approved for the transfer2074 */2075 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2076 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2077 }2078}207920802081class ChainGroup extends HelperGroup<ChainHelperBase> {2082 /**2083 * Get system properties of a chain2084 * @example getChainProperties();2085 * @returns ss58Format, token decimals, and token symbol2086 */2087 getChainProperties(): IChainProperties {2088 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2089 return {2090 ss58Format: properties.ss58Format.toJSON(),2091 tokenDecimals: properties.tokenDecimals.toJSON(),2092 tokenSymbol: properties.tokenSymbol.toJSON(),2093 };2094 }20952096 /**2097 * Get chain header2098 * @example getLatestBlockNumber();2099 * @returns the number of the last block2100 */2101 async getLatestBlockNumber(): Promise<number> {2102 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2103 }21042105 /**2106 * Get block hash by block number2107 * @param blockNumber number of block2108 * @example getBlockHashByNumber(12345);2109 * @returns hash of a block2110 */2111 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2112 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2113 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2114 return blockHash;2115 }21162117 // TODO add docs2118 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2119 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2120 if (!blockHash) return null;2121 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2122 }21232124 /**2125 * Get account nonce2126 * @param address substrate address2127 * @example getNonce("5GrwvaEF5zXb26Fz...");2128 * @returns number, account's nonce2129 */2130 async getNonce(address: TSubstrateAccount): Promise<number> {2131 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2132 }2133}21342135class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2136 /**2137 * Get substrate address balance2138 * @param address substrate address2139 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2140 * @returns amount of tokens on address2141 */2142 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2143 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2144 }21452146 /**2147 * Transfer tokens to substrate address2148 * @param signer keyring of signer2149 * @param address substrate address of a recipient2150 * @param amount amount of tokens to be transfered2151 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2152 * @returns ```true``` if extrinsic success, otherwise ```false```2153 */2154 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2155 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}`*/);21562157 let transfer = {from: null, to: null, amount: 0n} as any;2158 result.result.events.forEach(({event: {data, method, section}}) => {2159 if ((section === 'balances') && (method === 'Transfer')) {2160 transfer = {2161 from: this.helper.address.normalizeSubstrate(data[0]),2162 to: this.helper.address.normalizeSubstrate(data[1]),2163 amount: BigInt(data[2]),2164 };2165 }2166 });2167 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2168 && this.helper.address.normalizeSubstrate(address) === transfer.to 2169 && BigInt(amount) === transfer.amount;2170 return isSuccess;2171 }21722173 /**2174 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2175 * @param address substrate address2176 * @returns2177 */2178 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2179 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2180 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2181 }2182}21832184class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2185 /**2186 * Get ethereum address balance2187 * @param address ethereum address2188 * @example getEthereum("0x9F0583DbB855d...")2189 * @returns amount of tokens on address2190 */2191 async getEthereum(address: TEthereumAccount): Promise<bigint> {2192 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2193 }21942195 /**2196 * Transfer tokens to address2197 * @param signer keyring of signer2198 * @param address Ethereum address of a recipient2199 * @param amount amount of tokens to be transfered2200 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2201 * @returns ```true``` if extrinsic success, otherwise ```false```2202 */2203 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2204 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22052206 let transfer = {from: null, to: null, amount: 0n} as any;2207 result.result.events.forEach(({event: {data, method, section}}) => {2208 if ((section === 'balances') && (method === 'Transfer')) {2209 transfer = {2210 from: data[0].toString(),2211 to: data[1].toString(),2212 amount: BigInt(data[2]),2213 };2214 }2215 });2216 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2217 && address === transfer.to 2218 && BigInt(amount) === transfer.amount;2219 return isSuccess;2220 }2221}22222223class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2224 subBalanceGroup: SubstrateBalanceGroup<T>;2225 ethBalanceGroup: EthereumBalanceGroup<T>;22262227 constructor(helper: T) {2228 super(helper);2229 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2230 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2231 }22322233 getCollectionCreationPrice(): bigint {2234 return 2n * this.getOneTokenNominal();2235 }2236 /**2237 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2238 * @example getOneTokenNominal()2239 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2240 */2241 getOneTokenNominal(): bigint {2242 const chainProperties = this.helper.chain.getChainProperties();2243 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2244 }22452246 /**2247 * Get substrate address balance2248 * @param address substrate address2249 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2250 * @returns amount of tokens on address2251 */2252 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2253 return this.subBalanceGroup.getSubstrate(address);2254 }22552256 /**2257 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2258 * @param address substrate address2259 * @returns2260 */2261 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2262 return this.subBalanceGroup.getSubstrateFull(address);2263 }22642265 /**2266 * Get ethereum address balance2267 * @param address ethereum address2268 * @example getEthereum("0x9F0583DbB855d...")2269 * @returns amount of tokens on address2270 */2271 async getEthereum(address: TEthereumAccount): Promise<bigint> {2272 return this.ethBalanceGroup.getEthereum(address);2273 }22742275 /**2276 * Transfer tokens to substrate address2277 * @param signer keyring of signer2278 * @param address substrate address of a recipient2279 * @param amount amount of tokens to be transfered2280 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2281 * @returns ```true``` if extrinsic success, otherwise ```false```2282 */2283 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2284 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2285 }2286}22872288class AddressGroup extends HelperGroup<ChainHelperBase> {2289 /**2290 * Normalizes the address to the specified ss58 format, by default ```42```.2291 * @param address substrate address2292 * @param ss58Format format for address conversion, by default ```42```2293 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2294 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2295 */2296 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2297 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2298 }22992300 /**2301 * Get address in the connected chain format2302 * @param address substrate address2303 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2304 * @returns address in chain format2305 */2306 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2307 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2308 }23092310 /**2311 * Get substrate mirror of an ethereum address2312 * @param ethAddress ethereum address2313 * @param toChainFormat false for normalized account2314 * @example ethToSubstrate('0x9F0583DbB855d...')2315 * @returns substrate mirror of a provided ethereum address2316 */2317 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2318 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2319 }23202321 /**2322 * Get ethereum mirror of a substrate address2323 * @param subAddress substrate account2324 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2325 * @returns ethereum mirror of a provided substrate address2326 */2327 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2328 return CrossAccountId.translateSubToEth(subAddress);2329 }23302331 paraSiblingSovereignAccount(paraid: number) {2332 // We are getting a *sibling* parachain sovereign account,2333 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2334 const siblingPrefix = '0x7369626c';23352336 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2337 const suffix = '000000000000000000000000000000000000000000000000';23382339 return siblingPrefix + encodedParaId + suffix;2340 }2341}23422343class StakingGroup extends HelperGroup<UniqueHelper> {2344 /**2345 * Stake tokens for App Promotion2346 * @param signer keyring of signer2347 * @param amountToStake amount of tokens to stake2348 * @param label extra label for log2349 * @returns2350 */2351 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2352 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2353 const _stakeResult = await this.helper.executeExtrinsic(2354 signer, 'api.tx.appPromotion.stake',2355 [amountToStake], true,2356 );2357 // TODO extract info from stakeResult2358 return true;2359 }23602361 /**2362 * Unstake tokens for App Promotion2363 * @param signer keyring of signer2364 * @param amountToUnstake amount of tokens to unstake2365 * @param label extra label for log2366 * @returns block number where balances will be unlocked2367 */2368 async unstake(signer: TSigner, label?: string): Promise<number> {2369 if(typeof label === 'undefined') label = `${signer.address}`;2370 const _unstakeResult = await this.helper.executeExtrinsic(2371 signer, 'api.tx.appPromotion.unstake',2372 [], true,2373 );2374 // TODO extract block number fron events2375 return 1;2376 }23772378 /**2379 * Get total staked amount for address2380 * @param address substrate or ethereum address2381 * @returns total staked amount2382 */2383 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2384 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2385 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2386 }23872388 /**2389 * Get total staked per block2390 * @param address substrate or ethereum address2391 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2392 */2393 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2394 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2395 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2396 return { 2397 block: block.toBigInt(),2398 amount: amount.toBigInt(),2399 };2400 });2401 }24022403 /**2404 * Get total pending unstake amount for address2405 * @param address substrate or ethereum address2406 * @returns total pending unstake amount2407 */2408 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2409 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2410 }24112412 /**2413 * Get pending unstake amount per block for address2414 * @param address substrate or ethereum address2415 * @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 block2416 */2417 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2418 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2419 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2420 return {2421 block: block.toBigInt(),2422 amount: amount.toBigInt(),2423 };2424 });2425 return result;2426 }2427}24282429class SchedulerGroup extends HelperGroup<UniqueHelper> {2430 constructor(helper: UniqueHelper) {2431 super(helper);2432 }24332434 async cancelScheduled(signer: TSigner, scheduledId: string) {2435 return this.helper.executeExtrinsic(2436 signer,2437 'api.tx.scheduler.cancelNamed',2438 [scheduledId],2439 true,2440 );2441 }24422443 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2444 return this.helper.executeExtrinsic(2445 signer,2446 'api.tx.scheduler.changeNamedPriority',2447 [scheduledId, priority],2448 true,2449 );2450 }24512452 scheduleAt<T extends UniqueHelper>(2453 scheduledId: string,2454 executionBlockNumber: number,2455 options: ISchedulerOptions = {},2456 ) {2457 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2458 }24592460 scheduleAfter<T extends UniqueHelper>(2461 scheduledId: string,2462 blocksBeforeExecution: number,2463 options: ISchedulerOptions = {},2464 ) {2465 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2466 }24672468 schedule<T extends UniqueHelper>(2469 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2470 scheduledId: string,2471 blocksNum: number,2472 options: ISchedulerOptions = {},2473 ) {2474 // eslint-disable-next-line @typescript-eslint/naming-convention2475 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2476 return this.helper.clone(ScheduledHelperType, {2477 scheduleFn,2478 scheduledId,2479 blocksNum,2480 options,2481 }) as T;2482 }2483}24842485class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2486 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2487 await this.helper.executeExtrinsic(2488 signer,2489 'api.tx.foreignAssets.registerForeignAsset',2490 [ownerAddress, location, metadata],2491 true,2492 );2493 }24942495 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2496 await this.helper.executeExtrinsic(2497 signer,2498 'api.tx.foreignAssets.updateForeignAsset',2499 [foreignAssetId, location, metadata],2500 true,2501 );2502 }2503}25042505class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2506 palletName: string;25072508 constructor(helper: T, palletName: string) {2509 super(helper);25102511 this.palletName = palletName;2512 }25132514 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2515 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2516 }2517}25182519class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2520 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2521 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2522 }25232524 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2525 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2526 }25272528 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2529 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2530 }2531}25322533class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2534 async accounts(address: string, currencyId: any) {2535 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2536 return BigInt(free);2537 }2538}25392540class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2541 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2542 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2543 }25442545 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2546 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2547 }25482549 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2550 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2551 }25522553 async account(assetId: string | number, address: string) {2554 const accountAsset = (2555 await this.helper.callRpc('api.query.assets.account', [assetId, address])2556 ).toJSON()! as any;25572558 if (accountAsset !== null) {2559 return BigInt(accountAsset['balance']);2560 } else {2561 return null;2562 }2563 }2564}25652566class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2567 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2568 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2569 }2570}25712572class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2573 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2574 const apiPrefix = 'api.tx.assetManager.';25752576 const registerTx = this.helper.constructApiCall(2577 apiPrefix + 'registerForeignAsset',2578 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2579 );25802581 const setUnitsTx = this.helper.constructApiCall(2582 apiPrefix + 'setAssetUnitsPerSecond',2583 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2584 );25852586 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2587 const encodedProposal = batchCall?.method.toHex() || '';2588 return encodedProposal;2589 }25902591 async assetTypeId(location: any) {2592 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2593 }2594}25952596class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2597 async notePreimage(signer: TSigner, encodedProposal: string) {2598 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2599 }26002601 externalProposeMajority(proposalHash: string) {2602 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2603 }26042605 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2606 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2607 }26082609 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2610 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2611 }2612}26132614class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2615 collective: string;26162617 constructor(helper: MoonbeamHelper, collective: string) {2618 super(helper);26192620 this.collective = collective;2621 }26222623 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2624 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2625 }26262627 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2628 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2629 }26302631 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2632 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2633 }26342635 async proposalCount() {2636 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2637 }2638}26392640export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2641export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26422643export class UniqueHelper extends ChainHelperBase {2644 balance: BalanceGroup<UniqueHelper>;2645 collection: CollectionGroup;2646 nft: NFTGroup;2647 rft: RFTGroup;2648 ft: FTGroup;2649 staking: StakingGroup;2650 scheduler: SchedulerGroup;2651 foreignAssets: ForeignAssetsGroup;2652 xcm: XcmGroup<UniqueHelper>;2653 xTokens: XTokensGroup<UniqueHelper>;2654 tokens: TokensGroup<UniqueHelper>;26552656 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2657 super(logger, options.helperBase ?? UniqueHelper);26582659 this.balance = new BalanceGroup(this);2660 this.collection = new CollectionGroup(this);2661 this.nft = new NFTGroup(this);2662 this.rft = new RFTGroup(this);2663 this.ft = new FTGroup(this);2664 this.staking = new StakingGroup(this);2665 this.scheduler = new SchedulerGroup(this);2666 this.foreignAssets = new ForeignAssetsGroup(this);2667 this.xcm = new XcmGroup(this, 'polkadotXcm');2668 this.xTokens = new XTokensGroup(this);2669 this.tokens = new TokensGroup(this);2670 }26712672 getSudo<T extends UniqueHelper>() {2673 // eslint-disable-next-line @typescript-eslint/naming-convention2674 const SudoHelperType = SudoHelper(this.helperBase);2675 return this.clone(SudoHelperType) as T;2676 }2677}26782679export class XcmChainHelper extends ChainHelperBase {2680 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2681 const wsProvider = new WsProvider(wsEndpoint);2682 this.api = new ApiPromise({2683 provider: wsProvider,2684 });2685 await this.api.isReadyOrError;2686 this.network = await UniqueHelper.detectNetwork(this.api);2687 }2688}26892690export class RelayHelper extends XcmChainHelper {2691 xcm: XcmGroup<RelayHelper>;26922693 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2694 super(logger, options.helperBase ?? RelayHelper);26952696 this.xcm = new XcmGroup(this, 'xcmPallet');2697 }2698}26992700export class WestmintHelper extends XcmChainHelper {2701 balance: SubstrateBalanceGroup<WestmintHelper>;2702 xcm: XcmGroup<WestmintHelper>;2703 assets: AssetsGroup<WestmintHelper>;2704 xTokens: XTokensGroup<WestmintHelper>;27052706 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2707 super(logger, options.helperBase ?? WestmintHelper);27082709 this.balance = new SubstrateBalanceGroup(this);2710 this.xcm = new XcmGroup(this, 'polkadotXcm');2711 this.assets = new AssetsGroup(this);2712 this.xTokens = new XTokensGroup(this);2713 }2714}27152716export class MoonbeamHelper extends XcmChainHelper {2717 balance: EthereumBalanceGroup<MoonbeamHelper>;2718 assetManager: MoonbeamAssetManagerGroup;2719 assets: AssetsGroup<MoonbeamHelper>;2720 xTokens: XTokensGroup<MoonbeamHelper>;2721 democracy: MoonbeamDemocracyGroup;2722 collective: {2723 council: MoonbeamCollectiveGroup,2724 techCommittee: MoonbeamCollectiveGroup,2725 };27262727 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2728 super(logger, options.helperBase ?? MoonbeamHelper);27292730 this.balance = new EthereumBalanceGroup(this);2731 this.assetManager = new MoonbeamAssetManagerGroup(this);2732 this.assets = new AssetsGroup(this);2733 this.xTokens = new XTokensGroup(this);2734 this.democracy = new MoonbeamDemocracyGroup(this);2735 this.collective = {2736 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2737 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2738 };2739 }2740}27412742export class AcalaHelper extends XcmChainHelper {2743 balance: SubstrateBalanceGroup<AcalaHelper>;2744 assetRegistry: AcalaAssetRegistryGroup;2745 xTokens: XTokensGroup<AcalaHelper>;2746 tokens: TokensGroup<AcalaHelper>;27472748 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2749 super(logger, options.helperBase ?? AcalaHelper);27502751 this.balance = new SubstrateBalanceGroup(this);2752 this.assetRegistry = new AcalaAssetRegistryGroup(this);2753 this.xTokens = new XTokensGroup(this);2754 this.tokens = new TokensGroup(this);2755 }27562757 getSudo<T extends AcalaHelper>() {2758 // eslint-disable-next-line @typescript-eslint/naming-convention2759 const SudoHelperType = SudoHelper(this.helperBase);2760 return this.clone(SudoHelperType) as T;2761 }2762}27632764// eslint-disable-next-line @typescript-eslint/naming-convention2765function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2766 return class extends Base {2767 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2768 scheduledId: string;2769 blocksNum: number;2770 options: ISchedulerOptions;27712772 constructor(...args: any[]) {2773 const logger = args[0] as ILogger;2774 const options = args[1] as {2775 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2776 scheduledId: string,2777 blocksNum: number,2778 options: ISchedulerOptions2779 };27802781 super(logger);27822783 this.scheduleFn = options.scheduleFn;2784 this.scheduledId = options.scheduledId;2785 this.blocksNum = options.blocksNum;2786 this.options = options.options;2787 }27882789 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2790 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2791 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27922793 return super.executeExtrinsic(2794 sender,2795 extrinsic,2796 [2797 this.scheduledId,2798 this.blocksNum,2799 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2800 this.options.priority ?? null,2801 {Value: scheduledTx},2802 ],2803 expectSuccess,2804 );2805 }2806 };2807}28082809// eslint-disable-next-line @typescript-eslint/naming-convention2810function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2811 return class extends Base {2812 constructor(...args: any[]) {2813 super(...args);2814 }28152816 executeExtrinsic (2817 sender: IKeyringPair,2818 extrinsic: string,2819 params: any[],2820 expectSuccess?: boolean,2821 ): Promise<ITransactionResult> {2822 const call = this.constructApiCall(extrinsic, params);28232824 return super.executeExtrinsic(2825 sender,2826 'api.tx.sudo.sudo',2827 [call],2828 expectSuccess,2829 );2830 }2831 };2832}28332834export class UniqueBaseCollection {2835 helper: UniqueHelper;2836 collectionId: number;28372838 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2839 this.collectionId = collectionId;2840 this.helper = uniqueHelper;2841 }28422843 async getData() {2844 return await this.helper.collection.getData(this.collectionId);2845 }28462847 async getLastTokenId() {2848 return await this.helper.collection.getLastTokenId(this.collectionId);2849 }28502851 async doesTokenExist(tokenId: number) {2852 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2853 }28542855 async getAdmins() {2856 return await this.helper.collection.getAdmins(this.collectionId);2857 }28582859 async getAllowList() {2860 return await this.helper.collection.getAllowList(this.collectionId);2861 }28622863 async getEffectiveLimits() {2864 return await this.helper.collection.getEffectiveLimits(this.collectionId);2865 }28662867 async getProperties(propertyKeys?: string[] | null) {2868 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2869 }28702871 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2872 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2873 }28742875 async getOptions() {2876 return await this.helper.collection.getCollectionOptions(this.collectionId);2877 }28782879 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2880 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2881 }28822883 async confirmSponsorship(signer: TSigner) {2884 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2885 }28862887 async removeSponsor(signer: TSigner) {2888 return await this.helper.collection.removeSponsor(signer, this.collectionId);2889 }28902891 async setLimits(signer: TSigner, limits: ICollectionLimits) {2892 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2893 }28942895 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2896 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2897 }28982899 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2900 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2901 }29022903 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2904 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2905 }29062907 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2908 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2909 }29102911 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2912 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2913 }29142915 async setProperties(signer: TSigner, properties: IProperty[]) {2916 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2917 }29182919 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2920 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2921 }29222923 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2924 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2925 }29262927 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2928 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2929 }29302931 async disableNesting(signer: TSigner) {2932 return await this.helper.collection.disableNesting(signer, this.collectionId);2933 }29342935 async burn(signer: TSigner) {2936 return await this.helper.collection.burn(signer, this.collectionId);2937 }29382939 scheduleAt<T extends UniqueHelper>(2940 scheduledId: string,2941 executionBlockNumber: number,2942 options: ISchedulerOptions = {},2943 ) {2944 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2945 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2946 }29472948 scheduleAfter<T extends UniqueHelper>(2949 scheduledId: string,2950 blocksBeforeExecution: number,2951 options: ISchedulerOptions = {},2952 ) {2953 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2954 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2955 }29562957 getSudo<T extends UniqueHelper>() {2958 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2959 }2960}296129622963export class UniqueNFTCollection extends UniqueBaseCollection {2964 getTokenObject(tokenId: number) {2965 return new UniqueNFToken(tokenId, this);2966 }29672968 async getTokensByAddress(addressObj: ICrossAccountId) {2969 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2970 }29712972 async getToken(tokenId: number, blockHashAt?: string) {2973 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2974 }29752976 async getTokenOwner(tokenId: number, blockHashAt?: string) {2977 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2978 }29792980 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2981 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2982 }29832984 async getTokenChildren(tokenId: number, blockHashAt?: string) {2985 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2986 }29872988 async getPropertyPermissions(propertyKeys: string[] | null = null) {2989 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2990 }29912992 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2993 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2994 }29952996 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2997 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2998 }29993000 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3001 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3002 }30033004 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3005 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3006 }30073008 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3009 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3010 }30113012 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3013 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3014 }30153016 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3017 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3018 }30193020 async burnToken(signer: TSigner, tokenId: number) {3021 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3022 }30233024 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3025 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3026 }30273028 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3029 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3030 }30313032 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3033 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3034 }30353036 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3037 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3038 }30393040 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3041 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3042 }30433044 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3045 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);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 UniqueNFTCollection(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 UniqueNFTCollection(this.collectionId, scheduledHelper);3064 }30653066 getSudo<T extends UniqueHelper>() {3067 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3068 }3069}307030713072export class UniqueRFTCollection extends UniqueBaseCollection {3073 getTokenObject(tokenId: number) {3074 return new UniqueRFToken(tokenId, this);3075 }30763077 async getToken(tokenId: number, blockHashAt?: string) {3078 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3079 }30803081 async getTokensByAddress(addressObj: ICrossAccountId) {3082 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3083 }30843085 async getTop10TokenOwners(tokenId: number) {3086 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3087 }30883089 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3090 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3091 }30923093 async getTokenTotalPieces(tokenId: number) {3094 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3095 }30963097 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3098 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3099 }31003101 async getPropertyPermissions(propertyKeys: string[] | null = null) {3102 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3103 }31043105 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3106 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3107 }31083109 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3110 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3111 }31123113 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3114 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3115 }31163117 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3118 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3119 }31203121 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3122 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3123 }31243125 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3126 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3127 }31283129 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3130 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3131 }31323133 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3134 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3135 }31363137 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3138 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3139 }31403141 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3142 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3143 }31443145 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3146 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3147 }31483149 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3150 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3151 }31523153 scheduleAt<T extends UniqueHelper>(3154 scheduledId: string,3155 executionBlockNumber: number,3156 options: ISchedulerOptions = {},3157 ) {3158 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3159 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3160 }31613162 scheduleAfter<T extends UniqueHelper>(3163 scheduledId: string,3164 blocksBeforeExecution: number,3165 options: ISchedulerOptions = {},3166 ) {3167 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3168 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3169 }31703171 getSudo<T extends UniqueHelper>() {3172 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3173 }3174}317531763177export class UniqueFTCollection extends UniqueBaseCollection {3178 async getBalance(addressObj: ICrossAccountId) {3179 return await this.helper.ft.getBalance(this.collectionId, addressObj);3180 }31813182 async getTotalPieces() {3183 return await this.helper.ft.getTotalPieces(this.collectionId);3184 }31853186 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3187 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3188 }31893190 async getTop10Owners() {3191 return await this.helper.ft.getTop10Owners(this.collectionId);3192 }31933194 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3195 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3196 }31973198 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3199 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3200 }32013202 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3203 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3204 }32053206 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3207 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3208 }32093210 async burnTokens(signer: TSigner, amount=1n) {3211 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3212 }32133214 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3215 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3216 }32173218 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3219 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3220 }32213222 scheduleAt<T extends UniqueHelper>(3223 scheduledId: string,3224 executionBlockNumber: number,3225 options: ISchedulerOptions = {},3226 ) {3227 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3228 return new UniqueFTCollection(this.collectionId, scheduledHelper);3229 }32303231 scheduleAfter<T extends UniqueHelper>(3232 scheduledId: string,3233 blocksBeforeExecution: number,3234 options: ISchedulerOptions = {},3235 ) {3236 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3237 return new UniqueFTCollection(this.collectionId, scheduledHelper);3238 }32393240 getSudo<T extends UniqueHelper>() {3241 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3242 }3243}324432453246export class UniqueBaseToken {3247 collection: UniqueNFTCollection | UniqueRFTCollection;3248 collectionId: number;3249 tokenId: number;32503251 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3252 this.collection = collection;3253 this.collectionId = collection.collectionId;3254 this.tokenId = tokenId;3255 }32563257 async getNextSponsored(addressObj: ICrossAccountId) {3258 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3259 }32603261 async getProperties(propertyKeys?: string[] | null) {3262 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3263 }32643265 async setProperties(signer: TSigner, properties: IProperty[]) {3266 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3267 }32683269 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3270 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3271 }32723273 async doesExist() {3274 return await this.collection.doesTokenExist(this.tokenId);3275 }32763277 nestingAccount() {3278 return this.collection.helper.util.getTokenAccount(this);3279 }32803281 scheduleAt<T extends UniqueHelper>(3282 scheduledId: string,3283 executionBlockNumber: number,3284 options: ISchedulerOptions = {},3285 ) {3286 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3287 return new UniqueBaseToken(this.tokenId, scheduledCollection);3288 }32893290 scheduleAfter<T extends UniqueHelper>(3291 scheduledId: string,3292 blocksBeforeExecution: number,3293 options: ISchedulerOptions = {},3294 ) {3295 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3296 return new UniqueBaseToken(this.tokenId, scheduledCollection);3297 }32983299 getSudo<T extends UniqueHelper>() {3300 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3301 }3302}330333043305export class UniqueNFToken extends UniqueBaseToken {3306 collection: UniqueNFTCollection;33073308 constructor(tokenId: number, collection: UniqueNFTCollection) {3309 super(tokenId, collection);3310 this.collection = collection;3311 }33123313 async getData(blockHashAt?: string) {3314 return await this.collection.getToken(this.tokenId, blockHashAt);3315 }33163317 async getOwner(blockHashAt?: string) {3318 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3319 }33203321 async getTopmostOwner(blockHashAt?: string) {3322 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3323 }33243325 async getChildren(blockHashAt?: string) {3326 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3327 }33283329 async nest(signer: TSigner, toTokenObj: IToken) {3330 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3331 }33323333 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3334 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3335 }33363337 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3338 return await this.collection.transferToken(signer, this.tokenId, addressObj);3339 }33403341 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3342 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3343 }33443345 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3346 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3347 }33483349 async isApproved(toAddressObj: ICrossAccountId) {3350 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3351 }33523353 async burn(signer: TSigner) {3354 return await this.collection.burnToken(signer, this.tokenId);3355 }33563357 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3358 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3359 }33603361 scheduleAt<T extends UniqueHelper>(3362 scheduledId: string,3363 executionBlockNumber: number,3364 options: ISchedulerOptions = {},3365 ) {3366 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3367 return new UniqueNFToken(this.tokenId, scheduledCollection);3368 }33693370 scheduleAfter<T extends UniqueHelper>(3371 scheduledId: string,3372 blocksBeforeExecution: number,3373 options: ISchedulerOptions = {},3374 ) {3375 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3376 return new UniqueNFToken(this.tokenId, scheduledCollection);3377 }33783379 getSudo<T extends UniqueHelper>() {3380 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3381 }3382}33833384export class UniqueRFToken extends UniqueBaseToken {3385 collection: UniqueRFTCollection;33863387 constructor(tokenId: number, collection: UniqueRFTCollection) {3388 super(tokenId, collection);3389 this.collection = collection;3390 }33913392 async getData(blockHashAt?: string) {3393 return await this.collection.getToken(this.tokenId, blockHashAt);3394 }33953396 async getTop10Owners() {3397 return await this.collection.getTop10TokenOwners(this.tokenId);3398 }33993400 async getBalance(addressObj: ICrossAccountId) {3401 return await this.collection.getTokenBalance(this.tokenId, addressObj);3402 }34033404 async getTotalPieces() {3405 return await this.collection.getTokenTotalPieces(this.tokenId);3406 }34073408 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3409 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3410 }34113412 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3413 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3414 }34153416 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3417 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3418 }34193420 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3421 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3422 }34233424 async repartition(signer: TSigner, amount: bigint) {3425 return await this.collection.repartitionToken(signer, this.tokenId, amount);3426 }34273428 async burn(signer: TSigner, amount=1n) {3429 return await this.collection.burnToken(signer, this.tokenId, amount);3430 }34313432 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3433 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3434 }34353436 scheduleAt<T extends UniqueHelper>(3437 scheduledId: string,3438 executionBlockNumber: number,3439 options: ISchedulerOptions = {},3440 ) {3441 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3442 return new UniqueRFToken(this.tokenId, scheduledCollection);3443 }34443445 scheduleAfter<T extends UniqueHelper>(3446 scheduledId: string,3447 blocksBeforeExecution: number,3448 options: ISchedulerOptions = {},3449 ) {3450 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3451 return new UniqueRFToken(this.tokenId, scheduledCollection);3452 }34533454 getSudo<T extends UniqueHelper>() {3455 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3456 }3457}