difftreelog
Merge branch 'develop' into tests/generalization
in: master
41 files changed
.docker/Dockerfile-chain-devdiffbeforeafterboth--- a/.docker/Dockerfile-chain-dev
+++ b/.docker/Dockerfile-chain-dev
@@ -1,4 +1,4 @@
-FROM ubuntu:20.04
+FROM uniquenetwork/services:latest
ARG RUST_TOOLCHAIN
ARG NETWORK
@@ -10,10 +10,6 @@
ENV PATH="/cargo-home/bin:$PATH"
RUN echo "$NETWORK\n" && echo "$RUST_TOOLCHAIN\n"
-
-RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake protobuf-compiler
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install $RUST_TOOLCHAIN && \
.docker/Dockerfile-chain-dev-unitdiffbeforeafterboth--- a/.docker/Dockerfile-chain-dev-unit
+++ b/.docker/Dockerfile-chain-dev-unit
@@ -1,14 +1,8 @@
-FROM ubuntu:20.04
+FROM uniquenetwork/services:latest
ENV DEBIAN_FRONTEND=noninteractive
-ENV TZ=Etc/UTC
-
-RUN apt-get update && apt-get install -y git curl libssl-dev llvm pkg-config libclang-dev clang git make cmake protobuf-compiler
-
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
ARG RUST_TOOLCHAIN
ARG NETWORK
.docker/Dockerfile-parachaindiffbeforeafterboth--- a/.docker/Dockerfile-parachain
+++ b/.docker/Dockerfile-parachain
@@ -2,24 +2,13 @@
FROM uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} as polkadot
# ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
-
+FROM uniquenetwork/services:latest as rust-builder
ARG RUST_TOOLCHAIN=
ENV RUST_TOOLCHAIN $RUST_TOOLCHAIN
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
- apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
- apt-get clean && \
- rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
-
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install $RUST_TOOLCHAIN && \
rustup default $RUST_TOOLCHAIN && \
.docker/Dockerfile-parachain-node-onlydiffbeforeafterboth--- a/.docker/Dockerfile-parachain-node-only
+++ b/.docker/Dockerfile-parachain-node-only
@@ -2,24 +2,13 @@
FROM uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} as polkadot
# ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
+FROM uniquenetwork/services:latest as rust-builder
ARG RUST_TOOLCHAIN=
-
ENV RUST_TOOLCHAIN $RUST_TOOLCHAIN
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
- apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
- apt-get clean && \
- rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
-
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install $RUST_TOOLCHAIN && \
rustup default $RUST_TOOLCHAIN && \
.docker/Dockerfile-parachain-upgradediffbeforeafterboth--- a/.docker/Dockerfile-parachain-upgrade
+++ b/.docker/Dockerfile-parachain-upgrade
@@ -2,8 +2,7 @@
FROM uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} as polkadot
# ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
+FROM uniquenetwork/services:latest as rust-builder
ARG RUST_TOOLCHAIN=
@@ -11,15 +10,6 @@
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
- apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
- apt-get clean && \
- rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
-
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install $RUST_TOOLCHAIN && \
rustup default $RUST_TOOLCHAIN && \
.docker/Dockerfile-parachain-upgrade-datadiffbeforeafterboth--- a/.docker/Dockerfile-parachain-upgrade-data
+++ b/.docker/Dockerfile-parachain-upgrade-data
@@ -2,23 +2,13 @@
FROM uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} as polkadot
# ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
-
+FROM uniquenetwork/services:latest as rust-builder
ARG RUST_TOOLCHAIN=
ENV RUST_TOOLCHAIN $RUST_TOOLCHAIN
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
- apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
- apt-get clean && \
- rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install $RUST_TOOLCHAIN && \
.docker/Dockerfile-testnet.j2diffbeforeafterboth--- a/.docker/Dockerfile-testnet.j2
+++ b/.docker/Dockerfile-testnet.j2
@@ -1,18 +1,11 @@
# ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
+FROM uniquenetwork/services:latest as rust-builder
+ARG RUST_TOOLCHAIN=
+ENV RUST_TOOLCHAIN $RUST_TOOLCHAIN
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
- apt-get install -y curl cmake pkg-config libssl-dev git clang llvm libudev-dev protobuf-compiler && \
- apt-get clean && \
- rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install {{ RUST_TOOLCHAIN }} && \
.docker/Dockerfile-try-runtimediffbeforeafterboth--- a/.docker/Dockerfile-try-runtime
+++ b/.docker/Dockerfile-try-runtime
@@ -1,6 +1,5 @@
# ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
+FROM uniquenetwork/services:latest as rust-builder
ARG RUST_TOOLCHAIN
@@ -8,15 +7,6 @@
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-
-RUN apt-get update && \
- apt-get install -y curl cmake pkg-config libssl-dev git clang protobuf-compiler && \
- apt-get clean && \
- rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install $RUST_TOOLCHAIN && \
.docker/Dockerfile-xcm.j2diffbeforeafterboth--- a/.docker/Dockerfile-xcm.j2
+++ b/.docker/Dockerfile-xcm.j2
@@ -1,18 +1,8 @@
# ===== Rust builder =====
-FROM ubuntu:20.04 as rust-builder
-LABEL maintainer="Unique.Network"
-
+FROM uniquenetwork/services:latest as rust-builder
ENV CARGO_HOME="/cargo-home"
ENV PATH="/cargo-home/bin:$PATH"
ENV TZ=UTC
-RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
-
-RUN apt-get update && \
- apt-get install -y curl cmake pkg-config libssl-dev git clang llvm libudev-dev protobuf-compiler && \
- apt-get clean && \
- rm -r /var/lib/apt/lists/*
-
-RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
RUN rustup toolchain uninstall $(rustup toolchain list) && \
rustup toolchain install {{ RUST_TOOLCHAIN }} && \
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2340,7 +2340,7 @@
[[package]]
name = "evm-coder-procedural"
-version = "0.2.2"
+version = "0.2.3"
dependencies = [
"Inflector",
"hex",
@@ -2467,7 +2467,7 @@
[[package]]
name = "fc-consensus"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"async-trait",
"fc-db",
@@ -2486,7 +2486,7 @@
[[package]]
name = "fc-db"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"fp-storage",
"kvdb-rocksdb",
@@ -2505,7 +2505,7 @@
[[package]]
name = "fc-mapping-sync"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"fc-db",
"fp-consensus",
@@ -2522,7 +2522,7 @@
[[package]]
name = "fc-rpc"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -2565,7 +2565,7 @@
[[package]]
name = "fc-rpc-core"
version = "1.1.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -2730,7 +2730,7 @@
[[package]]
name = "fp-consensus"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"ethereum 0.14.0",
"parity-scale-codec 3.2.1",
@@ -2742,7 +2742,7 @@
[[package]]
name = "fp-ethereum"
version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -2757,7 +2757,7 @@
[[package]]
name = "fp-evm"
version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"evm",
"frame-support",
@@ -2771,7 +2771,7 @@
[[package]]
name = "fp-evm-mapping"
version = "0.1.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"frame-support",
"sp-core",
@@ -2780,7 +2780,7 @@
[[package]]
name = "fp-rpc"
version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -2797,7 +2797,7 @@
[[package]]
name = "fp-self-contained"
version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"ethereum 0.14.0",
"frame-support",
@@ -2810,7 +2810,7 @@
[[package]]
name = "fp-storage"
version = "2.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"parity-scale-codec 3.2.1",
"serde",
@@ -5687,7 +5687,7 @@
[[package]]
name = "pallet-base-fee"
version = "1.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"fp-evm",
"frame-support",
@@ -5952,7 +5952,7 @@
[[package]]
name = "pallet-ethereum"
version = "4.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"ethereum 0.14.0",
"ethereum-types 0.14.1",
@@ -5980,7 +5980,7 @@
[[package]]
name = "pallet-evm"
version = "6.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"environmental",
"evm",
@@ -6066,7 +6066,7 @@
[[package]]
name = "pallet-evm-precompile-simple"
version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#ef8d2809ed05da0664e9b43cb87436451295b634"
dependencies = [
"fp-evm",
"ripemd",
crates/evm-coder/procedural/Cargo.tomldiffbeforeafterboth--- a/crates/evm-coder/procedural/Cargo.toml
+++ b/crates/evm-coder/procedural/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "evm-coder-procedural"
-version = "0.2.2"
+version = "0.2.3"
license = "GPLv3"
edition = "2021"
crates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -811,6 +811,13 @@
let list = generics_list(gen);
quote! { <#list> }
}
+fn generics_stub(gen: &Generics) -> proc_macro2::TokenStream {
+ if gen.params.is_empty() {
+ return quote! {};
+ }
+ let params = (0..gen.params.len()).map(|_| quote! {()});
+ quote! {<#(#params,)*>}
+}
fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {
let list = generics_list(gen);
if gen.params.len() == 1 {
@@ -866,6 +873,7 @@
let generics = self.generics;
let gen_ref = generics_reference(&generics);
let gen_data = generics_data(&generics);
+ let gen_stub = generics_stub(&generics);
let gen_where = &generics.where_clause;
let call_sub = self
@@ -936,6 +944,12 @@
let solidity_events_idents = self.info.events.0.iter().map(|is| is.name.clone());
let docs = &self.docs;
+ let expect_selector = self.info.expect_selector.map(|s| {
+ quote! {
+ const _: () = assert!(#s == u32::from_be_bytes(<#call_name #gen_stub>::interface_id()), "selector mismatch, review contained function selectors");
+ }
+ });
+
quote! {
#(
const _: ::core::marker::PhantomData<#solidity_events_idents> = ::core::marker::PhantomData;
@@ -952,12 +966,15 @@
#call_sub,
)*
}
+
+ #expect_selector
+
impl #gen_ref #call_name #gen_ref {
#(
#consts
)*
/// Return this call ERC165 selector
- pub fn interface_id() -> ::evm_coder::types::bytes4 {
+ pub const fn interface_id() -> ::evm_coder::types::bytes4 {
let mut interface_id = 0;
#(#interface_id)*
#(#inline_interface_id)*
crates/evm-coder/procedural/src/to_log.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/to_log.rs
+++ b/crates/evm-coder/procedural/src/to_log.rs
@@ -16,7 +16,6 @@
use inflector::cases;
use syn::{Data, DeriveInput, Field, Fields, Ident, Variant, spanned::Spanned};
-use std::fmt::Write;
use quote::quote;
use crate::{parse_ident_from_path, parse_ident_from_type, snake_ident_to_screaming};
@@ -61,13 +60,13 @@
name: Ident,
name_screaming: Ident,
fields: Vec<EventField>,
- selector: [u8; 32],
- selector_str: String,
+ selector: proc_macro2::TokenStream,
}
impl Event {
fn try_from(variant: &Variant) -> syn::Result<Self> {
let name = &variant.ident;
+ let name_lit = proc_macro2::Literal::string(name.to_string().as_str());
let name_screaming = snake_ident_to_screaming(name);
let named = match &variant.fields {
@@ -89,22 +88,40 @@
"events can have at most 4 indexed fields (1 indexed field is reserved for event signature)"
));
}
- let mut selector_str = format!("{}(", name);
- for (i, arg) in fields.iter().enumerate() {
- if i != 0 {
- write!(selector_str, ",").unwrap();
+
+ let args = fields.iter().map(|f| {
+ let ty = &f.ty;
+ quote! {nameof(<#ty as ::evm_coder::abi::AbiType>::SIGNATURE) fixed(",")}
+ });
+ // Remove trailing comma
+ let shift = (!fields.is_empty()).then(|| quote! {shift_left(1)});
+
+ let signature = quote! { ::evm_coder::make_signature!(new fixed(#name_lit) fixed("(") #(#args)* #shift fixed(")")) };
+ let selector = quote! {
+ {
+ let signature = #signature;
+ let mut sum = ::evm_coder::sha3_const::Keccak256::new();
+ let mut pos = 0;
+ while pos < signature.len {
+ sum = sum.update(&[signature.data[pos]; 1]);
+ pos += 1;
+ }
+ let a = sum.finalize();
+ let mut selector_bytes = [0; 32];
+ let mut i = 0;
+ while i != 32 {
+ selector_bytes[i] = a[i];
+ i += 1;
+ }
+ selector_bytes
}
- write!(selector_str, "{}", arg.ty).unwrap();
- }
- selector_str.push(')');
- let selector = crate::event_selector_str(&selector_str);
+ };
Ok(Self {
name: name.to_owned(),
name_screaming,
fields,
selector,
- selector_str,
})
}
@@ -133,14 +150,10 @@
fn expand_consts(&self) -> proc_macro2::TokenStream {
let name_screaming = &self.name_screaming;
- let selector_str = &self.selector_str;
let selector = &self.selector;
quote! {
- #[doc = #selector_str]
- const #name_screaming: [u8; 32] = [#(
- #selector,
- )*];
+ const #name_screaming: [u8; 32] = #selector;
}
}
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -143,7 +143,7 @@
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
-#[cfg(feature = "quartz-runtime")]
+#[cfg(not(feature = "unique-runtime"))]
macro_rules! testnet_genesis {
(
$runtime:path,
@@ -207,7 +207,7 @@
}};
}
-#[cfg(not(feature = "quartz-runtime"))]
+#[cfg(feature = "unique-runtime")]
macro_rules! testnet_genesis {
(
$runtime:path,
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -176,7 +176,7 @@
key: property_key(p as usize),
value: property_value(),
}).collect::<Vec<_>>();
- }: {<Pallet<T>>::set_collection_properties(&collection, &owner, props)?}
+ }: {<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?}
delete_collection_properties {
let b in 0..MAX_PROPERTIES_PER_ITEM;
@@ -188,7 +188,7 @@
key: property_key(p as usize),
value: property_value(),
}).collect::<Vec<_>>();
- <Pallet<T>>::set_collection_properties(&collection, &owner, props)?;
+ <Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;
let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();
- }: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete)?}
+ }: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?}
}
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -125,7 +125,7 @@
.map(eth::Property::try_into)
.collect::<Result<Vec<_>>>()?;
- <Pallet<T>>::set_collection_properties(self, &caller, properties)
+ <Pallet<T>>::set_collection_properties(self, &caller, properties.into_iter())
.map_err(dispatch_to_evm::<T>)
}
@@ -158,7 +158,8 @@
})
.collect::<Result<Vec<_>>>()?;
- <Pallet<T>>::delete_collection_properties(self, &caller, keys).map_err(dispatch_to_evm::<T>)
+ <Pallet<T>>::delete_collection_properties(self, &caller, keys.into_iter())
+ .map_err(dispatch_to_evm::<T>)
}
/// Get collection property.
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -390,8 +390,10 @@
Ok(())
}
- /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.
- pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {
+ /// Returns **true** if
+ /// * the `user`is a collection owner or admin
+ /// * the collection limits allow the owner/admins to transfer/burn any collection token
+ pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {
self.limits.owner_can_transfer() && self.is_owner_or_admin(user)
}
@@ -1198,6 +1200,58 @@
Ok(())
}
+ /// This function sets or removes a collection properties according to
+ /// `properties_updates` contents:
+ /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
+ /// * removes a property under the <key> if the value is `None` `(<key>, None)`.
+ ///
+ /// This function fires an event for each property change.
+ /// In case of an error, all the changes (including the events) will be reverted
+ /// since the function is transactional.
+ #[transactional]
+ fn modify_collection_properties(
+ collection: &CollectionHandle<T>,
+ sender: &T::CrossAccountId,
+ properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+ ) -> DispatchResult {
+ collection.check_is_owner_or_admin(sender)?;
+
+ let mut stored_properties = <CollectionProperties<T>>::get(collection.id);
+
+ for (key, value) in properties_updates {
+ match value {
+ Some(value) => {
+ stored_properties
+ .try_set(key.clone(), value)
+ .map_err(<Error<T>>::from)?;
+
+ Self::deposit_event(Event::CollectionPropertySet(collection.id, key));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(collection.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+ }
+ None => {
+ stored_properties.remove(&key).map_err(<Error<T>>::from)?;
+
+ Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));
+ <PalletEvm<T>>::deposit_log(
+ erc::CollectionHelpersEvents::CollectionChanged {
+ collection_id: eth::collection_id_to_address(collection.id),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+ }
+ }
+ }
+
+ <CollectionProperties<T>>::set(collection.id, stored_properties);
+
+ Ok(())
+ }
+
/// Set collection property.
///
/// * `collection` - Collection handler.
@@ -1208,23 +1262,7 @@
sender: &T::CrossAccountId,
property: Property,
) -> DispatchResult {
- collection.check_is_owner_or_admin(sender)?;
-
- CollectionProperties::<T>::try_mutate(collection.id, |properties| {
- let property = property.clone();
- properties.try_set(property.key, property.value)
- })
- .map_err(<Error<T>>::from)?;
-
- Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));
- <PalletEvm<T>>::deposit_log(
- erc::CollectionHelpersEvents::CollectionChanged {
- collection_id: eth::collection_id_to_address(collection.id),
- }
- .to_log(T::ContractAddress::get()),
- );
-
- Ok(())
+ Self::set_collection_properties(collection, sender, [property].into_iter())
}
/// Set a scoped collection property, where the scope is a special prefix
@@ -1270,17 +1308,16 @@
/// * `collection` - Collection handler.
/// * `sender` - The owner or administrator of the collection.
/// * `properties` - The properties to set.
- #[transactional]
pub fn set_collection_properties(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
- properties: Vec<Property>,
+ properties: impl Iterator<Item = Property>,
) -> DispatchResult {
- for property in properties {
- Self::set_collection_property(collection, sender, property)?;
- }
-
- Ok(())
+ Self::modify_collection_properties(
+ collection,
+ sender,
+ properties.map(|property| (property.key, Some(property.value))),
+ )
}
/// Delete collection property.
@@ -1293,25 +1330,7 @@
sender: &T::CrossAccountId,
property_key: PropertyKey,
) -> DispatchResult {
- collection.check_is_owner_or_admin(sender)?;
-
- CollectionProperties::<T>::try_mutate(collection.id, |properties| {
- properties.remove(&property_key)
- })
- .map_err(<Error<T>>::from)?;
-
- Self::deposit_event(Event::CollectionPropertyDeleted(
- collection.id,
- property_key,
- ));
- <PalletEvm<T>>::deposit_log(
- erc::CollectionHelpersEvents::CollectionChanged {
- collection_id: eth::collection_id_to_address(collection.id),
- }
- .to_log(T::ContractAddress::get()),
- );
-
- Ok(())
+ Self::delete_collection_properties(collection, sender, [property_key].into_iter())
}
/// Delete collection properties.
@@ -1319,17 +1338,12 @@
/// * `collection` - Collection handler.
/// * `sender` - The owner or administrator of the collection.
/// * `properties` - The properties to delete.
- #[transactional]
pub fn delete_collection_properties(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
- property_keys: Vec<PropertyKey>,
+ property_keys: impl Iterator<Item = PropertyKey>,
) -> DispatchResult {
- for key in property_keys {
- Self::delete_collection_property(collection, sender, key)?;
- }
-
- Ok(())
+ Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))
}
/// Set collection propetry permission without any checks.
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -266,7 +266,7 @@
sender: &T::CrossAccountId,
properties: Vec<Property>,
) -> DispatchResult {
- <PalletCommon<T>>::set_collection_properties(collection, sender, properties)
+ <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())
}
/// Delete properties of the collection, associated with the provided keys.
@@ -275,7 +275,11 @@
sender: &T::CrossAccountId,
property_keys: Vec<PropertyKey>,
) -> DispatchResult {
- <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)
+ <PalletCommon<T>>::delete_collection_properties(
+ collection,
+ sender,
+ property_keys.into_iter(),
+ )
}
/// Checks if collection has tokens. Return `true` if it has.
@@ -673,8 +677,14 @@
// `from`, `to` checked in [`transfer`]
collection.check_allowlist(spender)?;
}
+
+ if collection.ignores_token_restrictions(spender) {
+ return Ok(Self::compute_allowance_decrease(
+ collection, from, spender, amount,
+ ));
+ }
+
if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
- // TODO: should collection owner be allowed to perform this transfer?
ensure!(
<PalletStructure<T>>::check_indirectly_owned(
spender.clone(),
@@ -687,17 +697,24 @@
);
return Ok(None);
}
- let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);
- if allowance.is_none() {
- ensure!(
- collection.ignores_allowance(spender),
- <CommonError<T>>::ApprovedValueTooLow
- );
- }
+ let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);
+ ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);
+
Ok(allowance)
}
+ /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.
+ /// Otherwise, it returns `None`.
+ fn compute_allowance_decrease(
+ collection: &FungibleHandle<T>,
+ from: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
+ amount: u128,
+ ) -> Option<u128> {
+ <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)
+ }
+
/// Transfer fungible tokens from one account to another.
/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.
/// The owner should set allowance for the spender to transfer pieces.
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -524,11 +524,6 @@
Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))
}
-
- /// @notice Returns collection helper contract address
- fn collection_helper_address(&self) -> Result<address> {
- Ok(T::ContractAddress::get())
- }
}
/// @title ERC721 Token that can be irreversibly burned (destroyed).
@@ -1058,6 +1053,11 @@
Ok(token_id.into())
}
+
+ /// @notice Returns collection helper contract address
+ fn collection_helper_address(&self) -> Result<address> {
+ Ok(T::ContractAddress::get())
+ }
}
#[solidity_interface(
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -577,20 +577,29 @@
})
}
- /// Batch operation to add, edit or remove properties for the token
- ///
- /// All affected properties should have mutable permission and sender should have
- /// permission to edit those properties.
+ /// A batch operation to add, edit or remove properties for a token.
+ /// It sets or removes a token's properties according to
+ /// `properties_updates` contents:
+ /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
+ /// * removes a property under the <key> if the value is `None` `(<key>, None)`.
///
- /// - `nesting_budget`: Limit for searching parents in depth to check ownership.
+ /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
/// - `is_token_create`: Indicates that method is called during token initialization.
/// Allows to bypass ownership check.
+ ///
+ /// All affected properties should have `mutable` permission
+ /// to be **deleted** or to be **set more than once**,
+ /// and the sender should have permission to edit those properties.
+ ///
+ /// This function fires an event for each property change.
+ /// In case of an error, all the changes (including the events) will be reverted
+ /// since the function is transactional.
#[transactional]
fn modify_token_properties(
collection: &NonfungibleHandle<T>,
sender: &T::CrossAccountId,
token_id: TokenId,
- properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+ properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
is_token_create: bool,
nesting_budget: &dyn Budget,
) -> DispatchResult {
@@ -614,15 +623,16 @@
})
};
- for (key, value) in properties {
- let permission = <PalletCommon<T>>::property_permissions(collection.id)
+ let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
+ let permissions = <PalletCommon<T>>::property_permissions(collection.id);
+
+ for (key, value) in properties_updates {
+ let permission = permissions
.get(&key)
.cloned()
.unwrap_or_else(PropertyPermission::none);
- let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))
- .get(&key)
- .is_some();
+ let is_property_exists = stored_properties.get(&key).is_some();
match permission {
PropertyPermission { mutable: false, .. } if is_property_exists => {
@@ -649,10 +659,9 @@
match value {
Some(value) => {
- <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
- properties.try_set(key.clone(), value)
- })
- .map_err(<CommonError<T>>::from)?;
+ stored_properties
+ .try_set(key.clone(), value)
+ .map_err(<CommonError<T>>::from)?;
<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(
collection.id,
@@ -661,10 +670,9 @@
));
}
None => {
- <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
- properties.remove(&key)
- })
- .map_err(<CommonError<T>>::from)?;
+ stored_properties
+ .remove(&key)
+ .map_err(<CommonError<T>>::from)?;
<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
collection.id,
@@ -683,6 +691,8 @@
);
}
+ <TokenProperties<T>>::set((collection.id, token_id), stored_properties);
+
Ok(())
}
@@ -784,7 +794,7 @@
sender: &T::CrossAccountId,
properties: Vec<Property>,
) -> DispatchResult {
- <PalletCommon<T>>::set_collection_properties(collection, sender, properties)
+ <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())
}
/// Remove properties from the collection
@@ -793,7 +803,11 @@
sender: &T::CrossAccountId,
property_keys: Vec<PropertyKey>,
) -> DispatchResult {
- <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)
+ <PalletCommon<T>>::delete_collection_properties(
+ collection,
+ sender,
+ property_keys.into_iter(),
+ )
}
/// Set property permissions for the token.
@@ -1232,7 +1246,7 @@
collection.check_allowlist(spender)?;
}
- if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {
+ if collection.ignores_token_restrictions(spender) {
return Ok(());
}
@@ -1255,11 +1269,8 @@
if <CollectionAllowance<T>>::get((collection.id, from, spender)) {
return Ok(());
}
- ensure!(
- collection.ignores_allowance(spender),
- <CommonError<T>>::ApprovedValueTooLow
- );
- Ok(())
+
+ Err(<CommonError<T>>::ApprovedValueTooLow.into())
}
/// Transfer NFT token from one account to another.
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
@@ -785,7 +785,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x0e48fdb4
+/// @dev the ERC-165 identifier for this interface is 0x16de3152
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,
@@ -986,6 +986,15 @@
dummy = 0;
return 0;
}
+
+ /// @notice Returns collection helper contract address
+ /// @dev EVM selector for this function is: 0x1896cce6,
+ /// or in textual repr: collectionHelperAddress()
+ function collectionHelperAddress() public view returns (address) {
+ require(false, stub_error);
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
}
/// @dev anonymous struct
@@ -1043,7 +1052,7 @@
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-/// @dev the ERC-165 identifier for this interface is 0x983a942b
+/// @dev the ERC-165 identifier for this interface is 0x80ac58cd
contract ERC721 is Dummy, ERC165, ERC721Events {
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
@@ -1175,15 +1184,6 @@
operator;
dummy;
return false;
- }
-
- /// @notice Returns collection helper contract address
- /// @dev EVM selector for this function is: 0x1896cce6,
- /// or in textual repr: collectionHelperAddress()
- function collectionHelperAddress() public view returns (address) {
- require(false, stub_error);
- dummy;
- return 0x0000000000000000000000000000000000000000;
}
}
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -184,21 +184,21 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Nonfungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
- Weight::from_ref_time(4_361_000 as u64)
- // Standard Error: 5_349_868
- .saturating_add(Weight::from_ref_time(637_246_356 as u64).saturating_mul(b as u64))
+ Weight::from_ref_time(31_850_484 as u64)
+ // Standard Error: 9_618
+ .saturating_add(Weight::from_ref_time(4_721_947 as u64).saturating_mul(b as u64))
.saturating_add(T::DbWeight::get().reads(2 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Nonfungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
- Weight::from_ref_time(4_489_000 as u64)
- // Standard Error: 5_738_954
- .saturating_add(Weight::from_ref_time(689_912_822 as u64).saturating_mul(b as u64))
+ Weight::from_ref_time(13_795_000 as u64)
+ // Standard Error: 28_239
+ .saturating_add(Weight::from_ref_time(12_840_446 as u64).saturating_mul(b as u64))
.saturating_add(T::DbWeight::get().reads(2 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
@@ -354,21 +354,21 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Nonfungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
- Weight::from_ref_time(4_361_000 as u64)
- // Standard Error: 5_349_868
- .saturating_add(Weight::from_ref_time(637_246_356 as u64).saturating_mul(b as u64))
+ Weight::from_ref_time(31_850_484 as u64)
+ // Standard Error: 9_618
+ .saturating_add(Weight::from_ref_time(4_721_947 as u64).saturating_mul(b as u64))
.saturating_add(RocksDbWeight::get().reads(2 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Nonfungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
- Weight::from_ref_time(4_489_000 as u64)
- // Standard Error: 5_738_954
- .saturating_add(Weight::from_ref_time(689_912_822 as u64).saturating_mul(b as u64))
+ Weight::from_ref_time(13_795_000 as u64)
+ // Standard Error: 28_239
+ .saturating_add(Weight::from_ref_time(12_840_446 as u64).saturating_mul(b as u64))
.saturating_add(RocksDbWeight::get().reads(2 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -295,7 +295,9 @@
MintingFinished {},
}
-#[solidity_interface(name = ERC721Metadata)]
+/// @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> RefungibleHandle<T>
where
T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
@@ -364,7 +366,7 @@
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
-#[solidity_interface(name = ERC721Enumerable)]
+#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]
impl<T: Config> RefungibleHandle<T> {
/// @notice Enumerate valid RFTs
/// @param index A counter less than `totalSupply()`
@@ -391,7 +393,7 @@
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-#[solidity_interface(name = ERC721, events(ERC721Events))]
+#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]
impl<T: Config> RefungibleHandle<T> {
/// @notice Count all RFTs assigned to an owner
/// @dev RFTs assigned to the zero address are considered invalid, and this
@@ -422,6 +424,7 @@
}
/// @dev Not implemented
+ #[solidity(rename_selector = "safeTransferFrom")]
fn safe_transfer_from_with_data(
&mut self,
_from: address,
@@ -434,6 +437,7 @@
}
/// @dev Not implemented
+ #[solidity(rename_selector = "safeTransferFrom")]
fn safe_transfer_from(
&mut self,
_from: address,
@@ -517,11 +521,6 @@
Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))
}
-
- /// @notice Returns collection helper contract address
- fn collection_helper_address(&self) -> Result<address> {
- Ok(T::ContractAddress::get())
- }
}
/// Returns amount of pieces of `token` that `owner` have
@@ -1116,6 +1115,11 @@
token.try_into().map_err(|_| "token id overflow")?,
))
}
+
+ /// @notice Returns collection helper contract address
+ fn collection_helper_address(&self) -> Result<address> {
+ Ok(T::ContractAddress::get())
+ }
}
#[solidity_interface(
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -515,12 +515,29 @@
Ok(())
}
+ /// A batch operation to add, edit or remove properties for a token.
+ /// It sets or removes a token's properties according to
+ /// `properties_updates` contents:
+ /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
+ /// * removes a property under the <key> if the value is `None` `(<key>, None)`.
+ ///
+ /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
+ /// - `is_token_create`: Indicates that method is called during token initialization.
+ /// Allows to bypass ownership check.
+ ///
+ /// All affected properties should have `mutable` permission
+ /// to be **deleted** or to be **set more than once**,
+ /// and the sender should have permission to edit those properties.
+ ///
+ /// This function fires an event for each property change.
+ /// In case of an error, all the changes (including the events) will be reverted
+ /// since the function is transactional.
#[transactional]
fn modify_token_properties(
collection: &RefungibleHandle<T>,
sender: &T::CrossAccountId,
token_id: TokenId,
- properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+ properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
is_token_create: bool,
nesting_budget: &dyn Budget,
) -> DispatchResult {
@@ -544,15 +561,16 @@
Ok(is_bundle_owner)
};
- for (key, value) in properties {
- let permission = <PalletCommon<T>>::property_permissions(collection.id)
+ let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
+ let permissions = <PalletCommon<T>>::property_permissions(collection.id);
+
+ for (key, value) in properties_updates {
+ let permission = permissions
.get(&key)
.cloned()
.unwrap_or_else(PropertyPermission::none);
- let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))
- .get(&key)
- .is_some();
+ let is_property_exists = stored_properties.get(&key).is_some();
match permission {
PropertyPermission { mutable: false, .. } if is_property_exists => {
@@ -578,10 +596,9 @@
match value {
Some(value) => {
- <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
- properties.try_set(key.clone(), value)
- })
- .map_err(<CommonError<T>>::from)?;
+ stored_properties
+ .try_set(key.clone(), value)
+ .map_err(<CommonError<T>>::from)?;
<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(
collection.id,
@@ -590,10 +607,9 @@
));
}
None => {
- <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
- properties.remove(&key)
- })
- .map_err(<CommonError<T>>::from)?;
+ stored_properties
+ .remove(&key)
+ .map_err(<CommonError<T>>::from)?;
<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
collection.id,
@@ -612,6 +628,8 @@
);
}
+ <TokenProperties<T>>::set((collection.id, token_id), stored_properties);
+
Ok(())
}
@@ -1159,6 +1177,13 @@
// `from`, `to` checked in [`transfer`]
collection.check_allowlist(spender)?;
}
+
+ if collection.ignores_token_restrictions(spender) {
+ return Ok(Self::compute_allowance_decrease(
+ collection, token, from, &spender, amount,
+ ));
+ }
+
if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
// TODO: should collection owner be allowed to perform this transfer?
ensure!(
@@ -1173,21 +1198,30 @@
);
return Ok(None);
}
- let allowance =
- <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
+ let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);
+ if allowance.is_some() {
+ return Ok(allowance);
+ }
+
// Allowance (if any) would be reduced if spender is also wallet operator
if <CollectionAllowance<T>>::get((collection.id, from, spender)) {
return Ok(allowance);
}
- if allowance.is_none() {
- ensure!(
- collection.ignores_allowance(spender),
- <CommonError<T>>::ApprovedValueTooLow
- );
- }
- Ok(allowance)
+ Err(<CommonError<T>>::ApprovedValueTooLow.into())
+ }
+
+ /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.
+ /// Otherwise, it returns `None`.
+ fn compute_allowance_decrease(
+ collection: &RefungibleHandle<T>,
+ token: TokenId,
+ from: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
+ amount: u128,
+ ) -> Option<u128> {
+ <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)
}
/// Transfer RFT token pieces from one account to another.
@@ -1353,7 +1387,7 @@
sender: &T::CrossAccountId,
properties: Vec<Property>,
) -> DispatchResult {
- <PalletCommon<T>>::set_collection_properties(collection, sender, properties)
+ <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())
}
pub fn delete_collection_properties(
@@ -1361,7 +1395,11 @@
sender: &T::CrossAccountId,
property_keys: Vec<PropertyKey>,
) -> DispatchResult {
- <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)
+ <PalletCommon<T>>::delete_collection_properties(
+ collection,
+ sender,
+ property_keys.into_iter(),
+ )
}
pub fn set_token_property_permissions(
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
@@ -641,6 +641,8 @@
TransferEnabled
}
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
contract ERC721Metadata is Dummy, ERC165 {
// /// @notice A descriptive name for a collection of NFTs in this contract
@@ -783,7 +785,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xabf30dc2
+/// @dev the ERC-165 identifier for this interface is 0xb365c124
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,
@@ -985,6 +987,15 @@
dummy;
return 0x0000000000000000000000000000000000000000;
}
+
+ /// @notice Returns collection helper contract address
+ /// @dev EVM selector for this function is: 0x1896cce6,
+ /// or in textual repr: collectionHelperAddress()
+ function collectionHelperAddress() public view returns (address) {
+ require(false, stub_error);
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
}
/// @dev anonymous struct
@@ -1042,7 +1053,7 @@
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-/// @dev the ERC-165 identifier for this interface is 0x4016cd87
+/// @dev the ERC-165 identifier for this interface is 0x80ac58cd
contract ERC721 is Dummy, ERC165, ERC721Events {
/// @notice Count all RFTs assigned to an owner
/// @dev RFTs assigned to the zero address are considered invalid, and this
@@ -1075,9 +1086,9 @@
}
/// @dev Not implemented
- /// @dev EVM selector for this function is: 0x60a11672,
- /// or in textual repr: safeTransferFromWithData(address,address,uint256,bytes)
- function safeTransferFromWithData(
+ /// @dev EVM selector for this function is: 0xb88d4fde,
+ /// or in textual repr: safeTransferFrom(address,address,uint256,bytes)
+ function safeTransferFrom(
address from,
address to,
uint256 tokenId,
@@ -1172,15 +1183,6 @@
operator;
dummy;
return false;
- }
-
- /// @notice Returns collection helper contract address
- /// @dev EVM selector for this function is: 0x1896cce6,
- /// or in textual repr: collectionHelperAddress()
- function collectionHelperAddress() public view returns (address) {
- require(false, stub_error);
- dummy;
- return 0x0000000000000000000000000000000000000000;
}
}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -246,21 +246,21 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible TokenProperties (r:1 w:1)
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Refungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
- Weight::from_ref_time(4_578_000 as u64)
- // Standard Error: 5_396_287
- .saturating_add(Weight::from_ref_time(633_314_546 as u64).saturating_mul(b as u64))
+ Weight::from_ref_time(25_518_267 as u64)
+ // Standard Error: 20_451
+ .saturating_add(Weight::from_ref_time(5_041_089 as u64).saturating_mul(b as u64))
.saturating_add(T::DbWeight::get().reads(2 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible TokenProperties (r:1 w:1)
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Refungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
- Weight::from_ref_time(4_583_000 as u64)
- // Standard Error: 5_762_380
- .saturating_add(Weight::from_ref_time(696_007_076 as u64).saturating_mul(b as u64))
+ Weight::from_ref_time(13_715_000 as u64)
+ // Standard Error: 28_323
+ .saturating_add(Weight::from_ref_time(13_113_351 as u64).saturating_mul(b as u64))
.saturating_add(T::DbWeight::get().reads(2 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
@@ -478,21 +478,21 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible TokenProperties (r:1 w:1)
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Refungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
- Weight::from_ref_time(4_578_000 as u64)
- // Standard Error: 5_396_287
- .saturating_add(Weight::from_ref_time(633_314_546 as u64).saturating_mul(b as u64))
+ Weight::from_ref_time(25_518_267 as u64)
+ // Standard Error: 20_451
+ .saturating_add(Weight::from_ref_time(5_041_089 as u64).saturating_mul(b as u64))
.saturating_add(RocksDbWeight::get().reads(2 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible TokenProperties (r:1 w:1)
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Refungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
- Weight::from_ref_time(4_583_000 as u64)
- // Standard Error: 5_762_380
- .saturating_add(Weight::from_ref_time(696_007_076 as u64).saturating_mul(b as u64))
+ Weight::from_ref_time(13_715_000 as u64)
+ // Standard Error: 28_323
+ .saturating_add(Weight::from_ref_time(13_113_351 as u64).saturating_mul(b as u64))
.saturating_add(RocksDbWeight::get().reads(2 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -33,7 +33,6 @@
};
use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};
-use sp_std::vec;
use up_data_structs::{
CollectionDescription, CollectionMode, CollectionName, CollectionTokenPrefix,
CreateCollectionData,
@@ -316,13 +315,14 @@
<PalletCommon<T>>::set_collection_properties(
&collection,
&caller,
- vec![up_data_structs::Property {
+ [up_data_structs::Property {
key: key::base_uri(),
value: base_uri
.into_bytes()
.try_into()
.map_err(|_| "base uri is too large")?,
- }],
+ }]
+ .into_iter(),
)
.map_err(dispatch_to_evm::<T>)?;
}
runtime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -139,8 +139,7 @@
| BalanceOf { .. }
| OwnerOf { .. }
| GetApproved { .. }
- | IsApprovedForAll { .. }
- | CollectionHelperAddress => None,
+ | IsApprovedForAll { .. } => None,
// Not sponsored
SafeTransferFromWithData { .. }
@@ -230,7 +229,8 @@
| CrossOwnerOf { .. }
| Properties { .. }
| NextTokenId
- | TokenContractAddress { .. } => None,
+ | TokenContractAddress { .. }
+ | CollectionHelperAddress => None,
// Not sponsored
BurnFrom { .. }
runtime/common/identity.rsdiffbeforeafterboth--- a/runtime/common/identity.rs
+++ b/runtime/common/identity.rs
@@ -24,6 +24,9 @@
transaction_validity::{TransactionValidity, ValidTransaction, TransactionValidityError},
};
+#[cfg(feature = "collator-selection")]
+use sp_runtime::transaction_validity::InvalidTransaction;
+
#[derive(Debug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
pub struct DisableIdentityCalls;
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -451,7 +451,9 @@
}
fn account_code_at(address: H160) -> Vec<u8> {
- EVM::account_codes(address)
+ use pallet_evm::OnMethodCall;
+ <Runtime as pallet_evm::Config>::OnMethodCall::get_code(&address)
+ .unwrap_or_else(|| EVM::account_codes(address))
}
fn author() -> H160 {
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -193,6 +193,7 @@
'refungible',
'rmrk',
'app-promotion',
+ 'collator-selection',
'foreign-assets',
'pallet-test-utils',
]
tests/src/eth/abi/nonFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -51,6 +51,12 @@
},
{
"anonymous": false,
+ "inputs": [],
+ "name": "MintingFinished",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
"inputs": [
{
"indexed": true,
@@ -417,6 +423,13 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "finishMinting",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
@@ -504,6 +517,13 @@
},
{
"inputs": [],
+ "name": "mintingFinished",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "name",
"outputs": [{ "internalType": "string", "name": "", "type": "string" }],
"stateMutability": "view",
tests/src/eth/abi/reFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -51,6 +51,12 @@
},
{
"anonymous": false,
+ "inputs": [],
+ "name": "MintingFinished",
+ "type": "event"
+ },
+ {
+ "anonymous": false,
"inputs": [
{
"indexed": true,
@@ -399,6 +405,13 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "finishMinting",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
@@ -486,6 +499,13 @@
},
{
"inputs": [],
+ "name": "mintingFinished",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "name",
"outputs": [{ "internalType": "string", "name": "", "type": "string" }],
"stateMutability": "view",
@@ -596,7 +616,7 @@
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{ "internalType": "bytes", "name": "data", "type": "bytes" }
],
- "name": "safeTransferFromWithData",
+ "name": "safeTransferFrom",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
tests/src/eth/abi/reFungibleToken.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungibleToken.json
+++ b/tests/src/eth/abi/reFungibleToken.json
@@ -98,6 +98,16 @@
},
{
"inputs": [
+ { "internalType": "address", "name": "from", "type": "address" },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
+ ],
+ "name": "burnFrom",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{
"components": [
{ "internalType": "address", "name": "eth", "type": "address" },
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -536,7 +536,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x0e48fdb4
+/// @dev the ERC-165 identifier for this interface is 0x16de3152
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,
@@ -661,6 +661,11 @@
/// @dev EVM selector for this function is: 0xb904db03,
/// or in textual repr: mintCross((address,uint256),(string,bytes)[])
function mintCross(CrossAddress memory to, Property[] memory properties) external returns (uint256);
+
+ /// @notice Returns collection helper contract address
+ /// @dev EVM selector for this function is: 0x1896cce6,
+ /// or in textual repr: collectionHelperAddress()
+ function collectionHelperAddress() external view returns (address);
}
/// @dev anonymous struct
@@ -703,7 +708,7 @@
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-/// @dev the ERC-165 identifier for this interface is 0x983a942b
+/// @dev the ERC-165 identifier for this interface is 0x80ac58cd
interface ERC721 is Dummy, ERC165, ERC721Events {
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
@@ -786,11 +791,6 @@
/// @dev EVM selector for this function is: 0xe985e9c5,
/// or in textual repr: isApprovedForAll(address,address)
function isApprovedForAll(address owner, address operator) external view returns (bool);
-
- /// @notice Returns collection helper contract address
- /// @dev EVM selector for this function is: 0x1896cce6,
- /// or in textual repr: collectionHelperAddress()
- function collectionHelperAddress() external view returns (address);
}
interface UniqueNFT is
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -441,6 +441,8 @@
TransferEnabled
}
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
interface ERC721Metadata is Dummy, ERC165 {
// /// @notice A descriptive name for a collection of NFTs in this contract
@@ -534,7 +536,7 @@
}
/// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xabf30dc2
+/// @dev the ERC-165 identifier for this interface is 0xb365c124
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,
@@ -660,6 +662,11 @@
/// @dev EVM selector for this function is: 0xab76fac6,
/// or in textual repr: tokenContractAddress(uint256)
function tokenContractAddress(uint256 token) external view returns (address);
+
+ /// @notice Returns collection helper contract address
+ /// @dev EVM selector for this function is: 0x1896cce6,
+ /// or in textual repr: collectionHelperAddress()
+ function collectionHelperAddress() external view returns (address);
}
/// @dev anonymous struct
@@ -702,7 +709,7 @@
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
-/// @dev the ERC-165 identifier for this interface is 0x4016cd87
+/// @dev the ERC-165 identifier for this interface is 0x80ac58cd
interface ERC721 is Dummy, ERC165, ERC721Events {
/// @notice Count all RFTs assigned to an owner
/// @dev RFTs assigned to the zero address are considered invalid, and this
@@ -725,9 +732,9 @@
function ownerOf(uint256 tokenId) external view returns (address);
/// @dev Not implemented
- /// @dev EVM selector for this function is: 0x60a11672,
- /// or in textual repr: safeTransferFromWithData(address,address,uint256,bytes)
- function safeTransferFromWithData(
+ /// @dev EVM selector for this function is: 0xb88d4fde,
+ /// or in textual repr: safeTransferFrom(address,address,uint256,bytes)
+ function safeTransferFrom(
address from,
address to,
uint256 tokenId,
@@ -783,11 +790,6 @@
/// @dev EVM selector for this function is: 0xe985e9c5,
/// or in textual repr: isApprovedForAll(address,address)
function isApprovedForAll(address owner, address operator) external view returns (bool);
-
- /// @notice Returns collection helper contract address
- /// @dev EVM selector for this function is: 0x1896cce6,
- /// or in textual repr: collectionHelperAddress()
- function collectionHelperAddress() external view returns (address);
}
interface UniqueRefungible is
tests/src/nesting/unnest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -16,14 +16,17 @@
import {IKeyringPair} from '@polkadot/types/types';
import {expect, itSub, Pallets, usingPlaygrounds} from '../util';
+import {UniqueFTCollection, UniqueNFToken, UniqueRFToken} from '../util/playgrounds/unique';
describe('Integration Test: Unnesting', () => {
let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
- [alice] = await helper.arrange.createAccounts([50n], donor);
+ [alice, bob, charlie] = await helper.arrange.createAccounts([200n, 50n, 50n], donor);
});
});
@@ -63,6 +66,208 @@
expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
expect(await targetToken.getChildren()).to.be.length(0);
});
+
+ itSub.ifWithPallets('ReFungible: allows the owner to successfully unnest a token', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+ const targetToken = await collection.mintToken(alice);
+
+ const collectionRFT = await helper.rft.mintCollection(alice);
+
+ // Nest and unnest
+ const token = await collectionRFT.mintToken(alice, 10n, targetToken.nestingAccount());
+ await expect(token.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(9n);
+ expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
+
+ // Nest and burn
+ await token.transfer(alice, targetToken.nestingAccount(), 5n);
+ await expect(token.burnFrom(alice, targetToken.nestingAccount(), 6n), 'while burning').to.be.fulfilled;
+ expect(await token.getBalance({Substrate: alice.address})).to.be.equal(4n);
+ expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+ expect(await targetToken.getChildren()).to.be.length(0);
+ });
+
+ async function checkNestedAmountState({
+ expectedBalance,
+ childrenShouldPresent,
+ nested,
+ targetNft,
+ }: {
+ expectedBalance: bigint,
+ childrenShouldPresent: boolean,
+ nested: UniqueFTCollection | UniqueRFToken,
+ targetNft: UniqueNFToken,
+ }) {
+ const balance = await nested.getBalance(targetNft.nestingAccount());
+ expect(balance).to.be.equal(expectedBalance);
+
+ const children = await targetNft.getChildren();
+
+ if (childrenShouldPresent) {
+ expect(children[0]).to.be.deep.equal({
+ collectionId: nested.collectionId,
+ tokenId: (nested instanceof UniqueFTCollection) ? 0 : nested.tokenId,
+ });
+ } else {
+ expect(children.length).to.be.equal(0);
+ }
+ }
+
+ function ownerOrAdminUnnestCases(modes: ('ft' | 'nft' | 'rft')[]): {
+ mode: 'ft' | 'nft' | 'rft',
+ sender: string,
+ op: 'transfer' | 'burn',
+ requiredPallets: Pallets[],
+ }[] {
+ const senders = ['owner', 'admin'];
+ const ops = ['transfer', 'burn'];
+
+ const cases = [];
+ for (const mode of modes) {
+ const requiredPallets = (mode === 'rft')
+ ? [Pallets.ReFungible]
+ : [];
+
+ for (const sender of senders) {
+ for (const op of ops) {
+ cases.push({
+ mode: mode as 'ft' | 'nft' | 'rft',
+ sender,
+ op: op as 'transfer' | 'burn',
+ requiredPallets,
+ });
+ }
+ }
+ }
+
+ return cases;
+ }
+
+ ownerOrAdminUnnestCases(['ft', 'rft']).map(testCase =>
+ itSub.ifWithPallets(`[${testCase.mode}]: allows a collection ${testCase.sender} to ${testCase.op} nested token`, testCase.requiredPallets, async({helper}) => {
+ const owner = alice;
+ const admin = bob;
+
+ const unnester = (testCase.sender === 'owner')
+ ? owner
+ : admin;
+
+ const collectionNFT = await helper.nft.mintCollection(owner);
+ await collectionNFT.setPermissions(owner, {nesting: {tokenOwner: true}});
+
+ const collectionNested = await helper[testCase.mode as 'ft' | 'rft'].mintCollection(owner, {
+ limits: {
+ ownerCanTransfer: true,
+ },
+ });
+ await collectionNested.addAdmin(owner, {Substrate: admin.address});
+
+ const targetNft = await collectionNFT.mintToken(owner, {Substrate: charlie.address});
+
+ let nested: UniqueFTCollection | UniqueRFToken;
+ const totalAmount = 5n;
+ const firstUnnestAmount = 2n;
+ const restUnnestAmount = totalAmount - firstUnnestAmount;
+
+ if (collectionNested instanceof UniqueFTCollection) {
+ await collectionNested.mint(owner, totalAmount, {Substrate: charlie.address});
+ nested = collectionNested;
+ } else {
+ nested = await collectionNested.mintToken(owner, totalAmount, {Substrate: charlie.address});
+ }
+
+ // transfer/burn `amount` of nested assets by `unnester`.
+ const doOperationAndCheck = async ({
+ amount,
+ shouldBeNestedAfterOp,
+ }: {
+ amount: bigint,
+ shouldBeNestedAfterOp: boolean,
+ }) => {
+ const nestedBalanceBeforeOp = await nested.getBalance(targetNft.nestingAccount());
+
+ if (testCase.op === 'transfer') {
+ const bobBalanceBeforeOp = await nested.getBalance({Substrate: bob.address});
+
+ await nested.transferFrom(unnester, targetNft.nestingAccount(), {Substrate: bob.address}, amount);
+ expect(await nested.getBalance({Substrate: bob.address})).to.be.equal(bobBalanceBeforeOp + amount);
+ } else {
+ if (nested instanceof UniqueFTCollection) {
+ await nested.burnTokensFrom(unnester, targetNft.nestingAccount(), amount);
+ } else {
+ await nested.burnFrom(unnester, targetNft.nestingAccount(), amount);
+ }
+ }
+
+ await checkNestedAmountState({
+ expectedBalance: nestedBalanceBeforeOp - amount,
+ childrenShouldPresent: shouldBeNestedAfterOp,
+ nested,
+ targetNft,
+ });
+ };
+
+ // Initial setup: nest (fungibles/rft parts).
+ // Check NFT's balance of nested assets and NFT's children.
+ await nested.transfer(charlie, targetNft.nestingAccount(), totalAmount);
+ await checkNestedAmountState({
+ expectedBalance: totalAmount,
+ childrenShouldPresent: true,
+ nested,
+ targetNft,
+ });
+
+ // Transfer/burn only a part of nested assets.
+ // Check that NFT's balance of the nested assets correctly decreased and NFT's children are not changed.
+ await doOperationAndCheck({
+ amount: firstUnnestAmount,
+ shouldBeNestedAfterOp: true,
+ });
+
+ // Transfer/burn all remaining nested assets.
+ // Check that NFT's balance of the nested assets is 0 and NFT has no more children.
+ await doOperationAndCheck({
+ amount: restUnnestAmount,
+ shouldBeNestedAfterOp: false,
+ });
+ }));
+
+ ownerOrAdminUnnestCases(['nft']).map(testCase =>
+ itSub(`[nft]: allows a collection ${testCase.sender} to ${testCase.op} nested token`, async ({helper}) => {
+ const owner = alice;
+ const admin = bob;
+
+ const unnester = (testCase.sender === 'owner')
+ ? owner
+ : admin;
+
+ const collectionNFT = await helper.nft.mintCollection(owner);
+ await collectionNFT.setPermissions(owner, {nesting: {tokenOwner: true}});
+
+ const collectionNested = await helper.nft.mintCollection(owner, {
+ limits: {
+ ownerCanTransfer: true,
+ },
+ });
+ await collectionNested.addAdmin(owner, {Substrate: admin.address});
+
+ const targetNft = await collectionNFT.mintToken(owner, {Substrate: charlie.address});
+ const nested = await collectionNested.mintToken(owner, {Substrate: charlie.address});
+
+ await nested.transfer(charlie, targetNft.nestingAccount());
+ expect(await targetNft.getChildren()).to.be.deep.equal([{
+ collectionId: nested.collectionId,
+ tokenId: nested.tokenId,
+ }]);
+
+ if (testCase.op === 'transfer') {
+ await nested.transferFrom(unnester, targetNft.nestingAccount(), {Substrate: bob.address});
+ } else {
+ await nested.burnFrom(unnester, targetNft.nestingAccount());
+ }
+
+ expect((await targetNft.getChildren()).length).to.be.equal(0);
+ }));
});
describe('Negative Test: Unnesting', () => {
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -76,6 +76,7 @@
appPromotion,
testUtils,
...rmrkPallets,
+ ...collatorSelection,
);
} else if (chain.eq('QUARTZ by UNIQUE') || chain.eq('SAPPHIRE by UNIQUE')) {
requiredPallets.push(
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, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50 Substrate?: TSubstrateAccount;51 Ethereum?: TEthereumAccount;5253 constructor(account: ICrossAccountId) {54 if (account.Substrate) this.Substrate = account.Substrate;55 if (account.Ethereum) this.Ethereum = account.Ethereum;56 }5758 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59 switch (domain) {60 case 'Substrate': return new CrossAccountId({Substrate: account.address});61 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62 }63 }6465 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67 }6869 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70 return encodeAddress(decodeAddress(address), ss58Format);71 }7273 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75 }7677 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79 return this;80 }8182 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84 }8586 toEthereum(): CrossAccountId {87 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88 return this;89 }9091 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92 return evmToAddress(address, ss58Format);93 }9495 toSubstrate(ss58Format?: number): CrossAccountId {96 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97 return this;98 }99100 toLowerCase(): CrossAccountId {101 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103 return this;104 }105}106107const nesting = {108 toChecksumAddress(address: string): string {109 if (typeof address === 'undefined') return '';110111 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113 address = address.toLowerCase().replace(/^0x/i,'');114 const addressHash = keccakAsHex(address).replace(/^0x/i,'');115 const checksumAddress = ['0x'];116117 for (let i = 0; i < address.length; i++) {118 // If ith character is 8 to f then make it uppercase119 if (parseInt(addressHash[i], 16) > 7) {120 checksumAddress.push(address[i].toUpperCase());121 } else {122 checksumAddress.push(address[i]);123 }124 }125 return checksumAddress.join('');126 },127 tokenIdToAddress(collectionId: number, tokenId: number) {128 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);129 },130};131132class UniqueUtil {133 static transactionStatus = {134 NOT_READY: 'NotReady',135 FAIL: 'Fail',136 SUCCESS: 'Success',137 };138139 static chainLogType = {140 EXTRINSIC: 'extrinsic',141 RPC: 'rpc',142 };143144 static getTokenAccount(token: IToken): CrossAccountId {145 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146 }147148 static getTokenAddress(token: IToken): string {149 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150 }151152 static getDefaultLogger(): ILogger {153 return {154 log(msg: any, level = 'INFO') {155 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156 },157 level: {158 ERROR: 'ERROR',159 WARNING: 'WARNING',160 INFO: 'INFO',161 },162 };163 }164165 static vec2str(arr: string[] | number[]) {166 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167 }168169 static str2vec(string: string) {170 if (typeof string !== 'string') return string;171 return Array.from(string).map(x => x.charCodeAt(0));172 }173174 static fromSeed(seed: string, ss58Format = 42) {175 const keyring = new Keyring({type: 'sr25519', ss58Format});176 return keyring.addFromUri(seed);177 }178179 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180 if (creationResult.status !== this.transactionStatus.SUCCESS) {181 throw Error('Unable to create collection!');182 }183184 let collectionId = null;185 creationResult.result.events.forEach(({event: {data, method, section}}) => {186 if ((section === 'common') && (method === 'CollectionCreated')) {187 collectionId = parseInt(data[0].toString(), 10);188 }189 });190191 if (collectionId === null) {192 throw Error('No CollectionCreated event was found!');193 }194195 return collectionId;196 }197198 static extractTokensFromCreationResult(creationResult: ITransactionResult): {199 success: boolean,200 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201 } {202 if (creationResult.status !== this.transactionStatus.SUCCESS) {203 throw Error('Unable to create tokens!');204 }205 let success = false;206 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207 creationResult.result.events.forEach(({event: {data, method, section}}) => {208 if (method === 'ExtrinsicSuccess') {209 success = true;210 } else if ((section === 'common') && (method === 'ItemCreated')) {211 tokens.push({212 collectionId: parseInt(data[0].toString(), 10),213 tokenId: parseInt(data[1].toString(), 10),214 owner: data[2].toHuman(),215 amount: data[3].toBigInt(),216 });217 }218 });219 return {success, tokens};220 }221222 static extractTokensFromBurnResult(burnResult: ITransactionResult): {223 success: boolean,224 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225 } {226 if (burnResult.status !== this.transactionStatus.SUCCESS) {227 throw Error('Unable to burn tokens!');228 }229 let success = false;230 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231 burnResult.result.events.forEach(({event: {data, method, section}}) => {232 if (method === 'ExtrinsicSuccess') {233 success = true;234 } else if ((section === 'common') && (method === 'ItemDestroyed')) {235 tokens.push({236 collectionId: parseInt(data[0].toString(), 10),237 tokenId: parseInt(data[1].toString(), 10),238 owner: data[2].toHuman(),239 amount: data[3].toBigInt(),240 });241 }242 });243 return {success, tokens};244 }245246 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247 let eventId = null;248 events.forEach(({event: {data, method, section}}) => {249 if ((section === expectedSection) && (method === expectedMethod)) {250 eventId = parseInt(data[0].toString(), 10);251 }252 });253254 if (eventId === null) {255 throw Error(`No ${expectedMethod} event was found!`);256 }257 return eventId === collectionId;258 }259260 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261 const normalizeAddress = (address: string | ICrossAccountId) => {262 if(typeof address === 'string') return address;263 const obj = {} as any;264 Object.keys(address).forEach(k => {265 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266 });267 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269 return address;270 };271 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272 events.forEach(({event: {data, method, section}}) => {273 if ((section === 'common') && (method === 'Transfer')) {274 const hData = (data as any).toJSON();275 transfer = {276 collectionId: hData[0],277 tokenId: hData[1],278 from: normalizeAddress(hData[2]),279 to: normalizeAddress(hData[3]),280 amount: BigInt(hData[4]),281 };282 }283 });284 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287 isSuccess = isSuccess && amount === transfer.amount;288 return isSuccess;289 }290291 static bigIntToDecimals(number: bigint, decimals = 18) {292 const numberStr = number.toString();293 const dotPos = numberStr.length - decimals;294295 if (dotPos <= 0) {296 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297 } else {298 const intPart = numberStr.substring(0, dotPos);299 const fractPart = numberStr.substring(dotPos);300 return intPart + '.' + fractPart;301 }302 }303}304305class UniqueEventHelper {306 private static extractIndex(index: any): [number, number] | string {307 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308 return index.toJSON();309 }310311 private static extractSub(data: any, subTypes: any): {[key: string]: any} {312 let obj: any = {};313 let index = 0;314315 if (data.entries) {316 for(const [key, value] of data.entries()) {317 obj[key] = this.extractData(value, subTypes[index]);318 index++;319 }320 } else obj = data.toJSON();321322 return obj;323 }324325 private static toHuman(data: any) {326 return data && data.toHuman ? data.toHuman() : `${data}`;327 }328329 private static extractData(data: any, type: any): any {330 if(!type) return this.toHuman(data);331 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334 return this.toHuman(data);335 }336337 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338 const parsedEvents: IEvent[] = [];339340 events.forEach((record) => {341 const {event, phase} = record;342 const types = event.typeDef;343344 const eventData: IEvent = {345 section: event.section.toString(),346 method: event.method.toString(),347 index: this.extractIndex(event.index),348 data: [],349 phase: phase.toJSON(),350 };351352 event.data.forEach((val: any, index: number) => {353 eventData.data.push(this.extractData(val, types[index]));354 });355356 parsedEvents.push(eventData);357 });358359 return parsedEvents;360 }361}362363export class ChainHelperBase {364 helperBase: any;365366 transactionStatus = UniqueUtil.transactionStatus;367 chainLogType = UniqueUtil.chainLogType;368 util: typeof UniqueUtil;369 eventHelper: typeof UniqueEventHelper;370 logger: ILogger;371 api: ApiPromise | null;372 forcedNetwork: TNetworks | null;373 network: TNetworks | null;374 wsEndpoint: string | null;375 chainLog: IUniqueHelperLog[];376 children: ChainHelperBase[];377 address: AddressGroup;378 chain: ChainGroup;379380 constructor(logger?: ILogger, helperBase?: any) {381 this.helperBase = helperBase;382383 this.util = UniqueUtil;384 this.eventHelper = UniqueEventHelper;385 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();386 this.logger = logger;387 this.api = null;388 this.forcedNetwork = null;389 this.network = null;390 this.wsEndpoint = null;391 this.chainLog = [];392 this.children = [];393 this.address = new AddressGroup(this);394 this.chain = new ChainGroup(this);395 }396397 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {398 Object.setPrototypeOf(helperCls.prototype, this);399 const newHelper = new helperCls(this.logger, options);400401 newHelper.api = this.api;402 newHelper.network = this.network;403 newHelper.forceNetwork = this.forceNetwork;404405 this.children.push(newHelper);406407 return newHelper;408 }409410 getEndpoint(): string {411 if (this.wsEndpoint === null) throw Error('No connection was established');412 return this.wsEndpoint;413 }414415 getApi(): ApiPromise {416 if(this.api === null) throw Error('API not initialized');417 return this.api;418 }419420 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {421 const collectedEvents: IEvent[] = [];422 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {423 const ievents = this.eventHelper.extractEvents(events);424 ievents.forEach((event) => {425 expectedEvents.forEach((e => {426 if (event.section === e.section && e.names.includes(event.method)) {427 collectedEvents.push(event);428 }429 }));430 });431 });432 return {unsubscribe: unsubscribe as any, collectedEvents};433 }434435 clearChainLog(): void {436 this.chainLog = [];437 }438439 forceNetwork(value: TNetworks): void {440 this.forcedNetwork = value;441 }442443 async connect(wsEndpoint: string, listeners?: IApiListeners) {444 if (this.api !== null) throw Error('Already connected');445 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);446 this.wsEndpoint = wsEndpoint;447 this.api = api;448 this.network = network;449 }450451 async disconnect() {452 for (const child of this.children) {453 child.clearApi();454 }455456 if (this.api === null) return;457 await this.api.disconnect();458 this.clearApi();459 }460461 clearApi() {462 this.api = null;463 this.network = null;464 }465466 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {467 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;468 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];469470 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;471472 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;473 return 'opal';474 }475476 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {477 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});478 await api.isReady;479480 const network = await this.detectNetwork(api);481482 await api.disconnect();483484 return network;485 }486487 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{488 api: ApiPromise;489 network: TNetworks;490 }> {491 if(typeof network === 'undefined' || network === null) network = 'opal';492 const supportedRPC = {493 opal: {494 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,495 },496 quartz: {497 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,498 },499 unique: {500 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,501 },502 rococo: {},503 westend: {},504 moonbeam: {},505 moonriver: {},506 acala: {},507 karura: {},508 westmint: {},509 };510 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);511 const rpc = supportedRPC[network];512513 // TODO: investigate how to replace rpc in runtime514 // api._rpcCore.addUserInterfaces(rpc);515516 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});517518 await api.isReadyOrError;519520 if (typeof listeners === 'undefined') listeners = {};521 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {522 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;523 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);524 }525526 return {api, network};527 }528529 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {530 const {events, status} = data;531 if (status.isReady) {532 return this.transactionStatus.NOT_READY;533 }534 if (status.isBroadcast) {535 return this.transactionStatus.NOT_READY;536 }537 if (status.isInBlock || status.isFinalized) {538 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');539 if (errors.length > 0) {540 return this.transactionStatus.FAIL;541 }542 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {543 return this.transactionStatus.SUCCESS;544 }545 }546547 return this.transactionStatus.FAIL;548 }549550 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {551 const sign = (callback: any) => {552 if(options !== null) return transaction.signAndSend(sender, options, callback);553 return transaction.signAndSend(sender, callback);554 };555 // eslint-disable-next-line no-async-promise-executor556 return new Promise(async (resolve, reject) => {557 try {558 const unsub = await sign((result: any) => {559 const status = this.getTransactionStatus(result);560561 if (status === this.transactionStatus.SUCCESS) {562 this.logger.log(`${label} successful`);563 unsub();564 resolve({result, status});565 } else if (status === this.transactionStatus.FAIL) {566 let moduleError = null;567568 if (result.hasOwnProperty('dispatchError')) {569 const dispatchError = result['dispatchError'];570571 if (dispatchError) {572 if (dispatchError.isModule) {573 const modErr = dispatchError.asModule;574 const errorMeta = dispatchError.registry.findMetaError(modErr);575576 moduleError = `${errorMeta.section}.${errorMeta.name}`;577 } else {578 moduleError = dispatchError.toHuman();579 }580 } else {581 this.logger.log(result, this.logger.level.ERROR);582 }583 }584585 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);586 unsub();587 reject({status, moduleError, result});588 }589 });590 } catch (e) {591 this.logger.log(e, this.logger.level.ERROR);592 reject(e);593 }594 });595 }596597 async signTransactionWithoutSending(signer: TSigner, tx: any) {598 const api = this.getApi();599 const signingInfo = await api.derive.tx.signingInfo(signer.address);600601 tx.sign(signer, {602 blockHash: api.genesisHash,603 genesisHash: api.genesisHash,604 runtimeVersion: api.runtimeVersion,605 nonce: signingInfo.nonce,606 });607608 return tx.toHex();609 }610611 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {612 const api = this.getApi();613 const signingInfo = await api.derive.tx.signingInfo(signer.address);614615 // We need to sign the tx because616 // unsigned transactions does not have an inclusion fee617 tx.sign(signer, {618 blockHash: api.genesisHash,619 genesisHash: api.genesisHash,620 runtimeVersion: api.runtimeVersion,621 nonce: signingInfo.nonce,622 });623624 if (len === null) {625 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;626 } else {627 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;628 }629 }630631 constructApiCall(apiCall: string, params: any[]) {632 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);633 let call = this.getApi() as any;634 for(const part of apiCall.slice(4).split('.')) {635 call = call[part];636 if (!call) {637 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';638 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);639 }640 }641 return call(...params);642 }643644 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {645 if(this.api === null) throw Error('API not initialized');646 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);647648 const startTime = (new Date()).getTime();649 let result: ITransactionResult;650 let events: IEvent[] = [];651 try {652 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;653 events = this.eventHelper.extractEvents(result.result.events);654 }655 catch(e) {656 if(!(e as object).hasOwnProperty('status')) throw e;657 result = e as ITransactionResult;658 }659660 const endTime = (new Date()).getTime();661662 const log = {663 executedAt: endTime,664 executionTime: endTime - startTime,665 type: this.chainLogType.EXTRINSIC,666 status: result.status,667 call: extrinsic,668 signer: this.getSignerAddress(sender),669 params,670 } as IUniqueHelperLog;671672 if(result.status !== this.transactionStatus.SUCCESS) {673 if (result.moduleError) log.moduleError = result.moduleError;674 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;675 }676 if(events.length > 0) log.events = events;677678 this.chainLog.push(log);679680 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {681 if (result.moduleError) throw Error(`${result.moduleError}`);682 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));683 }684 return result;685 }686687 async callRpc(rpc: string, params?: any[]) {688 if(typeof params === 'undefined') params = [];689 if(this.api === null) throw Error('API not initialized');690 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);691692 const startTime = (new Date()).getTime();693 let result;694 let error = null;695 const log = {696 type: this.chainLogType.RPC,697 call: rpc,698 params,699 } as IUniqueHelperLog;700701 try {702 result = await this.constructApiCall(rpc, params);703 }704 catch(e) {705 error = e;706 }707708 const endTime = (new Date()).getTime();709710 log.executedAt = endTime;711 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';712 log.executionTime = endTime - startTime;713714 this.chainLog.push(log);715716 if(error !== null) throw error;717718 return result;719 }720721 getSignerAddress(signer: IKeyringPair | string): string {722 if(typeof signer === 'string') return signer;723 return signer.address;724 }725726 fetchAllPalletNames(): string[] {727 if(this.api === null) throw Error('API not initialized');728 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());729 }730731 fetchMissingPalletNames(requiredPallets: string[]): string[] {732 const palletNames = this.fetchAllPalletNames();733 return requiredPallets.filter(p => !palletNames.includes(p));734 }735}736737738class HelperGroup<T extends ChainHelperBase> {739 helper: T;740741 constructor(uniqueHelper: T) {742 this.helper = uniqueHelper;743 }744}745746747class CollectionGroup extends HelperGroup<UniqueHelper> {748 /**749 * Get number of blocks when sponsored transaction is available.750 *751 * @param collectionId ID of collection752 * @param tokenId ID of token753 * @param addressObj address for which the sponsorship is checked754 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});755 * @returns number of blocks or null if sponsorship hasn't been set756 */757 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {758 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();759 }760761 /**762 * Get the number of created collections.763 *764 * @returns number of created collections765 */766 async getTotalCount(): Promise<number> {767 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();768 }769770 /**771 * Get information about the collection with additional data,772 * including the number of tokens it contains, its administrators,773 * the normalized address of the collection's owner, and decoded name and description.774 *775 * @param collectionId ID of collection776 * @example await getData(2)777 * @returns collection information object778 */779 async getData(collectionId: number): Promise<{780 id: number;781 name: string;782 description: string;783 tokensCount: number;784 admins: CrossAccountId[];785 normalizedOwner: TSubstrateAccount;786 raw: any787 } | null> {788 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);789 const humanCollection = collection.toHuman(), collectionData = {790 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],791 raw: humanCollection,792 } as any, jsonCollection = collection.toJSON();793 if (humanCollection === null) return null;794 collectionData.raw.limits = jsonCollection.limits;795 collectionData.raw.permissions = jsonCollection.permissions;796 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);797 for (const key of ['name', 'description']) {798 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);799 }800801 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))802 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)803 : 0;804 collectionData.admins = await this.getAdmins(collectionId);805806 return collectionData;807 }808809 /**810 * Get the addresses of the collection's administrators, optionally normalized.811 *812 * @param collectionId ID of collection813 * @param normalize whether to normalize the addresses to the default ss58 format814 * @example await getAdmins(1)815 * @returns array of administrators816 */817 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {818 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();819820 return normalize821 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())822 : admins;823 }824825 /**826 * Get the addresses added to the collection allow-list, optionally normalized.827 * @param collectionId ID of collection828 * @param normalize whether to normalize the addresses to the default ss58 format829 * @example await getAllowList(1)830 * @returns array of allow-listed addresses831 */832 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {833 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();834 return normalize835 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())836 : allowListed;837 }838839 /**840 * Get the effective limits of the collection instead of null for default values841 *842 * @param collectionId ID of collection843 * @example await getEffectiveLimits(2)844 * @returns object of collection limits845 */846 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {847 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();848 }849850 /**851 * Burns the collection if the signer has sufficient permissions and collection is empty.852 *853 * @param signer keyring of signer854 * @param collectionId ID of collection855 * @example await helper.collection.burn(aliceKeyring, 3);856 * @returns ```true``` if extrinsic success, otherwise ```false```857 */858 async burn(signer: TSigner, collectionId: number): Promise<boolean> {859 const result = await this.helper.executeExtrinsic(860 signer,861 'api.tx.unique.destroyCollection', [collectionId],862 true,863 );864865 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');866 }867868 /**869 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.870 *871 * @param signer keyring of signer872 * @param collectionId ID of collection873 * @param sponsorAddress Sponsor substrate address874 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")875 * @returns ```true``` if extrinsic success, otherwise ```false```876 */877 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {878 const result = await this.helper.executeExtrinsic(879 signer,880 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],881 true,882 );883884 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');885 }886887 /**888 * Confirms consent to sponsor the collection on behalf of the signer.889 *890 * @param signer keyring of signer891 * @param collectionId ID of collection892 * @example confirmSponsorship(aliceKeyring, 10)893 * @returns ```true``` if extrinsic success, otherwise ```false```894 */895 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {896 const result = await this.helper.executeExtrinsic(897 signer,898 'api.tx.unique.confirmSponsorship', [collectionId],899 true,900 );901902 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');903 }904905 /**906 * Removes the sponsor of a collection, regardless if it consented or not.907 *908 * @param signer keyring of signer909 * @param collectionId ID of collection910 * @example removeSponsor(aliceKeyring, 10)911 * @returns ```true``` if extrinsic success, otherwise ```false```912 */913 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {914 const result = await this.helper.executeExtrinsic(915 signer,916 'api.tx.unique.removeCollectionSponsor', [collectionId],917 true,918 );919920 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');921 }922923 /**924 * Sets the limits of the collection. At least one limit must be specified for a correct call.925 *926 * @param signer keyring of signer927 * @param collectionId ID of collection928 * @param limits collection limits object929 * @example930 * await setLimits(931 * aliceKeyring,932 * 10,933 * {934 * sponsorTransferTimeout: 0,935 * ownerCanDestroy: false936 * }937 * )938 * @returns ```true``` if extrinsic success, otherwise ```false```939 */940 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {941 const result = await this.helper.executeExtrinsic(942 signer,943 'api.tx.unique.setCollectionLimits', [collectionId, limits],944 true,945 );946947 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');948 }949950 /**951 * Changes the owner of the collection to the new Substrate address.952 *953 * @param signer keyring of signer954 * @param collectionId ID of collection955 * @param ownerAddress substrate address of new owner956 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")957 * @returns ```true``` if extrinsic success, otherwise ```false```958 */959 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {960 const result = await this.helper.executeExtrinsic(961 signer,962 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],963 true,964 );965966 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');967 }968969 /**970 * Adds a collection administrator.971 *972 * @param signer keyring of signer973 * @param collectionId ID of collection974 * @param adminAddressObj Administrator address (substrate or ethereum)975 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})976 * @returns ```true``` if extrinsic success, otherwise ```false```977 */978 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {979 const result = await this.helper.executeExtrinsic(980 signer,981 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],982 true,983 );984985 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');986 }987988 /**989 * Removes a collection administrator.990 *991 * @param signer keyring of signer992 * @param collectionId ID of collection993 * @param adminAddressObj Administrator address (substrate or ethereum)994 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})995 * @returns ```true``` if extrinsic success, otherwise ```false```996 */997 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {998 const result = await this.helper.executeExtrinsic(999 signer,1000 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1001 true,1002 );10031004 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1005 }10061007 /**1008 * Check if user is in allow list.1009 *1010 * @param collectionId ID of collection1011 * @param user Account to check1012 * @example await getAdmins(1)1013 * @returns is user in allow list1014 */1015 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1016 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1017 }10181019 /**1020 * Adds an address to allow list1021 * @param signer keyring of signer1022 * @param collectionId ID of collection1023 * @param addressObj address to add to the allow list1024 * @returns ```true``` if extrinsic success, otherwise ```false```1025 */1026 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1027 const result = await this.helper.executeExtrinsic(1028 signer,1029 'api.tx.unique.addToAllowList', [collectionId, addressObj],1030 true,1031 );10321033 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1034 }10351036 /**1037 * Removes an address from allow list1038 *1039 * @param signer keyring of signer1040 * @param collectionId ID of collection1041 * @param addressObj address to remove from the allow list1042 * @returns ```true``` if extrinsic success, otherwise ```false```1043 */1044 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1045 const result = await this.helper.executeExtrinsic(1046 signer,1047 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1048 true,1049 );10501051 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1052 }10531054 /**1055 * Sets onchain permissions for selected collection.1056 *1057 * @param signer keyring of signer1058 * @param collectionId ID of collection1059 * @param permissions collection permissions object1060 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1061 * @returns ```true``` if extrinsic success, otherwise ```false```1062 */1063 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1064 const result = await this.helper.executeExtrinsic(1065 signer,1066 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1067 true,1068 );10691070 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1071 }10721073 /**1074 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1075 *1076 * @param signer keyring of signer1077 * @param collectionId ID of collection1078 * @param permissions nesting permissions object1079 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1080 * @returns ```true``` if extrinsic success, otherwise ```false```1081 */1082 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1083 return await this.setPermissions(signer, collectionId, {nesting: permissions});1084 }10851086 /**1087 * Disables nesting for selected collection.1088 *1089 * @param signer keyring of signer1090 * @param collectionId ID of collection1091 * @example disableNesting(aliceKeyring, 10);1092 * @returns ```true``` if extrinsic success, otherwise ```false```1093 */1094 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1095 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1096 }10971098 /**1099 * Sets onchain properties to the collection.1100 *1101 * @param signer keyring of signer1102 * @param collectionId ID of collection1103 * @param properties array of property objects1104 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1105 * @returns ```true``` if extrinsic success, otherwise ```false```1106 */1107 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1108 const result = await this.helper.executeExtrinsic(1109 signer,1110 'api.tx.unique.setCollectionProperties', [collectionId, properties],1111 true,1112 );11131114 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1115 }11161117 /**1118 * Get collection properties.1119 *1120 * @param collectionId ID of collection1121 * @param propertyKeys optionally filter the returned properties to only these keys1122 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1123 * @returns array of key-value pairs1124 */1125 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1126 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1127 }11281129 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1130 const api = this.helper.getApi();1131 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11321133 return (props! as any).consumedSpace;1134 }11351136 async getCollectionOptions(collectionId: number) {1137 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1138 }11391140 /**1141 * Deletes onchain properties from the collection.1142 *1143 * @param signer keyring of signer1144 * @param collectionId ID of collection1145 * @param propertyKeys array of property keys to delete1146 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1147 * @returns ```true``` if extrinsic success, otherwise ```false```1148 */1149 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1150 const result = await this.helper.executeExtrinsic(1151 signer,1152 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1153 true,1154 );11551156 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1157 }11581159 /**1160 * Changes the owner of the token.1161 *1162 * @param signer keyring of signer1163 * @param collectionId ID of collection1164 * @param tokenId ID of token1165 * @param addressObj address of a new owner1166 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1167 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1168 * @returns true if the token success, otherwise false1169 */1170 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1171 const result = await this.helper.executeExtrinsic(1172 signer,1173 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1174 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1175 );11761177 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1178 }11791180 /**1181 *1182 * Change ownership of a token(s) on behalf of the owner.1183 *1184 * @param signer keyring of signer1185 * @param collectionId ID of collection1186 * @param tokenId ID of token1187 * @param fromAddressObj address on behalf of which the token will be sent1188 * @param toAddressObj new token owner1189 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1190 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1191 * @returns true if the token success, otherwise false1192 */1193 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1194 const result = await this.helper.executeExtrinsic(1195 signer,1196 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1197 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1198 );1199 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1200 }12011202 /**1203 *1204 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1205 *1206 * @param signer keyring of signer1207 * @param collectionId ID of collection1208 * @param tokenId ID of token1209 * @param amount amount of tokens to be burned. For NFT must be set to 1n1210 * @example burnToken(aliceKeyring, 10, 5);1211 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1212 */1213 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1214 const burnResult = await this.helper.executeExtrinsic(1215 signer,1216 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1217 true, // `Unable to burn token for ${label}`,1218 );1219 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1220 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1221 return burnedTokens.success;1222 }12231224 /**1225 * Destroys a concrete instance of NFT on behalf of the owner1226 *1227 * @param signer keyring of signer1228 * @param collectionId ID of collection1229 * @param tokenId ID of token1230 * @param fromAddressObj address on behalf of which the token will be burnt1231 * @param amount amount of tokens to be burned. For NFT must be set to 1n1232 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1233 * @returns ```true``` if extrinsic success, otherwise ```false```1234 */1235 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1236 const burnResult = await this.helper.executeExtrinsic(1237 signer,1238 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1239 true, // `Unable to burn token from for ${label}`,1240 );1241 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1242 return burnedTokens.success && burnedTokens.tokens.length > 0;1243 }12441245 /**1246 * Set, change, or remove approved address to transfer the ownership of the NFT.1247 *1248 * @param signer keyring of signer1249 * @param collectionId ID of collection1250 * @param tokenId ID of token1251 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1252 * @param amount amount of token to be approved. For NFT must be set to 1n1253 * @returns ```true``` if extrinsic success, otherwise ```false```1254 */1255 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1256 const approveResult = await this.helper.executeExtrinsic(1257 signer,1258 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1259 true, // `Unable to approve token for ${label}`,1260 );12611262 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1263 }12641265 /**1266 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1267 *1268 * @param signer keyring of signer1269 * @param collectionId ID of collection1270 * @param tokenId ID of token1271 * @param fromAddressObj Signer's Ethereum address containing her tokens1272 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1273 * @param amount amount of token to be approved. For NFT must be set to 1n1274 * @returns ```true``` if extrinsic success, otherwise ```false```1275 */1276 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1277 const approveResult = await this.helper.executeExtrinsic(1278 signer,1279 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1280 true, // `Unable to approve token for ${label}`,1281 );12821283 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1284 }12851286 /**1287 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1288 *1289 * @param signer keyring of signer1290 * @param collectionId ID of collection1291 * @param tokenId ID of token1292 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1293 * @param amount amount of token to be approved. For NFT must be set to 1n1294 * @returns ```true``` if extrinsic success, otherwise ```false```1295 */1296 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1297 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1298 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1299 }13001301 /**1302 * Get the amount of token pieces approved to transfer or burn. Normally 0.1303 *1304 * @param collectionId ID of collection1305 * @param tokenId ID of token1306 * @param toAccountObj address which is approved to use token pieces1307 * @param fromAccountObj address which may have allowed the use of its owned tokens1308 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1309 * @returns number of approved to transfer pieces1310 */1311 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1312 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1313 }13141315 /**1316 * Get the last created token ID in a collection1317 *1318 * @param collectionId ID of collection1319 * @example getLastTokenId(10);1320 * @returns id of the last created token1321 */1322 async getLastTokenId(collectionId: number): Promise<number> {1323 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1324 }13251326 /**1327 * Check if token exists1328 *1329 * @param collectionId ID of collection1330 * @param tokenId ID of token1331 * @example doesTokenExist(10, 20);1332 * @returns true if the token exists, otherwise false1333 */1334 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1335 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1336 }1337}13381339class NFTnRFT extends CollectionGroup {1340 /**1341 * Get tokens owned by account1342 *1343 * @param collectionId ID of collection1344 * @param addressObj tokens owner1345 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1346 * @returns array of token ids owned by account1347 */1348 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1349 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1350 }13511352 /**1353 * Get token data1354 *1355 * @param collectionId ID of collection1356 * @param tokenId ID of token1357 * @param propertyKeys optionally filter the token properties to only these keys1358 * @param blockHashAt optionally query the data at some block with this hash1359 * @example getToken(10, 5);1360 * @returns human readable token data1361 */1362 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1363 properties: IProperty[];1364 owner: CrossAccountId;1365 normalizedOwner: CrossAccountId;1366 }| null> {1367 let tokenData;1368 if(typeof blockHashAt === 'undefined') {1369 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1370 }1371 else {1372 if(propertyKeys.length == 0) {1373 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1374 if(!collection) return null;1375 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1376 }1377 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1378 }1379 tokenData = tokenData.toHuman();1380 if (tokenData === null || tokenData.owner === null) return null;1381 const owner = {} as any;1382 for (const key of Object.keys(tokenData.owner)) {1383 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1384 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1385 : tokenData.owner[key];1386 }1387 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1388 return tokenData;1389 }13901391 /**1392 * Set permissions to change token properties1393 *1394 * @param signer keyring of signer1395 * @param collectionId ID of collection1396 * @param permissions permissions to change a property by the collection admin or token owner1397 * @example setTokenPropertyPermissions(1398 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1399 * )1400 * @returns true if extrinsic success otherwise false1401 */1402 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1403 const result = await this.helper.executeExtrinsic(1404 signer,1405 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1406 true,1407 );14081409 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1410 }14111412 /**1413 * Get token property permissions.1414 *1415 * @param collectionId ID of collection1416 * @param propertyKeys optionally filter the returned property permissions to only these keys1417 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1418 * @returns array of key-permission pairs1419 */1420 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1421 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1422 }14231424 /**1425 * Set token properties1426 *1427 * @param signer keyring of signer1428 * @param collectionId ID of collection1429 * @param tokenId ID of token1430 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1431 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1432 * @returns ```true``` if extrinsic success, otherwise ```false```1433 */1434 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1435 const result = await this.helper.executeExtrinsic(1436 signer,1437 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1438 true,1439 );14401441 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1442 }14431444 /**1445 * Get properties, metadata assigned to a token.1446 *1447 * @param collectionId ID of collection1448 * @param tokenId ID of token1449 * @param propertyKeys optionally filter the returned properties to only these keys1450 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1451 * @returns array of key-value pairs1452 */1453 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1454 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1455 }14561457 /**1458 * Delete the provided properties of a token1459 * @param signer keyring of signer1460 * @param collectionId ID of collection1461 * @param tokenId ID of token1462 * @param propertyKeys property keys to be deleted1463 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1464 * @returns ```true``` if extrinsic success, otherwise ```false```1465 */1466 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1467 const result = await this.helper.executeExtrinsic(1468 signer,1469 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1470 true,1471 );14721473 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1474 }14751476 /**1477 * Mint new collection1478 *1479 * @param signer keyring of signer1480 * @param collectionOptions basic collection options and properties1481 * @param mode NFT or RFT type of a collection1482 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1483 * @returns object of the created collection1484 */1485 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1486 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1487 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1488 for (const key of ['name', 'description', 'tokenPrefix']) {1489 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);1490 }1491 const creationResult = await this.helper.executeExtrinsic(1492 signer,1493 'api.tx.unique.createCollectionEx', [collectionOptions],1494 true, // errorLabel,1495 );1496 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1497 }14981499 getCollectionObject(_collectionId: number): any {1500 return null;1501 }15021503 getTokenObject(_collectionId: number, _tokenId: number): any {1504 return null;1505 }15061507 /**1508 * Tells whether the given `owner` approves the `operator`.1509 * @param collectionId ID of collection1510 * @param owner owner address1511 * @param operator operator addrees1512 * @returns true if operator is enabled1513 */1514 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1515 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1516 }15171518 /** Sets or unsets the approval of a given operator.1519 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1520 * @param operator Operator1521 * @param approved Should operator status be granted or revoked?1522 * @returns ```true``` if extrinsic success, otherwise ```false```1523 */1524 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1525 const result = await this.helper.executeExtrinsic(1526 signer,1527 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1528 true,1529 );1530 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1531 }1532}153315341535class NFTGroup extends NFTnRFT {1536 /**1537 * Get collection object1538 * @param collectionId ID of collection1539 * @example getCollectionObject(2);1540 * @returns instance of UniqueNFTCollection1541 */1542 getCollectionObject(collectionId: number): UniqueNFTCollection {1543 return new UniqueNFTCollection(collectionId, this.helper);1544 }15451546 /**1547 * Get token object1548 * @param collectionId ID of collection1549 * @param tokenId ID of token1550 * @example getTokenObject(10, 5);1551 * @returns instance of UniqueNFTToken1552 */1553 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1554 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1555 }15561557 /**1558 * Get token's owner1559 * @param collectionId ID of collection1560 * @param tokenId ID of token1561 * @param blockHashAt optionally query the data at the block with this hash1562 * @example getTokenOwner(10, 5);1563 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1564 */1565 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1566 let owner;1567 if (typeof blockHashAt === 'undefined') {1568 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1569 } else {1570 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1571 }1572 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1573 }15741575 /**1576 * Is token approved to transfer1577 * @param collectionId ID of collection1578 * @param tokenId ID of token1579 * @param toAccountObj address to be approved1580 * @returns ```true``` if extrinsic success, otherwise ```false```1581 */1582 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1583 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1584 }15851586 /**1587 * Changes the owner of the token.1588 *1589 * @param signer keyring of signer1590 * @param collectionId ID of collection1591 * @param tokenId ID of token1592 * @param addressObj address of a new owner1593 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1594 * @returns ```true``` if extrinsic success, otherwise ```false```1595 */1596 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1597 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1598 }15991600 /**1601 *1602 * Change ownership of a NFT on behalf of the owner.1603 *1604 * @param signer keyring of signer1605 * @param collectionId ID of collection1606 * @param tokenId ID of token1607 * @param fromAddressObj address on behalf of which the token will be sent1608 * @param toAddressObj new token owner1609 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1610 * @returns ```true``` if extrinsic success, otherwise ```false```1611 */1612 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1613 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1614 }16151616 /**1617 * Recursively find the address that owns the token1618 * @param collectionId ID of collection1619 * @param tokenId ID of token1620 * @param blockHashAt1621 * @example getTokenTopmostOwner(10, 5);1622 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1623 */1624 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1625 let owner;1626 if (typeof blockHashAt === 'undefined') {1627 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1628 } else {1629 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1630 }16311632 if (owner === null) return null;16331634 return owner.toHuman();1635 }16361637 /**1638 * Get tokens nested in the provided token1639 * @param collectionId ID of collection1640 * @param tokenId ID of token1641 * @param blockHashAt optionally query the data at the block with this hash1642 * @example getTokenChildren(10, 5);1643 * @returns tokens whose depth of nesting is <= 51644 */1645 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1646 let children;1647 if(typeof blockHashAt === 'undefined') {1648 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1649 } else {1650 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1651 }16521653 return children.toJSON().map((x: any) => {1654 return {collectionId: x.collection, tokenId: x.token};1655 });1656 }16571658 /**1659 * Nest one token into another1660 * @param signer keyring of signer1661 * @param tokenObj token to be nested1662 * @param rootTokenObj token to be parent1663 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1664 * @returns ```true``` if extrinsic success, otherwise ```false```1665 */1666 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1667 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1668 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1669 if(!result) {1670 throw Error('Unable to nest token!');1671 }1672 return result;1673 }16741675 /**1676 * Remove token from nested state1677 * @param signer keyring of signer1678 * @param tokenObj token to unnest1679 * @param rootTokenObj parent of a token1680 * @param toAddressObj address of a new token owner1681 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1682 * @returns ```true``` if extrinsic success, otherwise ```false```1683 */1684 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1685 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1686 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1687 if(!result) {1688 throw Error('Unable to unnest token!');1689 }1690 return result;1691 }16921693 /**1694 * Mint new collection1695 * @param signer keyring of signer1696 * @param collectionOptions Collection options1697 * @example1698 * mintCollection(aliceKeyring, {1699 * name: 'New',1700 * description: 'New collection',1701 * tokenPrefix: 'NEW',1702 * })1703 * @returns object of the created collection1704 */1705 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1706 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1707 }17081709 /**1710 * Mint new token1711 * @param signer keyring of signer1712 * @param data token data1713 * @returns created token object1714 */1715 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1716 const creationResult = await this.helper.executeExtrinsic(1717 signer,1718 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1719 nft: {1720 properties: data.properties,1721 },1722 }],1723 true,1724 );1725 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1726 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1727 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1728 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1729 }17301731 /**1732 * Mint multiple NFT tokens1733 * @param signer keyring of signer1734 * @param collectionId ID of collection1735 * @param tokens array of tokens with owner and properties1736 * @example1737 * mintMultipleTokens(aliceKeyring, 10, [{1738 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1739 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1740 * },{1741 * owner: {Ethereum: "0x9F0583DbB855d..."},1742 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1743 * }]);1744 * @returns ```true``` if extrinsic success, otherwise ```false```1745 */1746 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1747 const creationResult = await this.helper.executeExtrinsic(1748 signer,1749 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1750 true,1751 );1752 const collection = this.getCollectionObject(collectionId);1753 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1754 }17551756 /**1757 * Mint multiple NFT tokens with one owner1758 * @param signer keyring of signer1759 * @param collectionId ID of collection1760 * @param owner tokens owner1761 * @param tokens array of tokens with owner and properties1762 * @example1763 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1764 * properties: [{1765 * key: "gender",1766 * value: "female",1767 * },{1768 * key: "age",1769 * value: "33",1770 * }],1771 * }]);1772 * @returns array of newly created tokens1773 */1774 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1775 const rawTokens = [];1776 for (const token of tokens) {1777 const raw = {NFT: {properties: token.properties}};1778 rawTokens.push(raw);1779 }1780 const creationResult = await this.helper.executeExtrinsic(1781 signer,1782 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1783 true,1784 );1785 const collection = this.getCollectionObject(collectionId);1786 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1787 }17881789 /**1790 * Set, change, or remove approved address to transfer the ownership of the NFT.1791 *1792 * @param signer keyring of signer1793 * @param collectionId ID of collection1794 * @param tokenId ID of token1795 * @param toAddressObj address to approve1796 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1797 * @returns ```true``` if extrinsic success, otherwise ```false```1798 */1799 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1800 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1801 }1802}180318041805class RFTGroup extends NFTnRFT {1806 /**1807 * Get collection object1808 * @param collectionId ID of collection1809 * @example getCollectionObject(2);1810 * @returns instance of UniqueRFTCollection1811 */1812 getCollectionObject(collectionId: number): UniqueRFTCollection {1813 return new UniqueRFTCollection(collectionId, this.helper);1814 }18151816 /**1817 * Get token object1818 * @param collectionId ID of collection1819 * @param tokenId ID of token1820 * @example getTokenObject(10, 5);1821 * @returns instance of UniqueNFTToken1822 */1823 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1824 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1825 }18261827 /**1828 * Get top 10 token owners with the largest number of pieces1829 * @param collectionId ID of collection1830 * @param tokenId ID of token1831 * @example getTokenTop10Owners(10, 5);1832 * @returns array of top 10 owners1833 */1834 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1835 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1836 }18371838 /**1839 * Get number of pieces owned by address1840 * @param collectionId ID of collection1841 * @param tokenId ID of token1842 * @param addressObj address token owner1843 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1844 * @returns number of pieces ownerd by address1845 */1846 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1847 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1848 }18491850 /**1851 * Transfer pieces of token to another address1852 * @param signer keyring of signer1853 * @param collectionId ID of collection1854 * @param tokenId ID of token1855 * @param addressObj address of a new owner1856 * @param amount number of pieces to be transfered1857 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1858 * @returns ```true``` if extrinsic success, otherwise ```false```1859 */1860 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1861 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1862 }18631864 /**1865 * Change ownership of some pieces of RFT on behalf of the owner.1866 * @param signer keyring of signer1867 * @param collectionId ID of collection1868 * @param tokenId ID of token1869 * @param fromAddressObj address on behalf of which the token will be sent1870 * @param toAddressObj new token owner1871 * @param amount number of pieces to be transfered1872 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1873 * @returns ```true``` if extrinsic success, otherwise ```false```1874 */1875 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1876 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1877 }18781879 /**1880 * Mint new collection1881 * @param signer keyring of signer1882 * @param collectionOptions Collection options1883 * @example1884 * mintCollection(aliceKeyring, {1885 * name: 'New',1886 * description: 'New collection',1887 * tokenPrefix: 'NEW',1888 * })1889 * @returns object of the created collection1890 */1891 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1892 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1893 }18941895 /**1896 * Mint new token1897 * @param signer keyring of signer1898 * @param data token data1899 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1900 * @returns created token object1901 */1902 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1903 const creationResult = await this.helper.executeExtrinsic(1904 signer,1905 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1906 refungible: {1907 pieces: data.pieces,1908 properties: data.properties,1909 },1910 }],1911 true,1912 );1913 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1914 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1915 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1916 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1917 }19181919 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1920 throw Error('Not implemented');1921 const creationResult = await this.helper.executeExtrinsic(1922 signer,1923 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1924 true, // `Unable to mint RFT tokens for ${label}`,1925 );1926 const collection = this.getCollectionObject(collectionId);1927 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1928 }19291930 /**1931 * Mint multiple RFT tokens with one owner1932 * @param signer keyring of signer1933 * @param collectionId ID of collection1934 * @param owner tokens owner1935 * @param tokens array of tokens with properties and pieces1936 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1937 * @returns array of newly created RFT tokens1938 */1939 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1940 const rawTokens = [];1941 for (const token of tokens) {1942 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1943 rawTokens.push(raw);1944 }1945 const creationResult = await this.helper.executeExtrinsic(1946 signer,1947 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1948 true,1949 );1950 const collection = this.getCollectionObject(collectionId);1951 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1952 }19531954 /**1955 * Destroys a concrete instance of RFT.1956 * @param signer keyring of signer1957 * @param collectionId ID of collection1958 * @param tokenId ID of token1959 * @param amount number of pieces to be burnt1960 * @example burnToken(aliceKeyring, 10, 5);1961 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1962 */1963 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1964 return await super.burnToken(signer, collectionId, tokenId, amount);1965 }19661967 /**1968 * Destroys a concrete instance of RFT on behalf of the owner.1969 * @param signer keyring of signer1970 * @param collectionId ID of collection1971 * @param tokenId ID of token1972 * @param fromAddressObj address on behalf of which the token will be burnt1973 * @param amount number of pieces to be burnt1974 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1975 * @returns ```true``` if extrinsic success, otherwise ```false```1976 */1977 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1978 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1979 }19801981 /**1982 * Set, change, or remove approved address to transfer the ownership of the RFT.1983 *1984 * @param signer keyring of signer1985 * @param collectionId ID of collection1986 * @param tokenId ID of token1987 * @param toAddressObj address to approve1988 * @param amount number of pieces to be approved1989 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1990 * @returns true if the token success, otherwise false1991 */1992 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1993 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1994 }19951996 /**1997 * Get total number of pieces1998 * @param collectionId ID of collection1999 * @param tokenId ID of token2000 * @example getTokenTotalPieces(10, 5);2001 * @returns number of pieces2002 */2003 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2004 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2005 }20062007 /**2008 * Change number of token pieces. Signer must be the owner of all token pieces.2009 * @param signer keyring of signer2010 * @param collectionId ID of collection2011 * @param tokenId ID of token2012 * @param amount new number of pieces2013 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2014 * @returns true if the repartion was success, otherwise false2015 */2016 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2017 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2018 const repartitionResult = await this.helper.executeExtrinsic(2019 signer,2020 'api.tx.unique.repartition', [collectionId, tokenId, amount],2021 true,2022 );2023 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2024 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2025 }2026}202720282029class FTGroup extends CollectionGroup {2030 /**2031 * Get collection object2032 * @param collectionId ID of collection2033 * @example getCollectionObject(2);2034 * @returns instance of UniqueFTCollection2035 */2036 getCollectionObject(collectionId: number): UniqueFTCollection {2037 return new UniqueFTCollection(collectionId, this.helper);2038 }20392040 /**2041 * Mint new fungible collection2042 * @param signer keyring of signer2043 * @param collectionOptions Collection options2044 * @param decimalPoints number of token decimals2045 * @example2046 * mintCollection(aliceKeyring, {2047 * name: 'New',2048 * description: 'New collection',2049 * tokenPrefix: 'NEW',2050 * }, 18)2051 * @returns newly created fungible collection2052 */2053 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2054 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2055 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2056 collectionOptions.mode = {fungible: decimalPoints};2057 for (const key of ['name', 'description', 'tokenPrefix']) {2058 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);2059 }2060 const creationResult = await this.helper.executeExtrinsic(2061 signer,2062 'api.tx.unique.createCollectionEx', [collectionOptions],2063 true,2064 );2065 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2066 }20672068 /**2069 * Mint tokens2070 * @param signer keyring of signer2071 * @param collectionId ID of collection2072 * @param owner address owner of new tokens2073 * @param amount amount of tokens to be meanted2074 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2075 * @returns ```true``` if extrinsic success, otherwise ```false```2076 */2077 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2078 const creationResult = await this.helper.executeExtrinsic(2079 signer,2080 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2081 fungible: {2082 value: amount,2083 },2084 }],2085 true, // `Unable to mint fungible tokens for ${label}`,2086 );2087 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2088 }20892090 /**2091 * Mint multiple Fungible tokens with one owner2092 * @param signer keyring of signer2093 * @param collectionId ID of collection2094 * @param owner tokens owner2095 * @param tokens array of tokens with properties and pieces2096 * @returns ```true``` if extrinsic success, otherwise ```false```2097 */2098 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2099 const rawTokens = [];2100 for (const token of tokens) {2101 const raw = {Fungible: {Value: token.value}};2102 rawTokens.push(raw);2103 }2104 const creationResult = await this.helper.executeExtrinsic(2105 signer,2106 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2107 true,2108 );2109 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2110 }21112112 /**2113 * Get the top 10 owners with the largest balance for the Fungible collection2114 * @param collectionId ID of collection2115 * @example getTop10Owners(10);2116 * @returns array of ```ICrossAccountId```2117 */2118 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2119 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2120 }21212122 /**2123 * Get account balance2124 * @param collectionId ID of collection2125 * @param addressObj address of owner2126 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2127 * @returns amount of fungible tokens owned by address2128 */2129 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2130 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2131 }21322133 /**2134 * Transfer tokens to address2135 * @param signer keyring of signer2136 * @param collectionId ID of collection2137 * @param toAddressObj address recipient2138 * @param amount amount of tokens to be sent2139 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2140 * @returns ```true``` if extrinsic success, otherwise ```false```2141 */2142 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2143 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2144 }21452146 /**2147 * Transfer some tokens on behalf of the owner.2148 * @param signer keyring of signer2149 * @param collectionId ID of collection2150 * @param fromAddressObj address on behalf of which tokens will be sent2151 * @param toAddressObj address where token to be sent2152 * @param amount number of tokens to be sent2153 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2154 * @returns ```true``` if extrinsic success, otherwise ```false```2155 */2156 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2157 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2158 }21592160 /**2161 * Destroy some amount of tokens2162 * @param signer keyring of signer2163 * @param collectionId ID of collection2164 * @param amount amount of tokens to be destroyed2165 * @example burnTokens(aliceKeyring, 10, 1000n);2166 * @returns ```true``` if extrinsic success, otherwise ```false```2167 */2168 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2169 return await super.burnToken(signer, collectionId, 0, amount);2170 }21712172 /**2173 * Burn some tokens on behalf of the owner.2174 * @param signer keyring of signer2175 * @param collectionId ID of collection2176 * @param fromAddressObj address on behalf of which tokens will be burnt2177 * @param amount amount of tokens to be burnt2178 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2179 * @returns ```true``` if extrinsic success, otherwise ```false```2180 */2181 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2182 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2183 }21842185 /**2186 * Get total collection supply2187 * @param collectionId2188 * @returns2189 */2190 async getTotalPieces(collectionId: number): Promise<bigint> {2191 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2192 }21932194 /**2195 * Set, change, or remove approved address to transfer tokens.2196 *2197 * @param signer keyring of signer2198 * @param collectionId ID of collection2199 * @param toAddressObj address to be approved2200 * @param amount amount of tokens to be approved2201 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2202 * @returns ```true``` if extrinsic success, otherwise ```false```2203 */2204 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2205 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2206 }22072208 /**2209 * Get amount of fungible tokens approved to transfer2210 * @param collectionId ID of collection2211 * @param fromAddressObj owner of tokens2212 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2213 * @returns number of tokens approved for the transfer2214 */2215 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2216 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2217 }2218}221922202221class ChainGroup extends HelperGroup<ChainHelperBase> {2222 /**2223 * Get system properties of a chain2224 * @example getChainProperties();2225 * @returns ss58Format, token decimals, and token symbol2226 */2227 getChainProperties(): IChainProperties {2228 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2229 return {2230 ss58Format: properties.ss58Format.toJSON(),2231 tokenDecimals: properties.tokenDecimals.toJSON(),2232 tokenSymbol: properties.tokenSymbol.toJSON(),2233 };2234 }22352236 /**2237 * Get chain header2238 * @example getLatestBlockNumber();2239 * @returns the number of the last block2240 */2241 async getLatestBlockNumber(): Promise<number> {2242 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2243 }22442245 /**2246 * Get block hash by block number2247 * @param blockNumber number of block2248 * @example getBlockHashByNumber(12345);2249 * @returns hash of a block2250 */2251 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2252 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2253 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2254 return blockHash;2255 }22562257 // TODO add docs2258 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2259 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2260 if (!blockHash) return null;2261 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2262 }22632264 /**2265 * Get latest relay block2266 * @returns {number} relay block2267 */2268 async getRelayBlockNumber(): Promise<bigint> {2269 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2270 return BigInt(blockNumber);2271 }22722273 /**2274 * Get account nonce2275 * @param address substrate address2276 * @example getNonce("5GrwvaEF5zXb26Fz...");2277 * @returns number, account's nonce2278 */2279 async getNonce(address: TSubstrateAccount): Promise<number> {2280 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2281 }2282}22832284class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2285 /**2286 * Get substrate address balance2287 * @param address substrate address2288 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2289 * @returns amount of tokens on address2290 */2291 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2292 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2293 }22942295 /**2296 * Transfer tokens to substrate address2297 * @param signer keyring of signer2298 * @param address substrate address of a recipient2299 * @param amount amount of tokens to be transfered2300 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2301 * @returns ```true``` if extrinsic success, otherwise ```false```2302 */2303 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2304 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}`*/);23052306 let transfer = {from: null, to: null, amount: 0n} as any;2307 result.result.events.forEach(({event: {data, method, section}}) => {2308 if ((section === 'balances') && (method === 'Transfer')) {2309 transfer = {2310 from: this.helper.address.normalizeSubstrate(data[0]),2311 to: this.helper.address.normalizeSubstrate(data[1]),2312 amount: BigInt(data[2]),2313 };2314 }2315 });2316 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2317 && this.helper.address.normalizeSubstrate(address) === transfer.to2318 && BigInt(amount) === transfer.amount;2319 return isSuccess;2320 }23212322 /**2323 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2324 * @param address substrate address2325 * @returns2326 */2327 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2328 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2329 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2330 }23312332 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2333 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2334 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2335 }2336}23372338class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2339 /**2340 * Get ethereum address balance2341 * @param address ethereum address2342 * @example getEthereum("0x9F0583DbB855d...")2343 * @returns amount of tokens on address2344 */2345 async getEthereum(address: TEthereumAccount): Promise<bigint> {2346 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2347 }23482349 /**2350 * Transfer tokens to address2351 * @param signer keyring of signer2352 * @param address Ethereum address of a recipient2353 * @param amount amount of tokens to be transfered2354 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2355 * @returns ```true``` if extrinsic success, otherwise ```false```2356 */2357 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2358 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23592360 let transfer = {from: null, to: null, amount: 0n} as any;2361 result.result.events.forEach(({event: {data, method, section}}) => {2362 if ((section === 'balances') && (method === 'Transfer')) {2363 transfer = {2364 from: data[0].toString(),2365 to: data[1].toString(),2366 amount: BigInt(data[2]),2367 };2368 }2369 });2370 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2371 && address === transfer.to2372 && BigInt(amount) === transfer.amount;2373 return isSuccess;2374 }2375}23762377class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2378 subBalanceGroup: SubstrateBalanceGroup<T>;2379 ethBalanceGroup: EthereumBalanceGroup<T>;23802381 constructor(helper: T) {2382 super(helper);2383 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2384 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2385 }23862387 getCollectionCreationPrice(): bigint {2388 return 2n * this.getOneTokenNominal();2389 }2390 /**2391 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2392 * @example getOneTokenNominal()2393 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2394 */2395 getOneTokenNominal(): bigint {2396 const chainProperties = this.helper.chain.getChainProperties();2397 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2398 }23992400 /**2401 * Get substrate address balance2402 * @param address substrate address2403 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2404 * @returns amount of tokens on address2405 */2406 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2407 return this.subBalanceGroup.getSubstrate(address);2408 }24092410 /**2411 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2412 * @param address substrate address2413 * @returns2414 */2415 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2416 return this.subBalanceGroup.getSubstrateFull(address);2417 }24182419 /**2420 * Get locked balances2421 * @param address substrate address2422 * @returns locked balances with reason via api.query.balances.locks2423 */2424 getLocked(address: TSubstrateAccount) {2425 return this.subBalanceGroup.getLocked(address);2426 }24272428 /**2429 * Get ethereum address balance2430 * @param address ethereum address2431 * @example getEthereum("0x9F0583DbB855d...")2432 * @returns amount of tokens on address2433 */2434 getEthereum(address: TEthereumAccount): Promise<bigint> {2435 return this.ethBalanceGroup.getEthereum(address);2436 }24372438 /**2439 * Transfer tokens to substrate address2440 * @param signer keyring of signer2441 * @param address substrate address of a recipient2442 * @param amount amount of tokens to be transfered2443 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2444 * @returns ```true``` if extrinsic success, otherwise ```false```2445 */2446 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2447 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2448 }24492450 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2451 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24522453 let transfer = {from: null, to: null, amount: 0n} as any;2454 result.result.events.forEach(({event: {data, method, section}}) => {2455 if ((section === 'balances') && (method === 'Transfer')) {2456 transfer = {2457 from: this.helper.address.normalizeSubstrate(data[0]),2458 to: this.helper.address.normalizeSubstrate(data[1]),2459 amount: BigInt(data[2]),2460 };2461 }2462 });2463 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2464 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2465 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2466 return isSuccess;2467 }24682469 /**2470 * Transfer tokens with the unlock period2471 * @param signer signers Keyring2472 * @param address Substrate address of recipient2473 * @param schedule Schedule params2474 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002475 */2476 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2477 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2478 const event = result.result.events2479 .find(e => e.event.section === 'vesting' &&2480 e.event.method === 'VestingScheduleAdded' &&2481 e.event.data[0].toHuman() === signer.address);2482 if (!event) throw Error('Cannot find transfer in events');2483 }24842485 /**2486 * Get schedule for recepient of vested transfer2487 * @param address Substrate address of recipient2488 * @returns2489 */2490 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2491 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2492 return schedule.map((schedule: any) => {2493 return {2494 start: BigInt(schedule.start),2495 period: BigInt(schedule.period),2496 periodCount: BigInt(schedule.periodCount),2497 perPeriod: BigInt(schedule.perPeriod),2498 };2499 });2500 }25012502 /**2503 * Claim vested tokens2504 * @param signer signers Keyring2505 */2506 async claim(signer: TSigner) {2507 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2508 const event = result.result.events2509 .find(e => e.event.section === 'vesting' &&2510 e.event.method === 'Claimed' &&2511 e.event.data[0].toHuman() === signer.address);2512 if (!event) throw Error('Cannot find claim in events');2513 }2514}25152516class AddressGroup extends HelperGroup<ChainHelperBase> {2517 /**2518 * Normalizes the address to the specified ss58 format, by default ```42```.2519 * @param address substrate address2520 * @param ss58Format format for address conversion, by default ```42```2521 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2522 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2523 */2524 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2525 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2526 }25272528 /**2529 * Get address in the connected chain format2530 * @param address substrate address2531 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2532 * @returns address in chain format2533 */2534 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2535 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2536 }25372538 /**2539 * Get substrate mirror of an ethereum address2540 * @param ethAddress ethereum address2541 * @param toChainFormat false for normalized account2542 * @example ethToSubstrate('0x9F0583DbB855d...')2543 * @returns substrate mirror of a provided ethereum address2544 */2545 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2546 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2547 }25482549 /**2550 * Get ethereum mirror of a substrate address2551 * @param subAddress substrate account2552 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2553 * @returns ethereum mirror of a provided substrate address2554 */2555 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2556 return CrossAccountId.translateSubToEth(subAddress);2557 }25582559 /**2560 * Encode key to substrate address2561 * @param key key for encoding address2562 * @param ss58Format prefix for encoding to the address of the corresponding network2563 * @returns encoded substrate address2564 */2565 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2566 const u8a :Uint8Array = typeof key === 'string'2567 ? hexToU8a(key)2568 : typeof key === 'bigint'2569 ? hexToU8a(key.toString(16))2570 : key;25712572 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2573 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2574 }25752576 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2577 if (!allowedDecodedLengths.includes(u8a.length)) {2578 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2579 }25802581 const u8aPrefix = ss58Format < 642582 ? new Uint8Array([ss58Format])2583 : new Uint8Array([2584 ((ss58Format & 0xfc) >> 2) | 0x40,2585 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2586 ]);25872588 const input = u8aConcat(u8aPrefix, u8a);25892590 return base58Encode(u8aConcat(2591 input,2592 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2593 ));2594 }25952596 /**2597 * Restore substrate address from bigint representation2598 * @param number decimal representation of substrate address2599 * @returns substrate address2600 */2601 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2602 if (this.helper.api === null) {2603 throw 'Not connected';2604 }2605 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2606 if (res === undefined || res === null) {2607 throw 'Restore address error';2608 }2609 return res.toString();2610 }26112612 /**2613 * Convert etherium cross account id to substrate cross account id2614 * @param ethCrossAccount etherium cross account2615 * @returns substrate cross account id2616 */2617 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2618 if (ethCrossAccount.sub === '0') {2619 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2620 }26212622 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2623 return {Substrate: ss58};2624 }26252626 paraSiblingSovereignAccount(paraid: number) {2627 // We are getting a *sibling* parachain sovereign account,2628 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2629 const siblingPrefix = '0x7369626c';26302631 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2632 const suffix = '000000000000000000000000000000000000000000000000';26332634 return siblingPrefix + encodedParaId + suffix;2635 }2636}26372638class StakingGroup extends HelperGroup<UniqueHelper> {2639 /**2640 * Stake tokens for App Promotion2641 * @param signer keyring of signer2642 * @param amountToStake amount of tokens to stake2643 * @param label extra label for log2644 * @returns2645 */2646 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2647 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2648 const _stakeResult = await this.helper.executeExtrinsic(2649 signer, 'api.tx.appPromotion.stake',2650 [amountToStake], true,2651 );2652 // TODO extract info from stakeResult2653 return true;2654 }26552656 /**2657 * Unstake tokens for App Promotion2658 * @param signer keyring of signer2659 * @param amountToUnstake amount of tokens to unstake2660 * @param label extra label for log2661 * @returns block number where balances will be unlocked2662 */2663 async unstake(signer: TSigner, label?: string): Promise<number> {2664 if(typeof label === 'undefined') label = `${signer.address}`;2665 const _unstakeResult = await this.helper.executeExtrinsic(2666 signer, 'api.tx.appPromotion.unstake',2667 [], true,2668 );2669 // TODO extract block number fron events2670 return 1;2671 }26722673 /**2674 * Get total staked amount for address2675 * @param address substrate or ethereum address2676 * @returns total staked amount2677 */2678 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2679 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2680 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2681 }26822683 /**2684 * Get total staked per block2685 * @param address substrate or ethereum address2686 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2687 */2688 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2689 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2690 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2691 return {2692 block: block.toBigInt(),2693 amount: amount.toBigInt(),2694 };2695 });2696 }26972698 /**2699 * Get total pending unstake amount for address2700 * @param address substrate or ethereum address2701 * @returns total pending unstake amount2702 */2703 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2704 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2705 }27062707 /**2708 * Get pending unstake amount per block for address2709 * @param address substrate or ethereum address2710 * @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 block2711 */2712 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2713 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2714 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2715 return {2716 block: block.toBigInt(),2717 amount: amount.toBigInt(),2718 };2719 });2720 return result;2721 }2722}27232724class SchedulerGroup extends HelperGroup<UniqueHelper> {2725 constructor(helper: UniqueHelper) {2726 super(helper);2727 }27282729 cancelScheduled(signer: TSigner, scheduledId: string) {2730 return this.helper.executeExtrinsic(2731 signer,2732 'api.tx.scheduler.cancelNamed',2733 [scheduledId],2734 true,2735 );2736 }27372738 changePriority(signer: TSigner, scheduledId: string, priority: number) {2739 return this.helper.executeExtrinsic(2740 signer,2741 'api.tx.scheduler.changeNamedPriority',2742 [scheduledId, priority],2743 true,2744 );2745 }27462747 scheduleAt<T extends UniqueHelper>(2748 executionBlockNumber: number,2749 options: ISchedulerOptions = {},2750 ) {2751 return this.schedule<T>('schedule', executionBlockNumber, options);2752 }27532754 scheduleAfter<T extends UniqueHelper>(2755 blocksBeforeExecution: number,2756 options: ISchedulerOptions = {},2757 ) {2758 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2759 }27602761 schedule<T extends UniqueHelper>(2762 scheduleFn: 'schedule' | 'scheduleAfter',2763 blocksNum: number,2764 options: ISchedulerOptions = {},2765 ) {2766 // eslint-disable-next-line @typescript-eslint/naming-convention2767 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2768 return this.helper.clone(ScheduledHelperType, {2769 scheduleFn,2770 blocksNum,2771 options,2772 }) as T;2773 }2774}27752776class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2777 //todo:collator documentation2778 addInvulnerable(signer: TSigner, address: string) {2779 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2780 }27812782 removeInvulnerable(signer: TSigner, address: string) {2783 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2784 }27852786 async getInvulnerables(): Promise<string[]> {2787 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2788 }27892790 /** and also total max invulnerables */2791 maxCollators(): number {2792 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2793 }27942795 async getDesiredCollators(): Promise<number> {2796 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2797 }27982799 setLicenseBond(signer: TSigner, amount: bigint) {2800 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2801 }28022803 async getLicenseBond(): Promise<bigint> {2804 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2805 }28062807 obtainLicense(signer: TSigner) {2808 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2809 }28102811 releaseLicense(signer: TSigner) {2812 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2813 }28142815 forceReleaseLicense(signer: TSigner, released: string) {2816 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2817 }28182819 async hasLicense(address: string): Promise<bigint> {2820 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2821 }28222823 onboard(signer: TSigner) {2824 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2825 }28262827 offboard(signer: TSigner) {2828 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2829 }28302831 async getCandidates(): Promise<string[]> {2832 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2833 }2834}28352836class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2837 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2838 await this.helper.executeExtrinsic(2839 signer,2840 'api.tx.foreignAssets.registerForeignAsset',2841 [ownerAddress, location, metadata],2842 true,2843 );2844 }28452846 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2847 await this.helper.executeExtrinsic(2848 signer,2849 'api.tx.foreignAssets.updateForeignAsset',2850 [foreignAssetId, location, metadata],2851 true,2852 );2853 }2854}28552856class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2857 palletName: string;28582859 constructor(helper: T, palletName: string) {2860 super(helper);28612862 this.palletName = palletName;2863 }28642865 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2866 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2867 }28682869 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2870 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2871 }28722873 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2874 const destination = {2875 V1: {2876 parents: 0,2877 interior: {2878 X1: {2879 Parachain: destinationParaId,2880 },2881 },2882 },2883 };28842885 const beneficiary = {2886 V1: {2887 parents: 0,2888 interior: {2889 X1: {2890 AccountId32: {2891 network: 'Any',2892 id: targetAccount,2893 },2894 },2895 },2896 },2897 };28982899 const assets = {2900 V1: [2901 {2902 id: {2903 Concrete: {2904 parents: 0,2905 interior: 'Here',2906 },2907 },2908 fun: {2909 Fungible: amount,2910 },2911 },2912 ],2913 };29142915 const feeAssetItem = 0;29162917 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2918 }2919}29202921class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2922 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2923 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2924 }29252926 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2927 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2928 }29292930 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2931 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2932 }2933}29342935class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2936 async accounts(address: string, currencyId: any) {2937 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2938 return BigInt(free);2939 }2940}29412942class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2943 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2944 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2945 }29462947 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2948 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2949 }29502951 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2952 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2953 }29542955 async account(assetId: string | number, address: string) {2956 const accountAsset = (2957 await this.helper.callRpc('api.query.assets.account', [assetId, address])2958 ).toJSON()! as any;29592960 if (accountAsset !== null) {2961 return BigInt(accountAsset['balance']);2962 } else {2963 return null;2964 }2965 }2966}29672968class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2969 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2970 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2971 }2972}29732974class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2975 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2976 const apiPrefix = 'api.tx.assetManager.';29772978 const registerTx = this.helper.constructApiCall(2979 apiPrefix + 'registerForeignAsset',2980 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2981 );29822983 const setUnitsTx = this.helper.constructApiCall(2984 apiPrefix + 'setAssetUnitsPerSecond',2985 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2986 );29872988 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2989 const encodedProposal = batchCall?.method.toHex() || '';2990 return encodedProposal;2991 }29922993 async assetTypeId(location: any) {2994 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2995 }2996}29972998class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2999 notePreimagePallet: string;30003001 constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3002 super(helper);3003 this.notePreimagePallet = options.notePreimagePallet;3004 }30053006 async notePreimage(signer: TSigner, encodedProposal: string) {3007 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3008 }30093010 externalProposeMajority(proposal: any) {3011 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3012 }30133014 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3015 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3016 }30173018 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3019 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3020 }3021}30223023class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3024 collective: string;30253026 constructor(helper: MoonbeamHelper, collective: string) {3027 super(helper);30283029 this.collective = collective;3030 }30313032 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3033 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3034 }30353036 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3037 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3038 }30393040 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3041 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3042 }30433044 async proposalCount() {3045 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3046 }3047}30483049export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3050export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;30513052export class UniqueHelper extends ChainHelperBase {3053 balance: BalanceGroup<UniqueHelper>;3054 collection: CollectionGroup;3055 nft: NFTGroup;3056 rft: RFTGroup;3057 ft: FTGroup;3058 staking: StakingGroup;3059 scheduler: SchedulerGroup;3060 collatorSelection: CollatorSelectionGroup;3061 foreignAssets: ForeignAssetsGroup;3062 xcm: XcmGroup<UniqueHelper>;3063 xTokens: XTokensGroup<UniqueHelper>;3064 tokens: TokensGroup<UniqueHelper>;30653066 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3067 super(logger, options.helperBase ?? UniqueHelper);30683069 this.balance = new BalanceGroup(this);3070 this.collection = new CollectionGroup(this);3071 this.nft = new NFTGroup(this);3072 this.rft = new RFTGroup(this);3073 this.ft = new FTGroup(this);3074 this.staking = new StakingGroup(this);3075 this.scheduler = new SchedulerGroup(this);3076 this.collatorSelection = new CollatorSelectionGroup(this);3077 this.foreignAssets = new ForeignAssetsGroup(this);3078 this.xcm = new XcmGroup(this, 'polkadotXcm');3079 this.xTokens = new XTokensGroup(this);3080 this.tokens = new TokensGroup(this);3081 }30823083 getSudo<T extends UniqueHelper>() {3084 // eslint-disable-next-line @typescript-eslint/naming-convention3085 const SudoHelperType = SudoHelper(this.helperBase);3086 return this.clone(SudoHelperType) as T;3087 }3088}30893090export class XcmChainHelper extends ChainHelperBase {3091 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3092 const wsProvider = new WsProvider(wsEndpoint);3093 this.api = new ApiPromise({3094 provider: wsProvider,3095 });3096 await this.api.isReadyOrError;3097 this.network = await UniqueHelper.detectNetwork(this.api);3098 }3099}31003101export class RelayHelper extends XcmChainHelper {3102 balance: SubstrateBalanceGroup<RelayHelper>;3103 xcm: XcmGroup<RelayHelper>;31043105 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3106 super(logger, options.helperBase ?? RelayHelper);31073108 this.balance = new SubstrateBalanceGroup(this);3109 this.xcm = new XcmGroup(this, 'xcmPallet');3110 }3111}31123113export class WestmintHelper extends XcmChainHelper {3114 balance: SubstrateBalanceGroup<WestmintHelper>;3115 xcm: XcmGroup<WestmintHelper>;3116 assets: AssetsGroup<WestmintHelper>;3117 xTokens: XTokensGroup<WestmintHelper>;31183119 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3120 super(logger, options.helperBase ?? WestmintHelper);31213122 this.balance = new SubstrateBalanceGroup(this);3123 this.xcm = new XcmGroup(this, 'polkadotXcm');3124 this.assets = new AssetsGroup(this);3125 this.xTokens = new XTokensGroup(this);3126 }3127}31283129export class MoonbeamHelper extends XcmChainHelper {3130 balance: EthereumBalanceGroup<MoonbeamHelper>;3131 assetManager: MoonbeamAssetManagerGroup;3132 assets: AssetsGroup<MoonbeamHelper>;3133 xTokens: XTokensGroup<MoonbeamHelper>;3134 democracy: MoonbeamDemocracyGroup;3135 collective: {3136 council: MoonbeamCollectiveGroup,3137 techCommittee: MoonbeamCollectiveGroup,3138 };31393140 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3141 super(logger, options.helperBase ?? MoonbeamHelper);31423143 this.balance = new EthereumBalanceGroup(this);3144 this.assetManager = new MoonbeamAssetManagerGroup(this);3145 this.assets = new AssetsGroup(this);3146 this.xTokens = new XTokensGroup(this);3147 this.democracy = new MoonbeamDemocracyGroup(this, options);3148 this.collective = {3149 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3150 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3151 };3152 }3153}31543155export class AcalaHelper extends XcmChainHelper {3156 balance: SubstrateBalanceGroup<AcalaHelper>;3157 assetRegistry: AcalaAssetRegistryGroup;3158 xTokens: XTokensGroup<AcalaHelper>;3159 tokens: TokensGroup<AcalaHelper>;31603161 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3162 super(logger, options.helperBase ?? AcalaHelper);31633164 this.balance = new SubstrateBalanceGroup(this);3165 this.assetRegistry = new AcalaAssetRegistryGroup(this);3166 this.xTokens = new XTokensGroup(this);3167 this.tokens = new TokensGroup(this);3168 }31693170 getSudo<T extends AcalaHelper>() {3171 // eslint-disable-next-line @typescript-eslint/naming-convention3172 const SudoHelperType = SudoHelper(this.helperBase);3173 return this.clone(SudoHelperType) as T;3174 }3175}31763177// eslint-disable-next-line @typescript-eslint/naming-convention3178function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3179 return class extends Base {3180 scheduleFn: 'schedule' | 'scheduleAfter';3181 blocksNum: number;3182 options: ISchedulerOptions;31833184 constructor(...args: any[]) {3185 const logger = args[0] as ILogger;3186 const options = args[1] as {3187 scheduleFn: 'schedule' | 'scheduleAfter',3188 blocksNum: number,3189 options: ISchedulerOptions3190 };31913192 super(logger);31933194 this.scheduleFn = options.scheduleFn;3195 this.blocksNum = options.blocksNum;3196 this.options = options.options;3197 }31983199 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3200 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);32013202 const mandatorySchedArgs = [3203 this.blocksNum,3204 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3205 this.options.priority ?? null,3206 scheduledTx,3207 ];32083209 let schedArgs;3210 let scheduleFn;32113212 if (this.options.scheduledId) {3213 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];32143215 if (this.scheduleFn == 'schedule') {3216 scheduleFn = 'scheduleNamed';3217 } else if (this.scheduleFn == 'scheduleAfter') {3218 scheduleFn = 'scheduleNamedAfter';3219 }3220 } else {3221 schedArgs = mandatorySchedArgs;3222 scheduleFn = this.scheduleFn;3223 }32243225 const extrinsic = 'api.tx.scheduler.' + scheduleFn;32263227 return super.executeExtrinsic(3228 sender,3229 extrinsic,3230 schedArgs,3231 expectSuccess,3232 );3233 }3234 };3235}32363237// eslint-disable-next-line @typescript-eslint/naming-convention3238function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3239 return class extends Base {3240 constructor(...args: any[]) {3241 super(...args);3242 }32433244 async executeExtrinsic(3245 sender: IKeyringPair,3246 extrinsic: string,3247 params: any[],3248 expectSuccess?: boolean,3249 options: Partial<SignerOptions>|null = null,3250 ): Promise<ITransactionResult> {3251 const call = this.constructApiCall(extrinsic, params);3252 const result = await super.executeExtrinsic(3253 sender,3254 'api.tx.sudo.sudo',3255 [call],3256 expectSuccess,3257 options,3258 );32593260 if (result.status === 'Fail') return result;32613262 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3263 if (data.isErr) {3264 if (data.asErr.isModule) {3265 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3266 const metaError = super.getApi()?.registry.findMetaError(error);3267 throw new Error(`${metaError.section}.${metaError.name}`);3268 } else {3269 throw new Error(data.asErr.toHuman());3270 }3271 }3272 return result;3273 }3274 };3275}32763277export class UniqueBaseCollection {3278 helper: UniqueHelper;3279 collectionId: number;32803281 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3282 this.collectionId = collectionId;3283 this.helper = uniqueHelper;3284 }32853286 async getData() {3287 return await this.helper.collection.getData(this.collectionId);3288 }32893290 async getLastTokenId() {3291 return await this.helper.collection.getLastTokenId(this.collectionId);3292 }32933294 async doesTokenExist(tokenId: number) {3295 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3296 }32973298 async getAdmins() {3299 return await this.helper.collection.getAdmins(this.collectionId);3300 }33013302 async getAllowList() {3303 return await this.helper.collection.getAllowList(this.collectionId);3304 }33053306 async getEffectiveLimits() {3307 return await this.helper.collection.getEffectiveLimits(this.collectionId);3308 }33093310 async getProperties(propertyKeys?: string[] | null) {3311 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3312 }33133314 async getPropertiesConsumedSpace() {3315 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3316 }33173318 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3319 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3320 }33213322 async getOptions() {3323 return await this.helper.collection.getCollectionOptions(this.collectionId);3324 }33253326 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3327 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3328 }33293330 async confirmSponsorship(signer: TSigner) {3331 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3332 }33333334 async removeSponsor(signer: TSigner) {3335 return await this.helper.collection.removeSponsor(signer, this.collectionId);3336 }33373338 async setLimits(signer: TSigner, limits: ICollectionLimits) {3339 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3340 }33413342 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3343 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3344 }33453346 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3347 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3348 }33493350 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3351 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3352 }33533354 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3355 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3356 }33573358 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3359 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3360 }33613362 async setProperties(signer: TSigner, properties: IProperty[]) {3363 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3364 }33653366 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3367 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3368 }33693370 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3371 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3372 }33733374 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3375 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3376 }33773378 async disableNesting(signer: TSigner) {3379 return await this.helper.collection.disableNesting(signer, this.collectionId);3380 }33813382 async burn(signer: TSigner) {3383 return await this.helper.collection.burn(signer, this.collectionId);3384 }33853386 scheduleAt<T extends UniqueHelper>(3387 executionBlockNumber: number,3388 options: ISchedulerOptions = {},3389 ) {3390 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3391 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3392 }33933394 scheduleAfter<T extends UniqueHelper>(3395 blocksBeforeExecution: number,3396 options: ISchedulerOptions = {},3397 ) {3398 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3399 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3400 }34013402 getSudo<T extends UniqueHelper>() {3403 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3404 }3405}340634073408export class UniqueNFTCollection extends UniqueBaseCollection {3409 getTokenObject(tokenId: number) {3410 return new UniqueNFToken(tokenId, this);3411 }34123413 async getTokensByAddress(addressObj: ICrossAccountId) {3414 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3415 }34163417 async getToken(tokenId: number, blockHashAt?: string) {3418 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3419 }34203421 async getTokenOwner(tokenId: number, blockHashAt?: string) {3422 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3423 }34243425 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3426 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3427 }34283429 async getTokenChildren(tokenId: number, blockHashAt?: string) {3430 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3431 }34323433 async getPropertyPermissions(propertyKeys: string[] | null = null) {3434 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3435 }34363437 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3438 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3439 }34403441 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3442 const api = this.helper.getApi();3443 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();34443445 return (props! as any).consumedSpace;3446 }34473448 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3449 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3450 }34513452 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3453 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3454 }34553456 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3457 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3458 }34593460 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3461 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3462 }34633464 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3465 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3466 }34673468 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3469 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3470 }34713472 async burnToken(signer: TSigner, tokenId: number) {3473 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3474 }34753476 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3477 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3478 }34793480 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3481 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3482 }34833484 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3485 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3486 }34873488 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3489 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3490 }34913492 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3493 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3494 }34953496 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3497 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3498 }34993500 scheduleAt<T extends UniqueHelper>(3501 executionBlockNumber: number,3502 options: ISchedulerOptions = {},3503 ) {3504 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3505 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3506 }35073508 scheduleAfter<T extends UniqueHelper>(3509 blocksBeforeExecution: number,3510 options: ISchedulerOptions = {},3511 ) {3512 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3513 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3514 }35153516 getSudo<T extends UniqueHelper>() {3517 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3518 }3519}352035213522export class UniqueRFTCollection extends UniqueBaseCollection {3523 getTokenObject(tokenId: number) {3524 return new UniqueRFToken(tokenId, this);3525 }35263527 async getToken(tokenId: number, blockHashAt?: string) {3528 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3529 }35303531 async getTokensByAddress(addressObj: ICrossAccountId) {3532 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3533 }35343535 async getTop10TokenOwners(tokenId: number) {3536 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3537 }35383539 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3540 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3541 }35423543 async getTokenTotalPieces(tokenId: number) {3544 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3545 }35463547 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3548 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3549 }35503551 async getPropertyPermissions(propertyKeys: string[] | null = null) {3552 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3553 }35543555 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3556 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3557 }35583559 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3560 const api = this.helper.getApi();3561 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();35623563 return (props! as any).consumedSpace;3564 }35653566 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3567 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3568 }35693570 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3571 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3572 }35733574 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3575 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3576 }35773578 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3579 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3580 }35813582 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3583 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3584 }35853586 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3587 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3588 }35893590 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3591 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3592 }35933594 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3595 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3596 }35973598 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3599 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3600 }36013602 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3603 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3604 }36053606 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3607 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3608 }36093610 scheduleAt<T extends UniqueHelper>(3611 executionBlockNumber: number,3612 options: ISchedulerOptions = {},3613 ) {3614 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3615 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3616 }36173618 scheduleAfter<T extends UniqueHelper>(3619 blocksBeforeExecution: number,3620 options: ISchedulerOptions = {},3621 ) {3622 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3623 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3624 }36253626 getSudo<T extends UniqueHelper>() {3627 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3628 }3629}363036313632export class UniqueFTCollection extends UniqueBaseCollection {3633 async getBalance(addressObj: ICrossAccountId) {3634 return await this.helper.ft.getBalance(this.collectionId, addressObj);3635 }36363637 async getTotalPieces() {3638 return await this.helper.ft.getTotalPieces(this.collectionId);3639 }36403641 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3642 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3643 }36443645 async getTop10Owners() {3646 return await this.helper.ft.getTop10Owners(this.collectionId);3647 }36483649 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3650 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3651 }36523653 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3654 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3655 }36563657 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3658 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3659 }36603661 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3662 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3663 }36643665 async burnTokens(signer: TSigner, amount=1n) {3666 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3667 }36683669 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3670 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3671 }36723673 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3674 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3675 }36763677 scheduleAt<T extends UniqueHelper>(3678 executionBlockNumber: number,3679 options: ISchedulerOptions = {},3680 ) {3681 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3682 return new UniqueFTCollection(this.collectionId, scheduledHelper);3683 }36843685 scheduleAfter<T extends UniqueHelper>(3686 blocksBeforeExecution: number,3687 options: ISchedulerOptions = {},3688 ) {3689 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3690 return new UniqueFTCollection(this.collectionId, scheduledHelper);3691 }36923693 getSudo<T extends UniqueHelper>() {3694 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3695 }3696}369736983699export class UniqueBaseToken {3700 collection: UniqueNFTCollection | UniqueRFTCollection;3701 collectionId: number;3702 tokenId: number;37033704 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3705 this.collection = collection;3706 this.collectionId = collection.collectionId;3707 this.tokenId = tokenId;3708 }37093710 async getNextSponsored(addressObj: ICrossAccountId) {3711 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3712 }37133714 async getProperties(propertyKeys?: string[] | null) {3715 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3716 }37173718 async getTokenPropertiesConsumedSpace() {3719 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3720 }37213722 async setProperties(signer: TSigner, properties: IProperty[]) {3723 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3724 }37253726 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3727 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3728 }37293730 async doesExist() {3731 return await this.collection.doesTokenExist(this.tokenId);3732 }37333734 nestingAccount() {3735 return this.collection.helper.util.getTokenAccount(this);3736 }37373738 scheduleAt<T extends UniqueHelper>(3739 executionBlockNumber: number,3740 options: ISchedulerOptions = {},3741 ) {3742 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3743 return new UniqueBaseToken(this.tokenId, scheduledCollection);3744 }37453746 scheduleAfter<T extends UniqueHelper>(3747 blocksBeforeExecution: number,3748 options: ISchedulerOptions = {},3749 ) {3750 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3751 return new UniqueBaseToken(this.tokenId, scheduledCollection);3752 }37533754 getSudo<T extends UniqueHelper>() {3755 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3756 }3757}375837593760export class UniqueNFToken extends UniqueBaseToken {3761 collection: UniqueNFTCollection;37623763 constructor(tokenId: number, collection: UniqueNFTCollection) {3764 super(tokenId, collection);3765 this.collection = collection;3766 }37673768 async getData(blockHashAt?: string) {3769 return await this.collection.getToken(this.tokenId, blockHashAt);3770 }37713772 async getOwner(blockHashAt?: string) {3773 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3774 }37753776 async getTopmostOwner(blockHashAt?: string) {3777 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3778 }37793780 async getChildren(blockHashAt?: string) {3781 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3782 }37833784 async nest(signer: TSigner, toTokenObj: IToken) {3785 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3786 }37873788 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3789 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3790 }37913792 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3793 return await this.collection.transferToken(signer, this.tokenId, addressObj);3794 }37953796 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3797 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3798 }37993800 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3801 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3802 }38033804 async isApproved(toAddressObj: ICrossAccountId) {3805 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3806 }38073808 async burn(signer: TSigner) {3809 return await this.collection.burnToken(signer, this.tokenId);3810 }38113812 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3813 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3814 }38153816 scheduleAt<T extends UniqueHelper>(3817 executionBlockNumber: number,3818 options: ISchedulerOptions = {},3819 ) {3820 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3821 return new UniqueNFToken(this.tokenId, scheduledCollection);3822 }38233824 scheduleAfter<T extends UniqueHelper>(3825 blocksBeforeExecution: number,3826 options: ISchedulerOptions = {},3827 ) {3828 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3829 return new UniqueNFToken(this.tokenId, scheduledCollection);3830 }38313832 getSudo<T extends UniqueHelper>() {3833 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3834 }3835}38363837export class UniqueRFToken extends UniqueBaseToken {3838 collection: UniqueRFTCollection;38393840 constructor(tokenId: number, collection: UniqueRFTCollection) {3841 super(tokenId, collection);3842 this.collection = collection;3843 }38443845 async getData(blockHashAt?: string) {3846 return await this.collection.getToken(this.tokenId, blockHashAt);3847 }38483849 async getTop10Owners() {3850 return await this.collection.getTop10TokenOwners(this.tokenId);3851 }38523853 async getBalance(addressObj: ICrossAccountId) {3854 return await this.collection.getTokenBalance(this.tokenId, addressObj);3855 }38563857 async getTotalPieces() {3858 return await this.collection.getTokenTotalPieces(this.tokenId);3859 }38603861 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3862 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3863 }38643865 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3866 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3867 }38683869 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3870 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3871 }38723873 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3874 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3875 }38763877 async repartition(signer: TSigner, amount: bigint) {3878 return await this.collection.repartitionToken(signer, this.tokenId, amount);3879 }38803881 async burn(signer: TSigner, amount=1n) {3882 return await this.collection.burnToken(signer, this.tokenId, amount);3883 }38843885 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3886 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3887 }38883889 scheduleAt<T extends UniqueHelper>(3890 executionBlockNumber: number,3891 options: ISchedulerOptions = {},3892 ) {3893 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3894 return new UniqueRFToken(this.tokenId, scheduledCollection);3895 }38963897 scheduleAfter<T extends UniqueHelper>(3898 blocksBeforeExecution: number,3899 options: ISchedulerOptions = {},3900 ) {3901 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3902 return new UniqueRFToken(this.tokenId, scheduledCollection);3903 }39043905 getSudo<T extends UniqueHelper>() {3906 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3907 }3908}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50 Substrate?: TSubstrateAccount;51 Ethereum?: TEthereumAccount;5253 constructor(account: ICrossAccountId) {54 if (account.Substrate) this.Substrate = account.Substrate;55 if (account.Ethereum) this.Ethereum = account.Ethereum;56 }5758 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59 switch (domain) {60 case 'Substrate': return new CrossAccountId({Substrate: account.address});61 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62 }63 }6465 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67 }6869 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70 return encodeAddress(decodeAddress(address), ss58Format);71 }7273 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75 }7677 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79 return this;80 }8182 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84 }8586 toEthereum(): CrossAccountId {87 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88 return this;89 }9091 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92 return evmToAddress(address, ss58Format);93 }9495 toSubstrate(ss58Format?: number): CrossAccountId {96 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97 return this;98 }99100 toLowerCase(): CrossAccountId {101 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103 return this;104 }105}106107const nesting = {108 toChecksumAddress(address: string): string {109 if (typeof address === 'undefined') return '';110111 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113 address = address.toLowerCase().replace(/^0x/i,'');114 const addressHash = keccakAsHex(address).replace(/^0x/i,'');115 const checksumAddress = ['0x'];116117 for (let i = 0; i < address.length; i++) {118 // If ith character is 8 to f then make it uppercase119 if (parseInt(addressHash[i], 16) > 7) {120 checksumAddress.push(address[i].toUpperCase());121 } else {122 checksumAddress.push(address[i]);123 }124 }125 return checksumAddress.join('');126 },127 tokenIdToAddress(collectionId: number, tokenId: number) {128 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);129 },130};131132class UniqueUtil {133 static transactionStatus = {134 NOT_READY: 'NotReady',135 FAIL: 'Fail',136 SUCCESS: 'Success',137 };138139 static chainLogType = {140 EXTRINSIC: 'extrinsic',141 RPC: 'rpc',142 };143144 static getTokenAccount(token: IToken): CrossAccountId {145 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146 }147148 static getTokenAddress(token: IToken): string {149 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150 }151152 static getDefaultLogger(): ILogger {153 return {154 log(msg: any, level = 'INFO') {155 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156 },157 level: {158 ERROR: 'ERROR',159 WARNING: 'WARNING',160 INFO: 'INFO',161 },162 };163 }164165 static vec2str(arr: string[] | number[]) {166 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167 }168169 static str2vec(string: string) {170 if (typeof string !== 'string') return string;171 return Array.from(string).map(x => x.charCodeAt(0));172 }173174 static fromSeed(seed: string, ss58Format = 42) {175 const keyring = new Keyring({type: 'sr25519', ss58Format});176 return keyring.addFromUri(seed);177 }178179 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180 if (creationResult.status !== this.transactionStatus.SUCCESS) {181 throw Error('Unable to create collection!');182 }183184 let collectionId = null;185 creationResult.result.events.forEach(({event: {data, method, section}}) => {186 if ((section === 'common') && (method === 'CollectionCreated')) {187 collectionId = parseInt(data[0].toString(), 10);188 }189 });190191 if (collectionId === null) {192 throw Error('No CollectionCreated event was found!');193 }194195 return collectionId;196 }197198 static extractTokensFromCreationResult(creationResult: ITransactionResult): {199 success: boolean,200 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201 } {202 if (creationResult.status !== this.transactionStatus.SUCCESS) {203 throw Error('Unable to create tokens!');204 }205 let success = false;206 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207 creationResult.result.events.forEach(({event: {data, method, section}}) => {208 if (method === 'ExtrinsicSuccess') {209 success = true;210 } else if ((section === 'common') && (method === 'ItemCreated')) {211 tokens.push({212 collectionId: parseInt(data[0].toString(), 10),213 tokenId: parseInt(data[1].toString(), 10),214 owner: data[2].toHuman(),215 amount: data[3].toBigInt(),216 });217 }218 });219 return {success, tokens};220 }221222 static extractTokensFromBurnResult(burnResult: ITransactionResult): {223 success: boolean,224 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225 } {226 if (burnResult.status !== this.transactionStatus.SUCCESS) {227 throw Error('Unable to burn tokens!');228 }229 let success = false;230 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231 burnResult.result.events.forEach(({event: {data, method, section}}) => {232 if (method === 'ExtrinsicSuccess') {233 success = true;234 } else if ((section === 'common') && (method === 'ItemDestroyed')) {235 tokens.push({236 collectionId: parseInt(data[0].toString(), 10),237 tokenId: parseInt(data[1].toString(), 10),238 owner: data[2].toHuman(),239 amount: data[3].toBigInt(),240 });241 }242 });243 return {success, tokens};244 }245246 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247 let eventId = null;248 events.forEach(({event: {data, method, section}}) => {249 if ((section === expectedSection) && (method === expectedMethod)) {250 eventId = parseInt(data[0].toString(), 10);251 }252 });253254 if (eventId === null) {255 throw Error(`No ${expectedMethod} event was found!`);256 }257 return eventId === collectionId;258 }259260 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261 const normalizeAddress = (address: string | ICrossAccountId) => {262 if(typeof address === 'string') return address;263 const obj = {} as any;264 Object.keys(address).forEach(k => {265 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266 });267 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269 return address;270 };271 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272 events.forEach(({event: {data, method, section}}) => {273 if ((section === 'common') && (method === 'Transfer')) {274 const hData = (data as any).toJSON();275 transfer = {276 collectionId: hData[0],277 tokenId: hData[1],278 from: normalizeAddress(hData[2]),279 to: normalizeAddress(hData[3]),280 amount: BigInt(hData[4]),281 };282 }283 });284 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287 isSuccess = isSuccess && amount === transfer.amount;288 return isSuccess;289 }290291 static bigIntToDecimals(number: bigint, decimals = 18) {292 const numberStr = number.toString();293 const dotPos = numberStr.length - decimals;294295 if (dotPos <= 0) {296 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297 } else {298 const intPart = numberStr.substring(0, dotPos);299 const fractPart = numberStr.substring(dotPos);300 return intPart + '.' + fractPart;301 }302 }303}304305class UniqueEventHelper {306 private static extractIndex(index: any): [number, number] | string {307 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308 return index.toJSON();309 }310311 private static extractSub(data: any, subTypes: any): {[key: string]: any} {312 let obj: any = {};313 let index = 0;314315 if (data.entries) {316 for(const [key, value] of data.entries()) {317 obj[key] = this.extractData(value, subTypes[index]);318 index++;319 }320 } else obj = data.toJSON();321322 return obj;323 }324325 private static toHuman(data: any) {326 return data && data.toHuman ? data.toHuman() : `${data}`;327 }328329 private static extractData(data: any, type: any): any {330 if(!type) return this.toHuman(data);331 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334 return this.toHuman(data);335 }336337 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338 const parsedEvents: IEvent[] = [];339340 events.forEach((record) => {341 const {event, phase} = record;342 const types = event.typeDef;343344 const eventData: IEvent = {345 section: event.section.toString(),346 method: event.method.toString(),347 index: this.extractIndex(event.index),348 data: [],349 phase: phase.toJSON(),350 };351352 event.data.forEach((val: any, index: number) => {353 eventData.data.push(this.extractData(val, types[index]));354 });355356 parsedEvents.push(eventData);357 });358359 return parsedEvents;360 }361}362363export class ChainHelperBase {364 helperBase: any;365366 transactionStatus = UniqueUtil.transactionStatus;367 chainLogType = UniqueUtil.chainLogType;368 util: typeof UniqueUtil;369 eventHelper: typeof UniqueEventHelper;370 logger: ILogger;371 api: ApiPromise | null;372 forcedNetwork: TNetworks | null;373 network: TNetworks | null;374 wsEndpoint: string | null;375 chainLog: IUniqueHelperLog[];376 children: ChainHelperBase[];377 address: AddressGroup;378 chain: ChainGroup;379380 constructor(logger?: ILogger, helperBase?: any) {381 this.helperBase = helperBase;382383 this.util = UniqueUtil;384 this.eventHelper = UniqueEventHelper;385 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();386 this.logger = logger;387 this.api = null;388 this.forcedNetwork = null;389 this.network = null;390 this.wsEndpoint = null;391 this.chainLog = [];392 this.children = [];393 this.address = new AddressGroup(this);394 this.chain = new ChainGroup(this);395 }396397 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {398 Object.setPrototypeOf(helperCls.prototype, this);399 const newHelper = new helperCls(this.logger, options);400401 newHelper.api = this.api;402 newHelper.network = this.network;403 newHelper.forceNetwork = this.forceNetwork;404405 this.children.push(newHelper);406407 return newHelper;408 }409410 getEndpoint(): string {411 if (this.wsEndpoint === null) throw Error('No connection was established');412 return this.wsEndpoint;413 }414415 getApi(): ApiPromise {416 if(this.api === null) throw Error('API not initialized');417 return this.api;418 }419420 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {421 const collectedEvents: IEvent[] = [];422 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {423 const ievents = this.eventHelper.extractEvents(events);424 ievents.forEach((event) => {425 expectedEvents.forEach((e => {426 if (event.section === e.section && e.names.includes(event.method)) {427 collectedEvents.push(event);428 }429 }));430 });431 });432 return {unsubscribe: unsubscribe as any, collectedEvents};433 }434435 clearChainLog(): void {436 this.chainLog = [];437 }438439 forceNetwork(value: TNetworks): void {440 this.forcedNetwork = value;441 }442443 async connect(wsEndpoint: string, listeners?: IApiListeners) {444 if (this.api !== null) throw Error('Already connected');445 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);446 this.wsEndpoint = wsEndpoint;447 this.api = api;448 this.network = network;449 }450451 async disconnect() {452 for (const child of this.children) {453 child.clearApi();454 }455456 if (this.api === null) return;457 await this.api.disconnect();458 this.clearApi();459 }460461 clearApi() {462 this.api = null;463 this.network = null;464 }465466 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {467 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;468 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];469470 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;471472 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;473 return 'opal';474 }475476 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {477 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});478 await api.isReady;479480 const network = await this.detectNetwork(api);481482 await api.disconnect();483484 return network;485 }486487 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{488 api: ApiPromise;489 network: TNetworks;490 }> {491 if(typeof network === 'undefined' || network === null) network = 'opal';492 const supportedRPC = {493 opal: {494 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,495 },496 quartz: {497 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,498 },499 unique: {500 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,501 },502 rococo: {},503 westend: {},504 moonbeam: {},505 moonriver: {},506 acala: {},507 karura: {},508 westmint: {},509 };510 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);511 const rpc = supportedRPC[network];512513 // TODO: investigate how to replace rpc in runtime514 // api._rpcCore.addUserInterfaces(rpc);515516 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});517518 await api.isReadyOrError;519520 if (typeof listeners === 'undefined') listeners = {};521 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {522 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;523 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);524 }525526 return {api, network};527 }528529 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {530 const {events, status} = data;531 if (status.isReady) {532 return this.transactionStatus.NOT_READY;533 }534 if (status.isBroadcast) {535 return this.transactionStatus.NOT_READY;536 }537 if (status.isInBlock || status.isFinalized) {538 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');539 if (errors.length > 0) {540 return this.transactionStatus.FAIL;541 }542 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {543 return this.transactionStatus.SUCCESS;544 }545 }546547 return this.transactionStatus.FAIL;548 }549550 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {551 const sign = (callback: any) => {552 if(options !== null) return transaction.signAndSend(sender, options, callback);553 return transaction.signAndSend(sender, callback);554 };555 // eslint-disable-next-line no-async-promise-executor556 return new Promise(async (resolve, reject) => {557 try {558 const unsub = await sign((result: any) => {559 const status = this.getTransactionStatus(result);560561 if (status === this.transactionStatus.SUCCESS) {562 this.logger.log(`${label} successful`);563 unsub();564 resolve({result, status});565 } else if (status === this.transactionStatus.FAIL) {566 let moduleError = null;567568 if (result.hasOwnProperty('dispatchError')) {569 const dispatchError = result['dispatchError'];570571 if (dispatchError) {572 if (dispatchError.isModule) {573 const modErr = dispatchError.asModule;574 const errorMeta = dispatchError.registry.findMetaError(modErr);575576 moduleError = `${errorMeta.section}.${errorMeta.name}`;577 } else {578 moduleError = dispatchError.toHuman();579 }580 } else {581 this.logger.log(result, this.logger.level.ERROR);582 }583 }584585 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);586 unsub();587 reject({status, moduleError, result});588 }589 });590 } catch (e) {591 this.logger.log(e, this.logger.level.ERROR);592 reject(e);593 }594 });595 }596597 async signTransactionWithoutSending(signer: TSigner, tx: any) {598 const api = this.getApi();599 const signingInfo = await api.derive.tx.signingInfo(signer.address);600601 tx.sign(signer, {602 blockHash: api.genesisHash,603 genesisHash: api.genesisHash,604 runtimeVersion: api.runtimeVersion,605 nonce: signingInfo.nonce,606 });607608 return tx.toHex();609 }610611 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {612 const api = this.getApi();613 const signingInfo = await api.derive.tx.signingInfo(signer.address);614615 // We need to sign the tx because616 // unsigned transactions does not have an inclusion fee617 tx.sign(signer, {618 blockHash: api.genesisHash,619 genesisHash: api.genesisHash,620 runtimeVersion: api.runtimeVersion,621 nonce: signingInfo.nonce,622 });623624 if (len === null) {625 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;626 } else {627 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;628 }629 }630631 constructApiCall(apiCall: string, params: any[]) {632 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);633 let call = this.getApi() as any;634 for(const part of apiCall.slice(4).split('.')) {635 call = call[part];636 if (!call) {637 const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';638 throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);639 }640 }641 return call(...params);642 }643644 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {645 if(this.api === null) throw Error('API not initialized');646 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);647648 const startTime = (new Date()).getTime();649 let result: ITransactionResult;650 let events: IEvent[] = [];651 try {652 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;653 events = this.eventHelper.extractEvents(result.result.events);654 const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');655 if (errorEvent)656 throw Error(errorEvent.method + ': ' + extrinsic);657 }658 catch(e) {659 if(!(e as object).hasOwnProperty('status')) throw e;660 result = e as ITransactionResult;661 }662663 const endTime = (new Date()).getTime();664665 const log = {666 executedAt: endTime,667 executionTime: endTime - startTime,668 type: this.chainLogType.EXTRINSIC,669 status: result.status,670 call: extrinsic,671 signer: this.getSignerAddress(sender),672 params,673 } as IUniqueHelperLog;674675 if(result.status !== this.transactionStatus.SUCCESS) {676 if (result.moduleError) log.moduleError = result.moduleError;677 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;678 }679 if(events.length > 0) log.events = events;680681 this.chainLog.push(log);682683 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {684 if (result.moduleError) throw Error(`${result.moduleError}`);685 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));686 }687 return result;688 }689690 async callRpc(rpc: string, params?: any[]) {691 if(typeof params === 'undefined') params = [];692 if(this.api === null) throw Error('API not initialized');693 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);694695 const startTime = (new Date()).getTime();696 let result;697 let error = null;698 const log = {699 type: this.chainLogType.RPC,700 call: rpc,701 params,702 } as IUniqueHelperLog;703704 try {705 result = await this.constructApiCall(rpc, params);706 }707 catch(e) {708 error = e;709 }710711 const endTime = (new Date()).getTime();712713 log.executedAt = endTime;714 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';715 log.executionTime = endTime - startTime;716717 this.chainLog.push(log);718719 if(error !== null) throw error;720721 return result;722 }723724 getSignerAddress(signer: IKeyringPair | string): string {725 if(typeof signer === 'string') return signer;726 return signer.address;727 }728729 fetchAllPalletNames(): string[] {730 if(this.api === null) throw Error('API not initialized');731 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());732 }733734 fetchMissingPalletNames(requiredPallets: string[]): string[] {735 const palletNames = this.fetchAllPalletNames();736 return requiredPallets.filter(p => !palletNames.includes(p));737 }738}739740741class HelperGroup<T extends ChainHelperBase> {742 helper: T;743744 constructor(uniqueHelper: T) {745 this.helper = uniqueHelper;746 }747}748749750class CollectionGroup extends HelperGroup<UniqueHelper> {751 /**752 * Get number of blocks when sponsored transaction is available.753 *754 * @param collectionId ID of collection755 * @param tokenId ID of token756 * @param addressObj address for which the sponsorship is checked757 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});758 * @returns number of blocks or null if sponsorship hasn't been set759 */760 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {761 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();762 }763764 /**765 * Get the number of created collections.766 *767 * @returns number of created collections768 */769 async getTotalCount(): Promise<number> {770 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();771 }772773 /**774 * Get information about the collection with additional data,775 * including the number of tokens it contains, its administrators,776 * the normalized address of the collection's owner, and decoded name and description.777 *778 * @param collectionId ID of collection779 * @example await getData(2)780 * @returns collection information object781 */782 async getData(collectionId: number): Promise<{783 id: number;784 name: string;785 description: string;786 tokensCount: number;787 admins: CrossAccountId[];788 normalizedOwner: TSubstrateAccount;789 raw: any790 } | null> {791 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);792 const humanCollection = collection.toHuman(), collectionData = {793 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],794 raw: humanCollection,795 } as any, jsonCollection = collection.toJSON();796 if (humanCollection === null) return null;797 collectionData.raw.limits = jsonCollection.limits;798 collectionData.raw.permissions = jsonCollection.permissions;799 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);800 for (const key of ['name', 'description']) {801 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);802 }803804 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))805 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)806 : 0;807 collectionData.admins = await this.getAdmins(collectionId);808809 return collectionData;810 }811812 /**813 * Get the addresses of the collection's administrators, optionally normalized.814 *815 * @param collectionId ID of collection816 * @param normalize whether to normalize the addresses to the default ss58 format817 * @example await getAdmins(1)818 * @returns array of administrators819 */820 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {821 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();822823 return normalize824 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())825 : admins;826 }827828 /**829 * Get the addresses added to the collection allow-list, optionally normalized.830 * @param collectionId ID of collection831 * @param normalize whether to normalize the addresses to the default ss58 format832 * @example await getAllowList(1)833 * @returns array of allow-listed addresses834 */835 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {836 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();837 return normalize838 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())839 : allowListed;840 }841842 /**843 * Get the effective limits of the collection instead of null for default values844 *845 * @param collectionId ID of collection846 * @example await getEffectiveLimits(2)847 * @returns object of collection limits848 */849 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {850 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();851 }852853 /**854 * Burns the collection if the signer has sufficient permissions and collection is empty.855 *856 * @param signer keyring of signer857 * @param collectionId ID of collection858 * @example await helper.collection.burn(aliceKeyring, 3);859 * @returns ```true``` if extrinsic success, otherwise ```false```860 */861 async burn(signer: TSigner, collectionId: number): Promise<boolean> {862 const result = await this.helper.executeExtrinsic(863 signer,864 'api.tx.unique.destroyCollection', [collectionId],865 true,866 );867868 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');869 }870871 /**872 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.873 *874 * @param signer keyring of signer875 * @param collectionId ID of collection876 * @param sponsorAddress Sponsor substrate address877 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")878 * @returns ```true``` if extrinsic success, otherwise ```false```879 */880 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {881 const result = await this.helper.executeExtrinsic(882 signer,883 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],884 true,885 );886887 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');888 }889890 /**891 * Confirms consent to sponsor the collection on behalf of the signer.892 *893 * @param signer keyring of signer894 * @param collectionId ID of collection895 * @example confirmSponsorship(aliceKeyring, 10)896 * @returns ```true``` if extrinsic success, otherwise ```false```897 */898 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {899 const result = await this.helper.executeExtrinsic(900 signer,901 'api.tx.unique.confirmSponsorship', [collectionId],902 true,903 );904905 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');906 }907908 /**909 * Removes the sponsor of a collection, regardless if it consented or not.910 *911 * @param signer keyring of signer912 * @param collectionId ID of collection913 * @example removeSponsor(aliceKeyring, 10)914 * @returns ```true``` if extrinsic success, otherwise ```false```915 */916 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {917 const result = await this.helper.executeExtrinsic(918 signer,919 'api.tx.unique.removeCollectionSponsor', [collectionId],920 true,921 );922923 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');924 }925926 /**927 * Sets the limits of the collection. At least one limit must be specified for a correct call.928 *929 * @param signer keyring of signer930 * @param collectionId ID of collection931 * @param limits collection limits object932 * @example933 * await setLimits(934 * aliceKeyring,935 * 10,936 * {937 * sponsorTransferTimeout: 0,938 * ownerCanDestroy: false939 * }940 * )941 * @returns ```true``` if extrinsic success, otherwise ```false```942 */943 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {944 const result = await this.helper.executeExtrinsic(945 signer,946 'api.tx.unique.setCollectionLimits', [collectionId, limits],947 true,948 );949950 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');951 }952953 /**954 * Changes the owner of the collection to the new Substrate address.955 *956 * @param signer keyring of signer957 * @param collectionId ID of collection958 * @param ownerAddress substrate address of new owner959 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")960 * @returns ```true``` if extrinsic success, otherwise ```false```961 */962 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {963 const result = await this.helper.executeExtrinsic(964 signer,965 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],966 true,967 );968969 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');970 }971972 /**973 * Adds a collection administrator.974 *975 * @param signer keyring of signer976 * @param collectionId ID of collection977 * @param adminAddressObj Administrator address (substrate or ethereum)978 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})979 * @returns ```true``` if extrinsic success, otherwise ```false```980 */981 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {982 const result = await this.helper.executeExtrinsic(983 signer,984 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],985 true,986 );987988 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');989 }990991 /**992 * Removes a collection administrator.993 *994 * @param signer keyring of signer995 * @param collectionId ID of collection996 * @param adminAddressObj Administrator address (substrate or ethereum)997 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})998 * @returns ```true``` if extrinsic success, otherwise ```false```999 */1000 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1001 const result = await this.helper.executeExtrinsic(1002 signer,1003 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1004 true,1005 );10061007 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1008 }10091010 /**1011 * Check if user is in allow list.1012 *1013 * @param collectionId ID of collection1014 * @param user Account to check1015 * @example await getAdmins(1)1016 * @returns is user in allow list1017 */1018 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1019 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1020 }10211022 /**1023 * Adds an address to allow list1024 * @param signer keyring of signer1025 * @param collectionId ID of collection1026 * @param addressObj address to add to the allow list1027 * @returns ```true``` if extrinsic success, otherwise ```false```1028 */1029 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1030 const result = await this.helper.executeExtrinsic(1031 signer,1032 'api.tx.unique.addToAllowList', [collectionId, addressObj],1033 true,1034 );10351036 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1037 }10381039 /**1040 * Removes an address from allow list1041 *1042 * @param signer keyring of signer1043 * @param collectionId ID of collection1044 * @param addressObj address to remove from the allow list1045 * @returns ```true``` if extrinsic success, otherwise ```false```1046 */1047 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1048 const result = await this.helper.executeExtrinsic(1049 signer,1050 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1051 true,1052 );10531054 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1055 }10561057 /**1058 * Sets onchain permissions for selected collection.1059 *1060 * @param signer keyring of signer1061 * @param collectionId ID of collection1062 * @param permissions collection permissions object1063 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1064 * @returns ```true``` if extrinsic success, otherwise ```false```1065 */1066 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1067 const result = await this.helper.executeExtrinsic(1068 signer,1069 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1070 true,1071 );10721073 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1074 }10751076 /**1077 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1078 *1079 * @param signer keyring of signer1080 * @param collectionId ID of collection1081 * @param permissions nesting permissions object1082 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1083 * @returns ```true``` if extrinsic success, otherwise ```false```1084 */1085 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1086 return await this.setPermissions(signer, collectionId, {nesting: permissions});1087 }10881089 /**1090 * Disables nesting for selected collection.1091 *1092 * @param signer keyring of signer1093 * @param collectionId ID of collection1094 * @example disableNesting(aliceKeyring, 10);1095 * @returns ```true``` if extrinsic success, otherwise ```false```1096 */1097 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1098 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1099 }11001101 /**1102 * Sets onchain properties to the collection.1103 *1104 * @param signer keyring of signer1105 * @param collectionId ID of collection1106 * @param properties array of property objects1107 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1108 * @returns ```true``` if extrinsic success, otherwise ```false```1109 */1110 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1111 const result = await this.helper.executeExtrinsic(1112 signer,1113 'api.tx.unique.setCollectionProperties', [collectionId, properties],1114 true,1115 );11161117 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1118 }11191120 /**1121 * Get collection properties.1122 *1123 * @param collectionId ID of collection1124 * @param propertyKeys optionally filter the returned properties to only these keys1125 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1126 * @returns array of key-value pairs1127 */1128 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1129 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1130 }11311132 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1133 const api = this.helper.getApi();1134 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11351136 return (props! as any).consumedSpace;1137 }11381139 async getCollectionOptions(collectionId: number) {1140 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1141 }11421143 /**1144 * Deletes onchain properties from the collection.1145 *1146 * @param signer keyring of signer1147 * @param collectionId ID of collection1148 * @param propertyKeys array of property keys to delete1149 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1150 * @returns ```true``` if extrinsic success, otherwise ```false```1151 */1152 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1153 const result = await this.helper.executeExtrinsic(1154 signer,1155 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1156 true,1157 );11581159 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1160 }11611162 /**1163 * Changes the owner of the token.1164 *1165 * @param signer keyring of signer1166 * @param collectionId ID of collection1167 * @param tokenId ID of token1168 * @param addressObj address of a new owner1169 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1170 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1171 * @returns true if the token success, otherwise false1172 */1173 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1174 const result = await this.helper.executeExtrinsic(1175 signer,1176 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1177 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1178 );11791180 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1181 }11821183 /**1184 *1185 * Change ownership of a token(s) on behalf of the owner.1186 *1187 * @param signer keyring of signer1188 * @param collectionId ID of collection1189 * @param tokenId ID of token1190 * @param fromAddressObj address on behalf of which the token will be sent1191 * @param toAddressObj new token owner1192 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1193 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1194 * @returns true if the token success, otherwise false1195 */1196 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1197 const result = await this.helper.executeExtrinsic(1198 signer,1199 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1200 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1201 );1202 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1203 }12041205 /**1206 *1207 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1208 *1209 * @param signer keyring of signer1210 * @param collectionId ID of collection1211 * @param tokenId ID of token1212 * @param amount amount of tokens to be burned. For NFT must be set to 1n1213 * @example burnToken(aliceKeyring, 10, 5);1214 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1215 */1216 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1217 const burnResult = await this.helper.executeExtrinsic(1218 signer,1219 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1220 true, // `Unable to burn token for ${label}`,1221 );1222 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1223 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1224 return burnedTokens.success;1225 }12261227 /**1228 * Destroys a concrete instance of NFT on behalf of the owner1229 *1230 * @param signer keyring of signer1231 * @param collectionId ID of collection1232 * @param tokenId ID of token1233 * @param fromAddressObj address on behalf of which the token will be burnt1234 * @param amount amount of tokens to be burned. For NFT must be set to 1n1235 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1236 * @returns ```true``` if extrinsic success, otherwise ```false```1237 */1238 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1239 const burnResult = await this.helper.executeExtrinsic(1240 signer,1241 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1242 true, // `Unable to burn token from for ${label}`,1243 );1244 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1245 return burnedTokens.success && burnedTokens.tokens.length > 0;1246 }12471248 /**1249 * Set, change, or remove approved address to transfer the ownership of the NFT.1250 *1251 * @param signer keyring of signer1252 * @param collectionId ID of collection1253 * @param tokenId ID of token1254 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1255 * @param amount amount of token to be approved. For NFT must be set to 1n1256 * @returns ```true``` if extrinsic success, otherwise ```false```1257 */1258 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1259 const approveResult = await this.helper.executeExtrinsic(1260 signer,1261 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1262 true, // `Unable to approve token for ${label}`,1263 );12641265 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1266 }12671268 /**1269 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1270 *1271 * @param signer keyring of signer1272 * @param collectionId ID of collection1273 * @param tokenId ID of token1274 * @param fromAddressObj Signer's Ethereum address containing her tokens1275 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1276 * @param amount amount of token to be approved. For NFT must be set to 1n1277 * @returns ```true``` if extrinsic success, otherwise ```false```1278 */1279 async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1280 const approveResult = await this.helper.executeExtrinsic(1281 signer,1282 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1283 true, // `Unable to approve token for ${label}`,1284 );12851286 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1287 }12881289 /**1290 * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1291 *1292 * @param signer keyring of signer1293 * @param collectionId ID of collection1294 * @param tokenId ID of token1295 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1296 * @param amount amount of token to be approved. For NFT must be set to 1n1297 * @returns ```true``` if extrinsic success, otherwise ```false```1298 */1299 async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1300 const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1301 return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1302 }13031304 /**1305 * Get the amount of token pieces approved to transfer or burn. Normally 0.1306 *1307 * @param collectionId ID of collection1308 * @param tokenId ID of token1309 * @param toAccountObj address which is approved to use token pieces1310 * @param fromAccountObj address which may have allowed the use of its owned tokens1311 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1312 * @returns number of approved to transfer pieces1313 */1314 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1315 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1316 }13171318 /**1319 * Get the last created token ID in a collection1320 *1321 * @param collectionId ID of collection1322 * @example getLastTokenId(10);1323 * @returns id of the last created token1324 */1325 async getLastTokenId(collectionId: number): Promise<number> {1326 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1327 }13281329 /**1330 * Check if token exists1331 *1332 * @param collectionId ID of collection1333 * @param tokenId ID of token1334 * @example doesTokenExist(10, 20);1335 * @returns true if the token exists, otherwise false1336 */1337 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1338 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1339 }1340}13411342class NFTnRFT extends CollectionGroup {1343 /**1344 * Get tokens owned by account1345 *1346 * @param collectionId ID of collection1347 * @param addressObj tokens owner1348 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1349 * @returns array of token ids owned by account1350 */1351 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1352 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1353 }13541355 /**1356 * Get token data1357 *1358 * @param collectionId ID of collection1359 * @param tokenId ID of token1360 * @param propertyKeys optionally filter the token properties to only these keys1361 * @param blockHashAt optionally query the data at some block with this hash1362 * @example getToken(10, 5);1363 * @returns human readable token data1364 */1365 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1366 properties: IProperty[];1367 owner: CrossAccountId;1368 normalizedOwner: CrossAccountId;1369 }| null> {1370 let tokenData;1371 if(typeof blockHashAt === 'undefined') {1372 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1373 }1374 else {1375 if(propertyKeys.length == 0) {1376 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1377 if(!collection) return null;1378 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1379 }1380 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1381 }1382 tokenData = tokenData.toHuman();1383 if (tokenData === null || tokenData.owner === null) return null;1384 const owner = {} as any;1385 for (const key of Object.keys(tokenData.owner)) {1386 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1387 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1388 : tokenData.owner[key];1389 }1390 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1391 return tokenData;1392 }13931394 /**1395 * Set permissions to change token properties1396 *1397 * @param signer keyring of signer1398 * @param collectionId ID of collection1399 * @param permissions permissions to change a property by the collection admin or token owner1400 * @example setTokenPropertyPermissions(1401 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1402 * )1403 * @returns true if extrinsic success otherwise false1404 */1405 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1406 const result = await this.helper.executeExtrinsic(1407 signer,1408 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1409 true,1410 );14111412 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1413 }14141415 /**1416 * Get token property permissions.1417 *1418 * @param collectionId ID of collection1419 * @param propertyKeys optionally filter the returned property permissions to only these keys1420 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1421 * @returns array of key-permission pairs1422 */1423 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1424 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1425 }14261427 /**1428 * Set token properties1429 *1430 * @param signer keyring of signer1431 * @param collectionId ID of collection1432 * @param tokenId ID of token1433 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1434 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1435 * @returns ```true``` if extrinsic success, otherwise ```false```1436 */1437 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1438 const result = await this.helper.executeExtrinsic(1439 signer,1440 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1441 true,1442 );14431444 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1445 }14461447 /**1448 * Get properties, metadata assigned to a token.1449 *1450 * @param collectionId ID of collection1451 * @param tokenId ID of token1452 * @param propertyKeys optionally filter the returned properties to only these keys1453 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1454 * @returns array of key-value pairs1455 */1456 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1457 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1458 }14591460 /**1461 * Delete the provided properties of a token1462 * @param signer keyring of signer1463 * @param collectionId ID of collection1464 * @param tokenId ID of token1465 * @param propertyKeys property keys to be deleted1466 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1467 * @returns ```true``` if extrinsic success, otherwise ```false```1468 */1469 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1470 const result = await this.helper.executeExtrinsic(1471 signer,1472 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1473 true,1474 );14751476 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1477 }14781479 /**1480 * Mint new collection1481 *1482 * @param signer keyring of signer1483 * @param collectionOptions basic collection options and properties1484 * @param mode NFT or RFT type of a collection1485 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1486 * @returns object of the created collection1487 */1488 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1489 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1490 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1491 for (const key of ['name', 'description', 'tokenPrefix']) {1492 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);1493 }1494 const creationResult = await this.helper.executeExtrinsic(1495 signer,1496 'api.tx.unique.createCollectionEx', [collectionOptions],1497 true, // errorLabel,1498 );1499 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1500 }15011502 getCollectionObject(_collectionId: number): any {1503 return null;1504 }15051506 getTokenObject(_collectionId: number, _tokenId: number): any {1507 return null;1508 }15091510 /**1511 * Tells whether the given `owner` approves the `operator`.1512 * @param collectionId ID of collection1513 * @param owner owner address1514 * @param operator operator addrees1515 * @returns true if operator is enabled1516 */1517 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1518 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1519 }15201521 /** Sets or unsets the approval of a given operator.1522 * The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1523 * @param operator Operator1524 * @param approved Should operator status be granted or revoked?1525 * @returns ```true``` if extrinsic success, otherwise ```false```1526 */1527 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1528 const result = await this.helper.executeExtrinsic(1529 signer,1530 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1531 true,1532 );1533 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1534 }1535}153615371538class NFTGroup extends NFTnRFT {1539 /**1540 * Get collection object1541 * @param collectionId ID of collection1542 * @example getCollectionObject(2);1543 * @returns instance of UniqueNFTCollection1544 */1545 getCollectionObject(collectionId: number): UniqueNFTCollection {1546 return new UniqueNFTCollection(collectionId, this.helper);1547 }15481549 /**1550 * Get token object1551 * @param collectionId ID of collection1552 * @param tokenId ID of token1553 * @example getTokenObject(10, 5);1554 * @returns instance of UniqueNFTToken1555 */1556 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1557 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1558 }15591560 /**1561 * Get token's owner1562 * @param collectionId ID of collection1563 * @param tokenId ID of token1564 * @param blockHashAt optionally query the data at the block with this hash1565 * @example getTokenOwner(10, 5);1566 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1567 */1568 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1569 let owner;1570 if (typeof blockHashAt === 'undefined') {1571 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1572 } else {1573 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1574 }1575 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1576 }15771578 /**1579 * Is token approved to transfer1580 * @param collectionId ID of collection1581 * @param tokenId ID of token1582 * @param toAccountObj address to be approved1583 * @returns ```true``` if extrinsic success, otherwise ```false```1584 */1585 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1586 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1587 }15881589 /**1590 * Changes the owner of the token.1591 *1592 * @param signer keyring of signer1593 * @param collectionId ID of collection1594 * @param tokenId ID of token1595 * @param addressObj address of a new owner1596 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1597 * @returns ```true``` if extrinsic success, otherwise ```false```1598 */1599 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1600 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1601 }16021603 /**1604 *1605 * Change ownership of a NFT on behalf of the owner.1606 *1607 * @param signer keyring of signer1608 * @param collectionId ID of collection1609 * @param tokenId ID of token1610 * @param fromAddressObj address on behalf of which the token will be sent1611 * @param toAddressObj new token owner1612 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1613 * @returns ```true``` if extrinsic success, otherwise ```false```1614 */1615 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1616 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1617 }16181619 /**1620 * Recursively find the address that owns the token1621 * @param collectionId ID of collection1622 * @param tokenId ID of token1623 * @param blockHashAt1624 * @example getTokenTopmostOwner(10, 5);1625 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1626 */1627 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1628 let owner;1629 if (typeof blockHashAt === 'undefined') {1630 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1631 } else {1632 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1633 }16341635 if (owner === null) return null;16361637 return owner.toHuman();1638 }16391640 /**1641 * Get tokens nested in the provided token1642 * @param collectionId ID of collection1643 * @param tokenId ID of token1644 * @param blockHashAt optionally query the data at the block with this hash1645 * @example getTokenChildren(10, 5);1646 * @returns tokens whose depth of nesting is <= 51647 */1648 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1649 let children;1650 if(typeof blockHashAt === 'undefined') {1651 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1652 } else {1653 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1654 }16551656 return children.toJSON().map((x: any) => {1657 return {collectionId: x.collection, tokenId: x.token};1658 });1659 }16601661 /**1662 * Nest one token into another1663 * @param signer keyring of signer1664 * @param tokenObj token to be nested1665 * @param rootTokenObj token to be parent1666 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1667 * @returns ```true``` if extrinsic success, otherwise ```false```1668 */1669 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1670 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1671 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1672 if(!result) {1673 throw Error('Unable to nest token!');1674 }1675 return result;1676 }16771678 /**1679 * Remove token from nested state1680 * @param signer keyring of signer1681 * @param tokenObj token to unnest1682 * @param rootTokenObj parent of a token1683 * @param toAddressObj address of a new token owner1684 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1685 * @returns ```true``` if extrinsic success, otherwise ```false```1686 */1687 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1688 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1689 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1690 if(!result) {1691 throw Error('Unable to unnest token!');1692 }1693 return result;1694 }16951696 /**1697 * Mint new collection1698 * @param signer keyring of signer1699 * @param collectionOptions Collection options1700 * @example1701 * mintCollection(aliceKeyring, {1702 * name: 'New',1703 * description: 'New collection',1704 * tokenPrefix: 'NEW',1705 * })1706 * @returns object of the created collection1707 */1708 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1709 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1710 }17111712 /**1713 * Mint new token1714 * @param signer keyring of signer1715 * @param data token data1716 * @returns created token object1717 */1718 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1719 const creationResult = await this.helper.executeExtrinsic(1720 signer,1721 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1722 nft: {1723 properties: data.properties,1724 },1725 }],1726 true,1727 );1728 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1729 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1730 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1731 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1732 }17331734 /**1735 * Mint multiple NFT tokens1736 * @param signer keyring of signer1737 * @param collectionId ID of collection1738 * @param tokens array of tokens with owner and properties1739 * @example1740 * mintMultipleTokens(aliceKeyring, 10, [{1741 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1742 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1743 * },{1744 * owner: {Ethereum: "0x9F0583DbB855d..."},1745 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1746 * }]);1747 * @returns ```true``` if extrinsic success, otherwise ```false```1748 */1749 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1750 const creationResult = await this.helper.executeExtrinsic(1751 signer,1752 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1753 true,1754 );1755 const collection = this.getCollectionObject(collectionId);1756 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1757 }17581759 /**1760 * Mint multiple NFT tokens with one owner1761 * @param signer keyring of signer1762 * @param collectionId ID of collection1763 * @param owner tokens owner1764 * @param tokens array of tokens with owner and properties1765 * @example1766 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1767 * properties: [{1768 * key: "gender",1769 * value: "female",1770 * },{1771 * key: "age",1772 * value: "33",1773 * }],1774 * }]);1775 * @returns array of newly created tokens1776 */1777 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1778 const rawTokens = [];1779 for (const token of tokens) {1780 const raw = {NFT: {properties: token.properties}};1781 rawTokens.push(raw);1782 }1783 const creationResult = await this.helper.executeExtrinsic(1784 signer,1785 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1786 true,1787 );1788 const collection = this.getCollectionObject(collectionId);1789 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1790 }17911792 /**1793 * Set, change, or remove approved address to transfer the ownership of the NFT.1794 *1795 * @param signer keyring of signer1796 * @param collectionId ID of collection1797 * @param tokenId ID of token1798 * @param toAddressObj address to approve1799 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1800 * @returns ```true``` if extrinsic success, otherwise ```false```1801 */1802 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1803 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1804 }1805}180618071808class RFTGroup extends NFTnRFT {1809 /**1810 * Get collection object1811 * @param collectionId ID of collection1812 * @example getCollectionObject(2);1813 * @returns instance of UniqueRFTCollection1814 */1815 getCollectionObject(collectionId: number): UniqueRFTCollection {1816 return new UniqueRFTCollection(collectionId, this.helper);1817 }18181819 /**1820 * Get token object1821 * @param collectionId ID of collection1822 * @param tokenId ID of token1823 * @example getTokenObject(10, 5);1824 * @returns instance of UniqueNFTToken1825 */1826 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1827 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1828 }18291830 /**1831 * Get top 10 token owners with the largest number of pieces1832 * @param collectionId ID of collection1833 * @param tokenId ID of token1834 * @example getTokenTop10Owners(10, 5);1835 * @returns array of top 10 owners1836 */1837 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1838 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1839 }18401841 /**1842 * Get number of pieces owned by address1843 * @param collectionId ID of collection1844 * @param tokenId ID of token1845 * @param addressObj address token owner1846 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1847 * @returns number of pieces ownerd by address1848 */1849 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1850 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1851 }18521853 /**1854 * Transfer pieces of token to another address1855 * @param signer keyring of signer1856 * @param collectionId ID of collection1857 * @param tokenId ID of token1858 * @param addressObj address of a new owner1859 * @param amount number of pieces to be transfered1860 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1861 * @returns ```true``` if extrinsic success, otherwise ```false```1862 */1863 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1864 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1865 }18661867 /**1868 * Change ownership of some pieces of RFT on behalf of the owner.1869 * @param signer keyring of signer1870 * @param collectionId ID of collection1871 * @param tokenId ID of token1872 * @param fromAddressObj address on behalf of which the token will be sent1873 * @param toAddressObj new token owner1874 * @param amount number of pieces to be transfered1875 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1876 * @returns ```true``` if extrinsic success, otherwise ```false```1877 */1878 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1879 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1880 }18811882 /**1883 * Mint new collection1884 * @param signer keyring of signer1885 * @param collectionOptions Collection options1886 * @example1887 * mintCollection(aliceKeyring, {1888 * name: 'New',1889 * description: 'New collection',1890 * tokenPrefix: 'NEW',1891 * })1892 * @returns object of the created collection1893 */1894 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1895 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1896 }18971898 /**1899 * Mint new token1900 * @param signer keyring of signer1901 * @param data token data1902 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1903 * @returns created token object1904 */1905 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1906 const creationResult = await this.helper.executeExtrinsic(1907 signer,1908 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1909 refungible: {1910 pieces: data.pieces,1911 properties: data.properties,1912 },1913 }],1914 true,1915 );1916 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1917 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1918 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1919 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1920 }19211922 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1923 throw Error('Not implemented');1924 const creationResult = await this.helper.executeExtrinsic(1925 signer,1926 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1927 true, // `Unable to mint RFT tokens for ${label}`,1928 );1929 const collection = this.getCollectionObject(collectionId);1930 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1931 }19321933 /**1934 * Mint multiple RFT tokens with one owner1935 * @param signer keyring of signer1936 * @param collectionId ID of collection1937 * @param owner tokens owner1938 * @param tokens array of tokens with properties and pieces1939 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1940 * @returns array of newly created RFT tokens1941 */1942 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1943 const rawTokens = [];1944 for (const token of tokens) {1945 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1946 rawTokens.push(raw);1947 }1948 const creationResult = await this.helper.executeExtrinsic(1949 signer,1950 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1951 true,1952 );1953 const collection = this.getCollectionObject(collectionId);1954 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1955 }19561957 /**1958 * Destroys a concrete instance of RFT.1959 * @param signer keyring of signer1960 * @param collectionId ID of collection1961 * @param tokenId ID of token1962 * @param amount number of pieces to be burnt1963 * @example burnToken(aliceKeyring, 10, 5);1964 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1965 */1966 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1967 return await super.burnToken(signer, collectionId, tokenId, amount);1968 }19691970 /**1971 * Destroys a concrete instance of RFT on behalf of the owner.1972 * @param signer keyring of signer1973 * @param collectionId ID of collection1974 * @param tokenId ID of token1975 * @param fromAddressObj address on behalf of which the token will be burnt1976 * @param amount number of pieces to be burnt1977 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1978 * @returns ```true``` if extrinsic success, otherwise ```false```1979 */1980 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1981 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1982 }19831984 /**1985 * Set, change, or remove approved address to transfer the ownership of the RFT.1986 *1987 * @param signer keyring of signer1988 * @param collectionId ID of collection1989 * @param tokenId ID of token1990 * @param toAddressObj address to approve1991 * @param amount number of pieces to be approved1992 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1993 * @returns true if the token success, otherwise false1994 */1995 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1996 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1997 }19981999 /**2000 * Get total number of pieces2001 * @param collectionId ID of collection2002 * @param tokenId ID of token2003 * @example getTokenTotalPieces(10, 5);2004 * @returns number of pieces2005 */2006 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2007 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2008 }20092010 /**2011 * Change number of token pieces. Signer must be the owner of all token pieces.2012 * @param signer keyring of signer2013 * @param collectionId ID of collection2014 * @param tokenId ID of token2015 * @param amount new number of pieces2016 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2017 * @returns true if the repartion was success, otherwise false2018 */2019 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2020 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2021 const repartitionResult = await this.helper.executeExtrinsic(2022 signer,2023 'api.tx.unique.repartition', [collectionId, tokenId, amount],2024 true,2025 );2026 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2027 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2028 }2029}203020312032class FTGroup extends CollectionGroup {2033 /**2034 * Get collection object2035 * @param collectionId ID of collection2036 * @example getCollectionObject(2);2037 * @returns instance of UniqueFTCollection2038 */2039 getCollectionObject(collectionId: number): UniqueFTCollection {2040 return new UniqueFTCollection(collectionId, this.helper);2041 }20422043 /**2044 * Mint new fungible collection2045 * @param signer keyring of signer2046 * @param collectionOptions Collection options2047 * @param decimalPoints number of token decimals2048 * @example2049 * mintCollection(aliceKeyring, {2050 * name: 'New',2051 * description: 'New collection',2052 * tokenPrefix: 'NEW',2053 * }, 18)2054 * @returns newly created fungible collection2055 */2056 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2057 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2058 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2059 collectionOptions.mode = {fungible: decimalPoints};2060 for (const key of ['name', 'description', 'tokenPrefix']) {2061 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);2062 }2063 const creationResult = await this.helper.executeExtrinsic(2064 signer,2065 'api.tx.unique.createCollectionEx', [collectionOptions],2066 true,2067 );2068 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2069 }20702071 /**2072 * Mint tokens2073 * @param signer keyring of signer2074 * @param collectionId ID of collection2075 * @param owner address owner of new tokens2076 * @param amount amount of tokens to be meanted2077 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2078 * @returns ```true``` if extrinsic success, otherwise ```false```2079 */2080 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2081 const creationResult = await this.helper.executeExtrinsic(2082 signer,2083 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2084 fungible: {2085 value: amount,2086 },2087 }],2088 true, // `Unable to mint fungible tokens for ${label}`,2089 );2090 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2091 }20922093 /**2094 * Mint multiple Fungible tokens with one owner2095 * @param signer keyring of signer2096 * @param collectionId ID of collection2097 * @param owner tokens owner2098 * @param tokens array of tokens with properties and pieces2099 * @returns ```true``` if extrinsic success, otherwise ```false```2100 */2101 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2102 const rawTokens = [];2103 for (const token of tokens) {2104 const raw = {Fungible: {Value: token.value}};2105 rawTokens.push(raw);2106 }2107 const creationResult = await this.helper.executeExtrinsic(2108 signer,2109 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2110 true,2111 );2112 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2113 }21142115 /**2116 * Get the top 10 owners with the largest balance for the Fungible collection2117 * @param collectionId ID of collection2118 * @example getTop10Owners(10);2119 * @returns array of ```ICrossAccountId```2120 */2121 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2122 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2123 }21242125 /**2126 * Get account balance2127 * @param collectionId ID of collection2128 * @param addressObj address of owner2129 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2130 * @returns amount of fungible tokens owned by address2131 */2132 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2133 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2134 }21352136 /**2137 * Transfer tokens to address2138 * @param signer keyring of signer2139 * @param collectionId ID of collection2140 * @param toAddressObj address recipient2141 * @param amount amount of tokens to be sent2142 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2143 * @returns ```true``` if extrinsic success, otherwise ```false```2144 */2145 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2146 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2147 }21482149 /**2150 * Transfer some tokens on behalf of the owner.2151 * @param signer keyring of signer2152 * @param collectionId ID of collection2153 * @param fromAddressObj address on behalf of which tokens will be sent2154 * @param toAddressObj address where token to be sent2155 * @param amount number of tokens to be sent2156 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2157 * @returns ```true``` if extrinsic success, otherwise ```false```2158 */2159 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2160 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2161 }21622163 /**2164 * Destroy some amount of tokens2165 * @param signer keyring of signer2166 * @param collectionId ID of collection2167 * @param amount amount of tokens to be destroyed2168 * @example burnTokens(aliceKeyring, 10, 1000n);2169 * @returns ```true``` if extrinsic success, otherwise ```false```2170 */2171 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2172 return await super.burnToken(signer, collectionId, 0, amount);2173 }21742175 /**2176 * Burn some tokens on behalf of the owner.2177 * @param signer keyring of signer2178 * @param collectionId ID of collection2179 * @param fromAddressObj address on behalf of which tokens will be burnt2180 * @param amount amount of tokens to be burnt2181 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2182 * @returns ```true``` if extrinsic success, otherwise ```false```2183 */2184 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2185 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2186 }21872188 /**2189 * Get total collection supply2190 * @param collectionId2191 * @returns2192 */2193 async getTotalPieces(collectionId: number): Promise<bigint> {2194 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2195 }21962197 /**2198 * Set, change, or remove approved address to transfer tokens.2199 *2200 * @param signer keyring of signer2201 * @param collectionId ID of collection2202 * @param toAddressObj address to be approved2203 * @param amount amount of tokens to be approved2204 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2205 * @returns ```true``` if extrinsic success, otherwise ```false```2206 */2207 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2208 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2209 }22102211 /**2212 * Get amount of fungible tokens approved to transfer2213 * @param collectionId ID of collection2214 * @param fromAddressObj owner of tokens2215 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2216 * @returns number of tokens approved for the transfer2217 */2218 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2219 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2220 }2221}222222232224class ChainGroup extends HelperGroup<ChainHelperBase> {2225 /**2226 * Get system properties of a chain2227 * @example getChainProperties();2228 * @returns ss58Format, token decimals, and token symbol2229 */2230 getChainProperties(): IChainProperties {2231 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2232 return {2233 ss58Format: properties.ss58Format.toJSON(),2234 tokenDecimals: properties.tokenDecimals.toJSON(),2235 tokenSymbol: properties.tokenSymbol.toJSON(),2236 };2237 }22382239 /**2240 * Get chain header2241 * @example getLatestBlockNumber();2242 * @returns the number of the last block2243 */2244 async getLatestBlockNumber(): Promise<number> {2245 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2246 }22472248 /**2249 * Get block hash by block number2250 * @param blockNumber number of block2251 * @example getBlockHashByNumber(12345);2252 * @returns hash of a block2253 */2254 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2255 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2256 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2257 return blockHash;2258 }22592260 // TODO add docs2261 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2262 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2263 if (!blockHash) return null;2264 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2265 }22662267 /**2268 * Get latest relay block2269 * @returns {number} relay block2270 */2271 async getRelayBlockNumber(): Promise<bigint> {2272 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2273 return BigInt(blockNumber);2274 }22752276 /**2277 * Get account nonce2278 * @param address substrate address2279 * @example getNonce("5GrwvaEF5zXb26Fz...");2280 * @returns number, account's nonce2281 */2282 async getNonce(address: TSubstrateAccount): Promise<number> {2283 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2284 }2285}22862287class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2288 /**2289 * Get substrate address balance2290 * @param address substrate address2291 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2292 * @returns amount of tokens on address2293 */2294 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2295 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2296 }22972298 /**2299 * Transfer tokens to substrate address2300 * @param signer keyring of signer2301 * @param address substrate address of a recipient2302 * @param amount amount of tokens to be transfered2303 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2304 * @returns ```true``` if extrinsic success, otherwise ```false```2305 */2306 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2307 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}`*/);23082309 let transfer = {from: null, to: null, amount: 0n} as any;2310 result.result.events.forEach(({event: {data, method, section}}) => {2311 if ((section === 'balances') && (method === 'Transfer')) {2312 transfer = {2313 from: this.helper.address.normalizeSubstrate(data[0]),2314 to: this.helper.address.normalizeSubstrate(data[1]),2315 amount: BigInt(data[2]),2316 };2317 }2318 });2319 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2320 && this.helper.address.normalizeSubstrate(address) === transfer.to2321 && BigInt(amount) === transfer.amount;2322 return isSuccess;2323 }23242325 /**2326 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2327 * @param address substrate address2328 * @returns2329 */2330 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2331 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2332 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2333 }23342335 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2336 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2337 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2338 }2339}23402341class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2342 /**2343 * Get ethereum address balance2344 * @param address ethereum address2345 * @example getEthereum("0x9F0583DbB855d...")2346 * @returns amount of tokens on address2347 */2348 async getEthereum(address: TEthereumAccount): Promise<bigint> {2349 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2350 }23512352 /**2353 * Transfer tokens to address2354 * @param signer keyring of signer2355 * @param address Ethereum address of a recipient2356 * @param amount amount of tokens to be transfered2357 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2358 * @returns ```true``` if extrinsic success, otherwise ```false```2359 */2360 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2361 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23622363 let transfer = {from: null, to: null, amount: 0n} as any;2364 result.result.events.forEach(({event: {data, method, section}}) => {2365 if ((section === 'balances') && (method === 'Transfer')) {2366 transfer = {2367 from: data[0].toString(),2368 to: data[1].toString(),2369 amount: BigInt(data[2]),2370 };2371 }2372 });2373 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2374 && address === transfer.to2375 && BigInt(amount) === transfer.amount;2376 return isSuccess;2377 }2378}23792380class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2381 subBalanceGroup: SubstrateBalanceGroup<T>;2382 ethBalanceGroup: EthereumBalanceGroup<T>;23832384 constructor(helper: T) {2385 super(helper);2386 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2387 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2388 }23892390 getCollectionCreationPrice(): bigint {2391 return 2n * this.getOneTokenNominal();2392 }2393 /**2394 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2395 * @example getOneTokenNominal()2396 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2397 */2398 getOneTokenNominal(): bigint {2399 const chainProperties = this.helper.chain.getChainProperties();2400 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2401 }24022403 /**2404 * Get substrate address balance2405 * @param address substrate address2406 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2407 * @returns amount of tokens on address2408 */2409 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2410 return this.subBalanceGroup.getSubstrate(address);2411 }24122413 /**2414 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2415 * @param address substrate address2416 * @returns2417 */2418 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2419 return this.subBalanceGroup.getSubstrateFull(address);2420 }24212422 /**2423 * Get locked balances2424 * @param address substrate address2425 * @returns locked balances with reason via api.query.balances.locks2426 */2427 getLocked(address: TSubstrateAccount) {2428 return this.subBalanceGroup.getLocked(address);2429 }24302431 /**2432 * Get ethereum address balance2433 * @param address ethereum address2434 * @example getEthereum("0x9F0583DbB855d...")2435 * @returns amount of tokens on address2436 */2437 getEthereum(address: TEthereumAccount): Promise<bigint> {2438 return this.ethBalanceGroup.getEthereum(address);2439 }24402441 /**2442 * Transfer tokens to substrate address2443 * @param signer keyring of signer2444 * @param address substrate address of a recipient2445 * @param amount amount of tokens to be transfered2446 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2447 * @returns ```true``` if extrinsic success, otherwise ```false```2448 */2449 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2450 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2451 }24522453 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2454 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24552456 let transfer = {from: null, to: null, amount: 0n} as any;2457 result.result.events.forEach(({event: {data, method, section}}) => {2458 if ((section === 'balances') && (method === 'Transfer')) {2459 transfer = {2460 from: this.helper.address.normalizeSubstrate(data[0]),2461 to: this.helper.address.normalizeSubstrate(data[1]),2462 amount: BigInt(data[2]),2463 };2464 }2465 });2466 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2467 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2468 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2469 return isSuccess;2470 }24712472 /**2473 * Transfer tokens with the unlock period2474 * @param signer signers Keyring2475 * @param address Substrate address of recipient2476 * @param schedule Schedule params2477 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002478 */2479 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2480 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2481 const event = result.result.events2482 .find(e => e.event.section === 'vesting' &&2483 e.event.method === 'VestingScheduleAdded' &&2484 e.event.data[0].toHuman() === signer.address);2485 if (!event) throw Error('Cannot find transfer in events');2486 }24872488 /**2489 * Get schedule for recepient of vested transfer2490 * @param address Substrate address of recipient2491 * @returns2492 */2493 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2494 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2495 return schedule.map((schedule: any) => {2496 return {2497 start: BigInt(schedule.start),2498 period: BigInt(schedule.period),2499 periodCount: BigInt(schedule.periodCount),2500 perPeriod: BigInt(schedule.perPeriod),2501 };2502 });2503 }25042505 /**2506 * Claim vested tokens2507 * @param signer signers Keyring2508 */2509 async claim(signer: TSigner) {2510 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2511 const event = result.result.events2512 .find(e => e.event.section === 'vesting' &&2513 e.event.method === 'Claimed' &&2514 e.event.data[0].toHuman() === signer.address);2515 if (!event) throw Error('Cannot find claim in events');2516 }2517}25182519class AddressGroup extends HelperGroup<ChainHelperBase> {2520 /**2521 * Normalizes the address to the specified ss58 format, by default ```42```.2522 * @param address substrate address2523 * @param ss58Format format for address conversion, by default ```42```2524 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2525 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2526 */2527 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2528 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2529 }25302531 /**2532 * Get address in the connected chain format2533 * @param address substrate address2534 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2535 * @returns address in chain format2536 */2537 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2538 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2539 }25402541 /**2542 * Get substrate mirror of an ethereum address2543 * @param ethAddress ethereum address2544 * @param toChainFormat false for normalized account2545 * @example ethToSubstrate('0x9F0583DbB855d...')2546 * @returns substrate mirror of a provided ethereum address2547 */2548 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2549 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2550 }25512552 /**2553 * Get ethereum mirror of a substrate address2554 * @param subAddress substrate account2555 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2556 * @returns ethereum mirror of a provided substrate address2557 */2558 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2559 return CrossAccountId.translateSubToEth(subAddress);2560 }25612562 /**2563 * Encode key to substrate address2564 * @param key key for encoding address2565 * @param ss58Format prefix for encoding to the address of the corresponding network2566 * @returns encoded substrate address2567 */2568 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2569 const u8a :Uint8Array = typeof key === 'string'2570 ? hexToU8a(key)2571 : typeof key === 'bigint'2572 ? hexToU8a(key.toString(16))2573 : key;25742575 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2576 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2577 }25782579 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2580 if (!allowedDecodedLengths.includes(u8a.length)) {2581 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2582 }25832584 const u8aPrefix = ss58Format < 642585 ? new Uint8Array([ss58Format])2586 : new Uint8Array([2587 ((ss58Format & 0xfc) >> 2) | 0x40,2588 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2589 ]);25902591 const input = u8aConcat(u8aPrefix, u8a);25922593 return base58Encode(u8aConcat(2594 input,2595 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2596 ));2597 }25982599 /**2600 * Restore substrate address from bigint representation2601 * @param number decimal representation of substrate address2602 * @returns substrate address2603 */2604 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2605 if (this.helper.api === null) {2606 throw 'Not connected';2607 }2608 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2609 if (res === undefined || res === null) {2610 throw 'Restore address error';2611 }2612 return res.toString();2613 }26142615 /**2616 * Convert etherium cross account id to substrate cross account id2617 * @param ethCrossAccount etherium cross account2618 * @returns substrate cross account id2619 */2620 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2621 if (ethCrossAccount.sub === '0') {2622 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2623 }26242625 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2626 return {Substrate: ss58};2627 }26282629 paraSiblingSovereignAccount(paraid: number) {2630 // We are getting a *sibling* parachain sovereign account,2631 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2632 const siblingPrefix = '0x7369626c';26332634 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2635 const suffix = '000000000000000000000000000000000000000000000000';26362637 return siblingPrefix + encodedParaId + suffix;2638 }2639}26402641class StakingGroup extends HelperGroup<UniqueHelper> {2642 /**2643 * Stake tokens for App Promotion2644 * @param signer keyring of signer2645 * @param amountToStake amount of tokens to stake2646 * @param label extra label for log2647 * @returns2648 */2649 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2650 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2651 const _stakeResult = await this.helper.executeExtrinsic(2652 signer, 'api.tx.appPromotion.stake',2653 [amountToStake], true,2654 );2655 // TODO extract info from stakeResult2656 return true;2657 }26582659 /**2660 * Unstake tokens for App Promotion2661 * @param signer keyring of signer2662 * @param amountToUnstake amount of tokens to unstake2663 * @param label extra label for log2664 * @returns block number where balances will be unlocked2665 */2666 async unstake(signer: TSigner, label?: string): Promise<number> {2667 if(typeof label === 'undefined') label = `${signer.address}`;2668 const _unstakeResult = await this.helper.executeExtrinsic(2669 signer, 'api.tx.appPromotion.unstake',2670 [], true,2671 );2672 // TODO extract block number fron events2673 return 1;2674 }26752676 /**2677 * Get total staked amount for address2678 * @param address substrate or ethereum address2679 * @returns total staked amount2680 */2681 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2682 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2683 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2684 }26852686 /**2687 * Get total staked per block2688 * @param address substrate or ethereum address2689 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2690 */2691 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2692 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2693 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2694 return {2695 block: block.toBigInt(),2696 amount: amount.toBigInt(),2697 };2698 });2699 }27002701 /**2702 * Get total pending unstake amount for address2703 * @param address substrate or ethereum address2704 * @returns total pending unstake amount2705 */2706 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2707 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2708 }27092710 /**2711 * Get pending unstake amount per block for address2712 * @param address substrate or ethereum address2713 * @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 block2714 */2715 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2716 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2717 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2718 return {2719 block: block.toBigInt(),2720 amount: amount.toBigInt(),2721 };2722 });2723 return result;2724 }2725}27262727class SchedulerGroup extends HelperGroup<UniqueHelper> {2728 constructor(helper: UniqueHelper) {2729 super(helper);2730 }27312732 cancelScheduled(signer: TSigner, scheduledId: string) {2733 return this.helper.executeExtrinsic(2734 signer,2735 'api.tx.scheduler.cancelNamed',2736 [scheduledId],2737 true,2738 );2739 }27402741 changePriority(signer: TSigner, scheduledId: string, priority: number) {2742 return this.helper.executeExtrinsic(2743 signer,2744 'api.tx.scheduler.changeNamedPriority',2745 [scheduledId, priority],2746 true,2747 );2748 }27492750 scheduleAt<T extends UniqueHelper>(2751 executionBlockNumber: number,2752 options: ISchedulerOptions = {},2753 ) {2754 return this.schedule<T>('schedule', executionBlockNumber, options);2755 }27562757 scheduleAfter<T extends UniqueHelper>(2758 blocksBeforeExecution: number,2759 options: ISchedulerOptions = {},2760 ) {2761 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2762 }27632764 schedule<T extends UniqueHelper>(2765 scheduleFn: 'schedule' | 'scheduleAfter',2766 blocksNum: number,2767 options: ISchedulerOptions = {},2768 ) {2769 // eslint-disable-next-line @typescript-eslint/naming-convention2770 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2771 return this.helper.clone(ScheduledHelperType, {2772 scheduleFn,2773 blocksNum,2774 options,2775 }) as T;2776 }2777}27782779class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2780 //todo:collator documentation2781 addInvulnerable(signer: TSigner, address: string) {2782 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2783 }27842785 removeInvulnerable(signer: TSigner, address: string) {2786 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2787 }27882789 async getInvulnerables(): Promise<string[]> {2790 return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2791 }27922793 /** and also total max invulnerables */2794 maxCollators(): number {2795 return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2796 }27972798 async getDesiredCollators(): Promise<number> {2799 return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2800 }28012802 setLicenseBond(signer: TSigner, amount: bigint) {2803 return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2804 }28052806 async getLicenseBond(): Promise<bigint> {2807 return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2808 }28092810 obtainLicense(signer: TSigner) {2811 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2812 }28132814 releaseLicense(signer: TSigner) {2815 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2816 }28172818 forceReleaseLicense(signer: TSigner, released: string) {2819 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2820 }28212822 async hasLicense(address: string): Promise<bigint> {2823 return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2824 }28252826 onboard(signer: TSigner) {2827 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2828 }28292830 offboard(signer: TSigner) {2831 return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2832 }28332834 async getCandidates(): Promise<string[]> {2835 return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2836 }2837}28382839class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2840 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2841 await this.helper.executeExtrinsic(2842 signer,2843 'api.tx.foreignAssets.registerForeignAsset',2844 [ownerAddress, location, metadata],2845 true,2846 );2847 }28482849 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2850 await this.helper.executeExtrinsic(2851 signer,2852 'api.tx.foreignAssets.updateForeignAsset',2853 [foreignAssetId, location, metadata],2854 true,2855 );2856 }2857}28582859class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2860 palletName: string;28612862 constructor(helper: T, palletName: string) {2863 super(helper);28642865 this.palletName = palletName;2866 }28672868 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2869 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2870 }28712872 async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2873 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2874 }28752876 async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2877 const destination = {2878 V1: {2879 parents: 0,2880 interior: {2881 X1: {2882 Parachain: destinationParaId,2883 },2884 },2885 },2886 };28872888 const beneficiary = {2889 V1: {2890 parents: 0,2891 interior: {2892 X1: {2893 AccountId32: {2894 network: 'Any',2895 id: targetAccount,2896 },2897 },2898 },2899 },2900 };29012902 const assets = {2903 V1: [2904 {2905 id: {2906 Concrete: {2907 parents: 0,2908 interior: 'Here',2909 },2910 },2911 fun: {2912 Fungible: amount,2913 },2914 },2915 ],2916 };29172918 const feeAssetItem = 0;29192920 await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2921 }2922}29232924class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2925 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2926 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2927 }29282929 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2930 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2931 }29322933 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2934 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2935 }2936}29372938class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2939 async accounts(address: string, currencyId: any) {2940 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2941 return BigInt(free);2942 }2943}29442945class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2946 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2947 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2948 }29492950 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2951 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2952 }29532954 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2955 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2956 }29572958 async account(assetId: string | number, address: string) {2959 const accountAsset = (2960 await this.helper.callRpc('api.query.assets.account', [assetId, address])2961 ).toJSON()! as any;29622963 if (accountAsset !== null) {2964 return BigInt(accountAsset['balance']);2965 } else {2966 return null;2967 }2968 }2969}29702971class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2972 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2973 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2974 }2975}29762977class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2978 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2979 const apiPrefix = 'api.tx.assetManager.';29802981 const registerTx = this.helper.constructApiCall(2982 apiPrefix + 'registerForeignAsset',2983 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2984 );29852986 const setUnitsTx = this.helper.constructApiCall(2987 apiPrefix + 'setAssetUnitsPerSecond',2988 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2989 );29902991 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2992 const encodedProposal = batchCall?.method.toHex() || '';2993 return encodedProposal;2994 }29952996 async assetTypeId(location: any) {2997 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2998 }2999}30003001class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3002 notePreimagePallet: string;30033004 constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3005 super(helper);3006 this.notePreimagePallet = options.notePreimagePallet;3007 }30083009 async notePreimage(signer: TSigner, encodedProposal: string) {3010 await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3011 }30123013 externalProposeMajority(proposal: any) {3014 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3015 }30163017 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3018 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3019 }30203021 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3022 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3023 }3024}30253026class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3027 collective: string;30283029 constructor(helper: MoonbeamHelper, collective: string) {3030 super(helper);30313032 this.collective = collective;3033 }30343035 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3036 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3037 }30383039 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3040 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3041 }30423043 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3044 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3045 }30463047 async proposalCount() {3048 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3049 }3050}30513052export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3053export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;30543055export class UniqueHelper extends ChainHelperBase {3056 balance: BalanceGroup<UniqueHelper>;3057 collection: CollectionGroup;3058 nft: NFTGroup;3059 rft: RFTGroup;3060 ft: FTGroup;3061 staking: StakingGroup;3062 scheduler: SchedulerGroup;3063 collatorSelection: CollatorSelectionGroup;3064 foreignAssets: ForeignAssetsGroup;3065 xcm: XcmGroup<UniqueHelper>;3066 xTokens: XTokensGroup<UniqueHelper>;3067 tokens: TokensGroup<UniqueHelper>;30683069 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3070 super(logger, options.helperBase ?? UniqueHelper);30713072 this.balance = new BalanceGroup(this);3073 this.collection = new CollectionGroup(this);3074 this.nft = new NFTGroup(this);3075 this.rft = new RFTGroup(this);3076 this.ft = new FTGroup(this);3077 this.staking = new StakingGroup(this);3078 this.scheduler = new SchedulerGroup(this);3079 this.collatorSelection = new CollatorSelectionGroup(this);3080 this.foreignAssets = new ForeignAssetsGroup(this);3081 this.xcm = new XcmGroup(this, 'polkadotXcm');3082 this.xTokens = new XTokensGroup(this);3083 this.tokens = new TokensGroup(this);3084 }30853086 getSudo<T extends UniqueHelper>() {3087 // eslint-disable-next-line @typescript-eslint/naming-convention3088 const SudoHelperType = SudoHelper(this.helperBase);3089 return this.clone(SudoHelperType) as T;3090 }3091}30923093export class XcmChainHelper extends ChainHelperBase {3094 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3095 const wsProvider = new WsProvider(wsEndpoint);3096 this.api = new ApiPromise({3097 provider: wsProvider,3098 });3099 await this.api.isReadyOrError;3100 this.network = await UniqueHelper.detectNetwork(this.api);3101 }3102}31033104export class RelayHelper extends XcmChainHelper {3105 balance: SubstrateBalanceGroup<RelayHelper>;3106 xcm: XcmGroup<RelayHelper>;31073108 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3109 super(logger, options.helperBase ?? RelayHelper);31103111 this.balance = new SubstrateBalanceGroup(this);3112 this.xcm = new XcmGroup(this, 'xcmPallet');3113 }3114}31153116export class WestmintHelper extends XcmChainHelper {3117 balance: SubstrateBalanceGroup<WestmintHelper>;3118 xcm: XcmGroup<WestmintHelper>;3119 assets: AssetsGroup<WestmintHelper>;3120 xTokens: XTokensGroup<WestmintHelper>;31213122 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3123 super(logger, options.helperBase ?? WestmintHelper);31243125 this.balance = new SubstrateBalanceGroup(this);3126 this.xcm = new XcmGroup(this, 'polkadotXcm');3127 this.assets = new AssetsGroup(this);3128 this.xTokens = new XTokensGroup(this);3129 }3130}31313132export class MoonbeamHelper extends XcmChainHelper {3133 balance: EthereumBalanceGroup<MoonbeamHelper>;3134 assetManager: MoonbeamAssetManagerGroup;3135 assets: AssetsGroup<MoonbeamHelper>;3136 xTokens: XTokensGroup<MoonbeamHelper>;3137 democracy: MoonbeamDemocracyGroup;3138 collective: {3139 council: MoonbeamCollectiveGroup,3140 techCommittee: MoonbeamCollectiveGroup,3141 };31423143 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3144 super(logger, options.helperBase ?? MoonbeamHelper);31453146 this.balance = new EthereumBalanceGroup(this);3147 this.assetManager = new MoonbeamAssetManagerGroup(this);3148 this.assets = new AssetsGroup(this);3149 this.xTokens = new XTokensGroup(this);3150 this.democracy = new MoonbeamDemocracyGroup(this, options);3151 this.collective = {3152 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3153 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3154 };3155 }3156}31573158export class AcalaHelper extends XcmChainHelper {3159 balance: SubstrateBalanceGroup<AcalaHelper>;3160 assetRegistry: AcalaAssetRegistryGroup;3161 xTokens: XTokensGroup<AcalaHelper>;3162 tokens: TokensGroup<AcalaHelper>;31633164 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3165 super(logger, options.helperBase ?? AcalaHelper);31663167 this.balance = new SubstrateBalanceGroup(this);3168 this.assetRegistry = new AcalaAssetRegistryGroup(this);3169 this.xTokens = new XTokensGroup(this);3170 this.tokens = new TokensGroup(this);3171 }31723173 getSudo<T extends AcalaHelper>() {3174 // eslint-disable-next-line @typescript-eslint/naming-convention3175 const SudoHelperType = SudoHelper(this.helperBase);3176 return this.clone(SudoHelperType) as T;3177 }3178}31793180// eslint-disable-next-line @typescript-eslint/naming-convention3181function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3182 return class extends Base {3183 scheduleFn: 'schedule' | 'scheduleAfter';3184 blocksNum: number;3185 options: ISchedulerOptions;31863187 constructor(...args: any[]) {3188 const logger = args[0] as ILogger;3189 const options = args[1] as {3190 scheduleFn: 'schedule' | 'scheduleAfter',3191 blocksNum: number,3192 options: ISchedulerOptions3193 };31943195 super(logger);31963197 this.scheduleFn = options.scheduleFn;3198 this.blocksNum = options.blocksNum;3199 this.options = options.options;3200 }32013202 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3203 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);32043205 const mandatorySchedArgs = [3206 this.blocksNum,3207 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3208 this.options.priority ?? null,3209 scheduledTx,3210 ];32113212 let schedArgs;3213 let scheduleFn;32143215 if (this.options.scheduledId) {3216 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];32173218 if (this.scheduleFn == 'schedule') {3219 scheduleFn = 'scheduleNamed';3220 } else if (this.scheduleFn == 'scheduleAfter') {3221 scheduleFn = 'scheduleNamedAfter';3222 }3223 } else {3224 schedArgs = mandatorySchedArgs;3225 scheduleFn = this.scheduleFn;3226 }32273228 const extrinsic = 'api.tx.scheduler.' + scheduleFn;32293230 return super.executeExtrinsic(3231 sender,3232 extrinsic,3233 schedArgs,3234 expectSuccess,3235 );3236 }3237 };3238}32393240// eslint-disable-next-line @typescript-eslint/naming-convention3241function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3242 return class extends Base {3243 constructor(...args: any[]) {3244 super(...args);3245 }32463247 async executeExtrinsic(3248 sender: IKeyringPair,3249 extrinsic: string,3250 params: any[],3251 expectSuccess?: boolean,3252 options: Partial<SignerOptions>|null = null,3253 ): Promise<ITransactionResult> {3254 const call = this.constructApiCall(extrinsic, params);3255 const result = await super.executeExtrinsic(3256 sender,3257 'api.tx.sudo.sudo',3258 [call],3259 expectSuccess,3260 options,3261 );32623263 if (result.status === 'Fail') return result;32643265 const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3266 if (data.isErr) {3267 if (data.asErr.isModule) {3268 const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3269 const metaError = super.getApi()?.registry.findMetaError(error);3270 throw new Error(`${metaError.section}.${metaError.name}`);3271 } else {3272 throw new Error(data.asErr.toHuman());3273 }3274 }3275 return result;3276 }3277 };3278}32793280export class UniqueBaseCollection {3281 helper: UniqueHelper;3282 collectionId: number;32833284 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3285 this.collectionId = collectionId;3286 this.helper = uniqueHelper;3287 }32883289 async getData() {3290 return await this.helper.collection.getData(this.collectionId);3291 }32923293 async getLastTokenId() {3294 return await this.helper.collection.getLastTokenId(this.collectionId);3295 }32963297 async doesTokenExist(tokenId: number) {3298 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3299 }33003301 async getAdmins() {3302 return await this.helper.collection.getAdmins(this.collectionId);3303 }33043305 async getAllowList() {3306 return await this.helper.collection.getAllowList(this.collectionId);3307 }33083309 async getEffectiveLimits() {3310 return await this.helper.collection.getEffectiveLimits(this.collectionId);3311 }33123313 async getProperties(propertyKeys?: string[] | null) {3314 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3315 }33163317 async getPropertiesConsumedSpace() {3318 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3319 }33203321 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3322 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3323 }33243325 async getOptions() {3326 return await this.helper.collection.getCollectionOptions(this.collectionId);3327 }33283329 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3330 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3331 }33323333 async confirmSponsorship(signer: TSigner) {3334 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3335 }33363337 async removeSponsor(signer: TSigner) {3338 return await this.helper.collection.removeSponsor(signer, this.collectionId);3339 }33403341 async setLimits(signer: TSigner, limits: ICollectionLimits) {3342 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3343 }33443345 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3346 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3347 }33483349 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3350 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3351 }33523353 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3354 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3355 }33563357 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3358 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3359 }33603361 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3362 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3363 }33643365 async setProperties(signer: TSigner, properties: IProperty[]) {3366 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3367 }33683369 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3370 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3371 }33723373 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3374 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3375 }33763377 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3378 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3379 }33803381 async disableNesting(signer: TSigner) {3382 return await this.helper.collection.disableNesting(signer, this.collectionId);3383 }33843385 async burn(signer: TSigner) {3386 return await this.helper.collection.burn(signer, this.collectionId);3387 }33883389 scheduleAt<T extends UniqueHelper>(3390 executionBlockNumber: number,3391 options: ISchedulerOptions = {},3392 ) {3393 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3394 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3395 }33963397 scheduleAfter<T extends UniqueHelper>(3398 blocksBeforeExecution: number,3399 options: ISchedulerOptions = {},3400 ) {3401 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3402 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3403 }34043405 getSudo<T extends UniqueHelper>() {3406 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3407 }3408}340934103411export class UniqueNFTCollection extends UniqueBaseCollection {3412 getTokenObject(tokenId: number) {3413 return new UniqueNFToken(tokenId, this);3414 }34153416 async getTokensByAddress(addressObj: ICrossAccountId) {3417 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3418 }34193420 async getToken(tokenId: number, blockHashAt?: string) {3421 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3422 }34233424 async getTokenOwner(tokenId: number, blockHashAt?: string) {3425 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3426 }34273428 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3429 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3430 }34313432 async getTokenChildren(tokenId: number, blockHashAt?: string) {3433 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3434 }34353436 async getPropertyPermissions(propertyKeys: string[] | null = null) {3437 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3438 }34393440 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3441 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3442 }34433444 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3445 const api = this.helper.getApi();3446 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();34473448 return (props! as any).consumedSpace;3449 }34503451 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3452 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3453 }34543455 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3456 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3457 }34583459 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3460 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3461 }34623463 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3464 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3465 }34663467 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3468 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3469 }34703471 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3472 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3473 }34743475 async burnToken(signer: TSigner, tokenId: number) {3476 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3477 }34783479 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3480 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3481 }34823483 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3484 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3485 }34863487 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3488 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3489 }34903491 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3492 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3493 }34943495 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3496 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3497 }34983499 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3500 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3501 }35023503 scheduleAt<T extends UniqueHelper>(3504 executionBlockNumber: number,3505 options: ISchedulerOptions = {},3506 ) {3507 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3508 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3509 }35103511 scheduleAfter<T extends UniqueHelper>(3512 blocksBeforeExecution: number,3513 options: ISchedulerOptions = {},3514 ) {3515 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3516 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3517 }35183519 getSudo<T extends UniqueHelper>() {3520 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3521 }3522}352335243525export class UniqueRFTCollection extends UniqueBaseCollection {3526 getTokenObject(tokenId: number) {3527 return new UniqueRFToken(tokenId, this);3528 }35293530 async getToken(tokenId: number, blockHashAt?: string) {3531 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3532 }35333534 async getTokensByAddress(addressObj: ICrossAccountId) {3535 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3536 }35373538 async getTop10TokenOwners(tokenId: number) {3539 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3540 }35413542 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3543 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3544 }35453546 async getTokenTotalPieces(tokenId: number) {3547 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3548 }35493550 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3551 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3552 }35533554 async getPropertyPermissions(propertyKeys: string[] | null = null) {3555 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3556 }35573558 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3559 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3560 }35613562 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3563 const api = this.helper.getApi();3564 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();35653566 return (props! as any).consumedSpace;3567 }35683569 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3570 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3571 }35723573 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3574 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3575 }35763577 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3578 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3579 }35803581 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3582 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3583 }35843585 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3586 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3587 }35883589 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3590 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3591 }35923593 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3594 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3595 }35963597 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3598 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3599 }36003601 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3602 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3603 }36043605 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3606 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3607 }36083609 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3610 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3611 }36123613 scheduleAt<T extends UniqueHelper>(3614 executionBlockNumber: number,3615 options: ISchedulerOptions = {},3616 ) {3617 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3618 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3619 }36203621 scheduleAfter<T extends UniqueHelper>(3622 blocksBeforeExecution: number,3623 options: ISchedulerOptions = {},3624 ) {3625 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3626 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3627 }36283629 getSudo<T extends UniqueHelper>() {3630 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3631 }3632}363336343635export class UniqueFTCollection extends UniqueBaseCollection {3636 async getBalance(addressObj: ICrossAccountId) {3637 return await this.helper.ft.getBalance(this.collectionId, addressObj);3638 }36393640 async getTotalPieces() {3641 return await this.helper.ft.getTotalPieces(this.collectionId);3642 }36433644 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3645 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3646 }36473648 async getTop10Owners() {3649 return await this.helper.ft.getTop10Owners(this.collectionId);3650 }36513652 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3653 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3654 }36553656 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3657 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3658 }36593660 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3661 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3662 }36633664 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3665 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3666 }36673668 async burnTokens(signer: TSigner, amount=1n) {3669 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3670 }36713672 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3673 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3674 }36753676 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3677 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3678 }36793680 scheduleAt<T extends UniqueHelper>(3681 executionBlockNumber: number,3682 options: ISchedulerOptions = {},3683 ) {3684 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3685 return new UniqueFTCollection(this.collectionId, scheduledHelper);3686 }36873688 scheduleAfter<T extends UniqueHelper>(3689 blocksBeforeExecution: number,3690 options: ISchedulerOptions = {},3691 ) {3692 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3693 return new UniqueFTCollection(this.collectionId, scheduledHelper);3694 }36953696 getSudo<T extends UniqueHelper>() {3697 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3698 }3699}370037013702export class UniqueBaseToken {3703 collection: UniqueNFTCollection | UniqueRFTCollection;3704 collectionId: number;3705 tokenId: number;37063707 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3708 this.collection = collection;3709 this.collectionId = collection.collectionId;3710 this.tokenId = tokenId;3711 }37123713 async getNextSponsored(addressObj: ICrossAccountId) {3714 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3715 }37163717 async getProperties(propertyKeys?: string[] | null) {3718 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3719 }37203721 async getTokenPropertiesConsumedSpace() {3722 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3723 }37243725 async setProperties(signer: TSigner, properties: IProperty[]) {3726 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3727 }37283729 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3730 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3731 }37323733 async doesExist() {3734 return await this.collection.doesTokenExist(this.tokenId);3735 }37363737 nestingAccount() {3738 return this.collection.helper.util.getTokenAccount(this);3739 }37403741 scheduleAt<T extends UniqueHelper>(3742 executionBlockNumber: number,3743 options: ISchedulerOptions = {},3744 ) {3745 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3746 return new UniqueBaseToken(this.tokenId, scheduledCollection);3747 }37483749 scheduleAfter<T extends UniqueHelper>(3750 blocksBeforeExecution: number,3751 options: ISchedulerOptions = {},3752 ) {3753 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3754 return new UniqueBaseToken(this.tokenId, scheduledCollection);3755 }37563757 getSudo<T extends UniqueHelper>() {3758 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3759 }3760}376137623763export class UniqueNFToken extends UniqueBaseToken {3764 collection: UniqueNFTCollection;37653766 constructor(tokenId: number, collection: UniqueNFTCollection) {3767 super(tokenId, collection);3768 this.collection = collection;3769 }37703771 async getData(blockHashAt?: string) {3772 return await this.collection.getToken(this.tokenId, blockHashAt);3773 }37743775 async getOwner(blockHashAt?: string) {3776 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3777 }37783779 async getTopmostOwner(blockHashAt?: string) {3780 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3781 }37823783 async getChildren(blockHashAt?: string) {3784 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3785 }37863787 async nest(signer: TSigner, toTokenObj: IToken) {3788 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3789 }37903791 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3792 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3793 }37943795 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3796 return await this.collection.transferToken(signer, this.tokenId, addressObj);3797 }37983799 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3800 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3801 }38023803 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3804 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3805 }38063807 async isApproved(toAddressObj: ICrossAccountId) {3808 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3809 }38103811 async burn(signer: TSigner) {3812 return await this.collection.burnToken(signer, this.tokenId);3813 }38143815 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3816 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3817 }38183819 scheduleAt<T extends UniqueHelper>(3820 executionBlockNumber: number,3821 options: ISchedulerOptions = {},3822 ) {3823 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3824 return new UniqueNFToken(this.tokenId, scheduledCollection);3825 }38263827 scheduleAfter<T extends UniqueHelper>(3828 blocksBeforeExecution: number,3829 options: ISchedulerOptions = {},3830 ) {3831 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3832 return new UniqueNFToken(this.tokenId, scheduledCollection);3833 }38343835 getSudo<T extends UniqueHelper>() {3836 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3837 }3838}38393840export class UniqueRFToken extends UniqueBaseToken {3841 collection: UniqueRFTCollection;38423843 constructor(tokenId: number, collection: UniqueRFTCollection) {3844 super(tokenId, collection);3845 this.collection = collection;3846 }38473848 async getData(blockHashAt?: string) {3849 return await this.collection.getToken(this.tokenId, blockHashAt);3850 }38513852 async getTop10Owners() {3853 return await this.collection.getTop10TokenOwners(this.tokenId);3854 }38553856 async getBalance(addressObj: ICrossAccountId) {3857 return await this.collection.getTokenBalance(this.tokenId, addressObj);3858 }38593860 async getTotalPieces() {3861 return await this.collection.getTokenTotalPieces(this.tokenId);3862 }38633864 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3865 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3866 }38673868 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3869 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3870 }38713872 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3873 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3874 }38753876 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3877 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3878 }38793880 async repartition(signer: TSigner, amount: bigint) {3881 return await this.collection.repartitionToken(signer, this.tokenId, amount);3882 }38833884 async burn(signer: TSigner, amount=1n) {3885 return await this.collection.burnToken(signer, this.tokenId, amount);3886 }38873888 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3889 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3890 }38913892 scheduleAt<T extends UniqueHelper>(3893 executionBlockNumber: number,3894 options: ISchedulerOptions = {},3895 ) {3896 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3897 return new UniqueRFToken(this.tokenId, scheduledCollection);3898 }38993900 scheduleAfter<T extends UniqueHelper>(3901 blocksBeforeExecution: number,3902 options: ISchedulerOptions = {},3903 ) {3904 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3905 return new UniqueRFToken(this.tokenId, scheduledCollection);3906 }39073908 getSudo<T extends UniqueHelper>() {3909 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3910 }3911}