git.delta.rocks / unique-network / refs/commits / 6360d02576ab

difftreelog

Merge branch 'develop' into tests/feed-alices

Fahrrader2022-10-17parents: #520f20e #d8e7f8d.patch.diff
in: master

47 files changed

added.docker/additional/xcm-rococo/.envdiffbeforeafterboth
--- /dev/null
+++ b/.docker/additional/xcm-rococo/.env
@@ -0,0 +1,16 @@
+RUST_TOOLCHAIN=nightly-2022-07-24
+UNIQUE_BRANCH="develop"
+
+POLKADOT_BUILD_BRANCH=release-v0.9.29
+
+KARURA_BUILD_BRANCH=2.9.1
+ACALA_BUILD_BRANCH=2.9.2
+
+MOONRIVER_BUILD_BRANCH=runtime-1701
+MOONBEAM_BUILD_BRANCH=runtime-1701
+
+STATEMINE_BUILD_BRANCH=parachains-v9270
+STATEMINT_BUILD_BRANCH=release-parachains-v9230
+WESTMINT_BUILD_BRANCH=parachains-v9270
+
+POLKADOT_LAUNCH_BRANCH="unique-network"
added.docker/additional/xcm-rococo/Dockerfile-xcm-opal-rococodiffbeforeafterboth
--- /dev/null
+++ b/.docker/additional/xcm-rococo/Dockerfile-xcm-opal-rococo
@@ -0,0 +1,89 @@
+ARG CHAIN=opal
+ARG LAUNCH_CONFIG_FILE=launch-config-xcm-opal-rococo.json
+
+# ===== Rust builder =====
+FROM ubuntu:20.04 as rust-builder
+LABEL maintainer="Unique.Network"
+
+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 && \
+    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} && \
+    rustup target list --installed && \
+    rustup show
+RUN rustup target add wasm32-unknown-unknown --toolchain ${RUST_TOOLCHAIN}
+
+RUN mkdir /unique_parachain
+WORKDIR /unique_parachain
+
+# ===== BUILD ======
+FROM rust-builder as builder-unique
+
+ARG UNIQUE_BRANCH
+ARG CHAIN
+ARG LAUNCH_CONFIG_FILE
+ARG PROFILE=release
+
+WORKDIR /unique_parachain
+#COPY . .
+
+RUN git clone -b ${UNIQUE_BRANCH} https://github.com/UniqueNetwork/unique-chain.git . && \
+#    cd unique-chain && \
+  cargo build --features=${CHAIN}-runtime --$PROFILE
+
+# ===== RUN ======
+FROM ubuntu:20.04
+
+ARG POLKADOT_LAUNCH_BRANCH
+ARG LAUNCH_CONFIG_FILE
+ENV POLKADOT_LAUNCH_BRANCH $POLKADOT_LAUNCH_BRANCH
+ENV LAUNCH_CONFIG_FILE $LAUNCH_CONFIG_FILE
+
+RUN apt-get -y update && \
+      apt-get -y install curl git && \
+      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash && \
+      export NVM_DIR="$HOME/.nvm" && \
+      [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+      nvm install v16.16.0 && \
+      nvm use v16.16.0
+
+RUN git clone https://github.com/uniquenetwork/polkadot-launch -b ${POLKADOT_LAUNCH_BRANCH}
+
+RUN export NVM_DIR="$HOME/.nvm" && \
+    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+    cd /polkadot-launch && \
+    npm install --global yarn && \
+    yarn install
+
+COPY --from=builder-unique /unique_parachain/.docker/xcm-config/${LAUNCH_CONFIG_FILE} /polkadot-launch/
+
+COPY --from=builder-unique /unique_parachain/target/release/unique-collator /unique-chain/target/release/
+COPY --from=uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} /unique_parachain/polkadot/target/release/polkadot /polkadot/target/release/
+COPY --from=uniquenetwork/builder-cumulus:${STATEMINE_BUILD_BRANCH} /unique_parachain/cumulus/target/release/polkadot-parachain /cumulus/target/release/cumulus
+COPY --from=uniquenetwork/builder-chainql:latest /chainql/target/release/chainql /chainql/target/release/
+
+EXPOSE 9844
+EXPOSE 9944
+EXPOSE 9946
+EXPOSE 9947
+EXPOSE 9948
+
+CMD export NVM_DIR="$HOME/.nvm" PATH="$PATH:/chainql/target/release" && \
+    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+    cd /polkadot-launch && \
+    yarn start ${LAUNCH_CONFIG_FILE}
+
+                                                                                        
added.docker/additional/xcm-rococo/Dockerfile-xcm-quartz-rococodiffbeforeafterboth
--- /dev/null
+++ b/.docker/additional/xcm-rococo/Dockerfile-xcm-quartz-rococo
@@ -0,0 +1,93 @@
+ARG CHAIN=quartz
+ARG LAUNCH_CONFIG_FILE=launch-config-xcm-quartz-rococo.json
+
+# ===== Rust builder =====
+FROM ubuntu:20.04 as rust-builder
+LABEL maintainer="Unique.Network"
+
+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 && \
+    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} && \
+    rustup target list --installed && \
+    rustup show
+RUN rustup target add wasm32-unknown-unknown --toolchain ${RUST_TOOLCHAIN}
+
+RUN mkdir /unique_parachain
+WORKDIR /unique_parachain
+
+# ===== BUILD ======
+FROM rust-builder as builder-unique
+
+ARG UNIQUE_BRANCH
+ARG CHAIN
+ARG LAUNCH_CONFIG_FILE
+ARG PROFILE=release
+
+WORKDIR /unique_parachain
+#COPY . .
+
+RUN git clone -b ${UNIQUE_BRANCH} https://github.com/UniqueNetwork/unique-chain.git . && \
+#    cd unique-chain && \
+  cargo build --features=${CHAIN}-runtime --$PROFILE
+
+# ===== RUN ======
+FROM ubuntu:20.04
+
+ARG POLKADOT_LAUNCH_BRANCH
+ARG LAUNCH_CONFIG_FILE
+ENV POLKADOT_LAUNCH_BRANCH $POLKADOT_LAUNCH_BRANCH
+ENV LAUNCH_CONFIG_FILE $LAUNCH_CONFIG_FILE
+
+RUN apt-get -y update && \
+      apt-get -y install curl git && \
+      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash && \
+      export NVM_DIR="$HOME/.nvm" && \
+      [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+      nvm install v16.16.0 && \
+      nvm use v16.16.0
+
+RUN git clone https://github.com/uniquenetwork/polkadot-launch -b ${POLKADOT_LAUNCH_BRANCH}
+
+RUN export NVM_DIR="$HOME/.nvm" && \
+    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+    cd /polkadot-launch && \
+    npm install --global yarn && \
+    yarn install
+
+COPY --from=builder-unique /unique_parachain/.docker/xcm-config/${LAUNCH_CONFIG_FILE} /polkadot-launch/
+COPY --from=builder-unique /unique_parachain/.docker/xcm-config/5validators.jsonnet /polkadot-launch/5validators.jsonnet
+COPY --from=builder-unique /unique_parachain/.docker/xcm-config/minBondFix.jsonnet /polkadot-launch/minBondFix.jsonnet
+
+COPY --from=builder-unique /unique_parachain/target/release/unique-collator /unique-chain/target/release/
+COPY --from=uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} /unique_parachain/polkadot/target/release/polkadot /polkadot/target/release/
+COPY --from=uniquenetwork/builder-moonbeam:${MOONRIVER_BUILD_BRANCH} /unique_parachain/moonbeam/target/release/moonbeam /moonbeam/target/release/
+COPY --from=uniquenetwork/builder-cumulus:${STATEMINE_BUILD_BRANCH} /unique_parachain/cumulus/target/release/polkadot-parachain /cumulus/target/release/cumulus
+COPY --from=uniquenetwork/builder-acala:${KARURA_BUILD_BRANCH} /unique_parachain/Acala/target/production/acala /acala/target/release/
+COPY --from=uniquenetwork/builder-chainql:latest /chainql/target/release/chainql /chainql/target/release/
+
+EXPOSE 9844
+EXPOSE 9944
+EXPOSE 9946
+EXPOSE 9947
+EXPOSE 9948
+
+CMD export NVM_DIR="$HOME/.nvm" PATH="$PATH:/chainql/target/release" && \
+    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+    cd /polkadot-launch && \
+    yarn start ${LAUNCH_CONFIG_FILE}
+
+                                                                                        
added.docker/additional/xcm-rococo/Dockerfile-xcm-unique-rococodiffbeforeafterboth
--- /dev/null
+++ b/.docker/additional/xcm-rococo/Dockerfile-xcm-unique-rococo
@@ -0,0 +1,93 @@
+ARG CHAIN=unique
+ARG LAUNCH_CONFIG_FILE=launch-config-xcm-unique-rococo.json
+
+# ===== Rust builder =====
+FROM ubuntu:20.04 as rust-builder
+LABEL maintainer="Unique.Network"
+
+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 && \
+    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} && \
+    rustup target list --installed && \
+    rustup show
+RUN rustup target add wasm32-unknown-unknown --toolchain ${RUST_TOOLCHAIN}
+
+RUN mkdir /unique_parachain
+WORKDIR /unique_parachain
+
+# ===== BUILD ======
+FROM rust-builder as builder-unique
+
+ARG UNIQUE_BRANCH
+ARG CHAIN
+ARG LAUNCH_CONFIG_FILE
+ARG PROFILE=release
+
+WORKDIR /unique_parachain
+#COPY . .
+
+RUN git clone -b ${UNIQUE_BRANCH} https://github.com/UniqueNetwork/unique-chain.git . && \
+#    cd unique-chain && \
+  cargo build --features=${CHAIN}-runtime --$PROFILE
+
+# ===== RUN ======
+FROM ubuntu:20.04
+
+ARG POLKADOT_LAUNCH_BRANCH
+ARG LAUNCH_CONFIG_FILE
+ENV POLKADOT_LAUNCH_BRANCH $POLKADOT_LAUNCH_BRANCH
+ENV LAUNCH_CONFIG_FILE $LAUNCH_CONFIG_FILE
+
+RUN apt-get -y update && \
+      apt-get -y install curl git && \
+      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash && \
+      export NVM_DIR="$HOME/.nvm" && \
+      [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+      nvm install v16.16.0 && \
+      nvm use v16.16.0
+
+RUN git clone https://github.com/uniquenetwork/polkadot-launch -b ${POLKADOT_LAUNCH_BRANCH}
+
+RUN export NVM_DIR="$HOME/.nvm" && \
+    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+    cd /polkadot-launch && \
+    npm install --global yarn && \
+    yarn install
+
+COPY --from=builder-unique /unique_parachain/.docker/xcm-config/${LAUNCH_CONFIG_FILE} /polkadot-launch/
+COPY --from=builder-unique /unique_parachain/.docker/xcm-config/5validators.jsonnet /polkadot-launch/5validators.jsonnet
+COPY --from=builder-unique /unique_parachain/.docker/xcm-config/minBondFix.jsonnet /polkadot-launch/minBondFix.jsonnet
+
+COPY --from=builder-unique /unique_parachain/target/release/unique-collator /unique-chain/target/release/
+COPY --from=uniquenetwork/builder-polkadot:${POLKADOT_BUILD_BRANCH} /unique_parachain/polkadot/target/release/polkadot /polkadot/target/release/
+COPY --from=uniquenetwork/builder-moonbeam:${MOONBEAM_BUILD_BRANCH} /unique_parachain/moonbeam/target/release/moonbeam /moonbeam/target/release/
+COPY --from=uniquenetwork/builder-cumulus:${STATEMINT_BUILD_BRANCH} /unique_parachain/cumulus/target/release/polkadot-parachain /cumulus/target/release/cumulus
+COPY --from=uniquenetwork/builder-acala:${ACALA_BUILD_BRANCH} /unique_parachain/Acala/target/production/acala /acala/target/release/
+COPY --from=uniquenetwork/builder-chainql:latest /chainql/target/release/chainql /chainql/target/release/
+
+EXPOSE 9844
+EXPOSE 9944
+EXPOSE 9946
+EXPOSE 9947
+EXPOSE 9948
+
+CMD export NVM_DIR="$HOME/.nvm" PATH="$PATH:/chainql/target/release" && \
+    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+    cd /polkadot-launch && \
+    yarn start ${LAUNCH_CONFIG_FILE}
+
+                                                                                        
added.docker/additional/xcm-rococo/docker-compose-xcm-opal-rococo.ymldiffbeforeafterboth
--- /dev/null
+++ b/.docker/additional/xcm-rococo/docker-compose-xcm-opal-rococo.yml
@@ -0,0 +1,26 @@
+version: "3.5"
+
+services:
+  xcm_opal_rococo:
+    build:
+      context: .
+      dockerfile: .Dockerfile-xcm-opal-rococo
+    container_name: xcm-opal-rococo
+    image: xcm-opal-rococo:latest
+    env_file: .env
+    expose:
+      - 9844
+      - 9944
+      - 9946
+      - 9947
+      - 9948
+    ports:
+      - 127.0.0.1:9844:9844
+      - 127.0.0.1:9944:9944
+      - 127.0.0.1:9946:9946
+      - 127.0.0.1:9947:9947
+      - 127.0.0.1:9948:9948
+    logging:
+      options:
+        max-size: "1m"
+        max-file: "3"
added.docker/additional/xcm-rococo/docker-compose-xcm-quartz-rococo.ymldiffbeforeafterboth
--- /dev/null
+++ b/.docker/additional/xcm-rococo/docker-compose-xcm-quartz-rococo.yml
@@ -0,0 +1,26 @@
+version: "3.5"
+
+services:
+  xcm_quartz_rococo:
+    build:
+      context: .
+      dockerfile: .Dockerfile-xcm-quartz-rococo
+    container_name: xcm-quartz-rococo
+    image: xcm-quartz-rococo:latest
+    env_file: .env
+    expose:
+      - 9844
+      - 9944
+      - 9946
+      - 9947
+      - 9948
+    ports:
+      - 127.0.0.1:9844:9844
+      - 127.0.0.1:9944:9944
+      - 127.0.0.1:9946:9946
+      - 127.0.0.1:9947:9947
+      - 127.0.0.1:9948:9948
+    logging:
+      options:
+        max-size: "1m"
+        max-file: "3"
added.docker/additional/xcm-rococo/docker-compose-xcm-unique-rococo.ymldiffbeforeafterboth
--- /dev/null
+++ b/.docker/additional/xcm-rococo/docker-compose-xcm-unique-rococo.yml
@@ -0,0 +1,26 @@
+version: "3.5"
+
+services:
+  xcm_unique_rococo:
+    build:
+      context: .
+      dockerfile: .Dockerfile-xcm-unique-rococo
+    container_name: xcm-unique-rococo
+    image: xcm-unique-rococo:latest
+    env_file: .env
+    expose:
+      - 9844
+      - 9944
+      - 9946
+      - 9947
+      - 9948
+    ports:
+      - 127.0.0.1:9844:9844
+      - 127.0.0.1:9944:9944
+      - 127.0.0.1:9946:9946
+      - 127.0.0.1:9947:9947
+      - 127.0.0.1:9948:9948
+    logging:
+      options:
+        max-size: "1m"
+        max-file: "3"
added.docker/xcm-config/launch-config-xcm-opal-rococo.jsondiffbeforeafterboth
--- /dev/null
+++ b/.docker/xcm-config/launch-config-xcm-opal-rococo.json
@@ -0,0 +1,134 @@
+{
+    "relaychain": {
+        "bin": "/polkadot/target/release/polkadot",
+        "chain": "rococo-local",
+        "chainInitializer": [
+                "chainql",
+                "--tla-code=spec=import '${spec}'",
+                "5validators.jsonnet"
+            ],	
+        "nodes": [
+            {
+                "name": "alice",
+                "wsPort": 9844,
+                "rpcPort": 9843,
+                "port": 30444,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "bob",
+                "wsPort": 9855,
+                "rpcPort": 9854,
+                "port": 30555,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "charlie",
+                "wsPort": 9866,
+                "rpcPort": 9865,
+                "port": 30666,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "dave",
+                "wsPort": 9877,
+                "rpcPort": 9876,
+                "port": 30777,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "eve",
+                "wsPort": 9888,
+                "rpcPort": 9887,
+                "port": 30888,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            }
+
+        ],
+        "genesis": {
+            "runtime": {
+                "runtime_genesis_config": {
+                    "parachainsConfiguration": {
+                        "config": {
+                            "validation_upgrade_frequency": 1,
+                            "validation_upgrade_delay": 1
+                        }
+                    }
+                }
+            }
+        }
+    },
+    "parachains": [
+        {
+            "bin": "/unique-chain/target/release/unique-collator",
+            "id": "2095",
+            "balance": "1000000000000000000000000",
+            "nodes": [
+                {
+                    "port": 31200,
+                    "wsPort": 9944,
+                    "rpcPort": 9933,
+                    "name": "alice",
+                    "flags": [
+                       "--unsafe-rpc-external",
+                       "--unsafe-ws-external"
+		    ]
+                }
+            ]
+        },
+        {
+            "bin": "/cumulus/target/release/cumulus",
+            "id": "1000",
+            "chain": "westmint-local",
+            "balance": "1000000000000000000000000",
+            "nodes": [
+                {
+                    "wsPort": 9948,
+                    "port": 31204,
+                    "name": "alice",
+                    "flags": [
+                       "--unsafe-rpc-external",
+                       "--unsafe-ws-external"
+                    ]
+                }
+            ]
+        }
+    ],
+    "simpleParachains": [],
+    "hrmpChannels": [
+        {
+            "sender": 2095,
+            "recipient": 1000,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        },
+        {
+            "sender": 1000,
+            "recipient": 2095,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        }
+    ],
+    "finalization": false
+}
+
added.docker/xcm-config/launch-config-xcm-quartz-rococo.jsondiffbeforeafterboth
--- /dev/null
+++ b/.docker/xcm-config/launch-config-xcm-quartz-rococo.json
@@ -0,0 +1,199 @@
+{
+    "relaychain": {
+        "bin": "/polkadot/target/release/polkadot",
+        "chain": "rococo-local",
+        "chainInitializer": [
+                "chainql",
+                "--tla-code=spec=import '${spec}'",
+                "5validators.jsonnet"
+            ],	
+        "nodes": [
+            {
+                "name": "alice",
+                "wsPort": 9844,
+                "rpcPort": 9843,
+                "port": 30444,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "bob",
+                "wsPort": 9855,
+                "rpcPort": 9854,
+                "port": 30555,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "charlie",
+                "wsPort": 9866,
+                "rpcPort": 9865,
+                "port": 30666,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "dave",
+                "wsPort": 9877,
+                "rpcPort": 9876,
+                "port": 30777,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            },
+            {
+                "name": "eve",
+                "wsPort": 9888,
+                "rpcPort": 9887,
+                "port": 30888,
+                "flags": [
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external",
+                    "-lparachain::candidate_validation=debug"
+                ]
+            }
+
+        ],
+        "genesis": {
+            "runtime": {
+                "runtime_genesis_config": {
+                    "parachainsConfiguration": {
+                        "config": {
+                            "validation_upgrade_frequency": 1,
+                            "validation_upgrade_delay": 1
+                        }
+                    }
+                }
+            }
+        }
+    },
+    "parachains": [
+        {
+            "bin": "/unique-chain/target/release/unique-collator",
+            "id": "2095",
+            "balance": "1000000000000000000000000",
+            "nodes": [
+                {
+                    "port": 31200,
+                    "wsPort": 9944,
+                    "rpcPort": 9933,
+                    "name": "alice",
+                    "flags": [
+                       "--unsafe-rpc-external",
+                       "--unsafe-ws-external"
+		    ]
+                }
+            ]
+        },
+        {
+            "bin": "/acala/target/release/acala",
+            "id": "2000",
+            "chain":  "karura-dev",
+            "balance": "1000000000000000000000",
+            "nodes": [
+                {
+                    "wsPort": 9946,
+                    "port": 31202,
+                    "name": "alice",
+                    "flags": [
+                       "--unsafe-rpc-external",
+                       "--unsafe-ws-external"
+                     ]
+                }
+              ]
+        },
+        {
+            "bin": "/moonbeam/target/release/moonbeam",
+            "id": 2023,
+            "balance": "1000000000000000000000",
+            "chain": "moonriver-local",
+            "chainInitializer": [
+                "chainql",
+                "--tla-code=spec=import '${spec}'",
+                "minBondFix.jsonnet"
+            ],		    
+            "nodes": [
+                {
+                    "wsPort": 9947,
+                    "port": 31203,
+                    "name": "alice",
+                    "flags": [
+                       "--unsafe-rpc-external",
+                       "--unsafe-ws-external",
+                        "--",
+                        "--execution=wasm"
+                    ]
+                }
+            ]
+        },
+        {
+            "bin": "/cumulus/target/release/cumulus",
+            "id": "1000",
+            "chain": "statemine-local",
+            "balance": "1000000000000000000000000",
+            "nodes": [
+                {
+                    "wsPort": 9948,
+                    "port": 31204,
+                    "name": "alice",
+                    "flags": [
+                       "--unsafe-rpc-external",
+                       "--unsafe-ws-external"
+                    ]
+                }
+            ]
+        }
+    ],
+    "simpleParachains": [],
+    "hrmpChannels": [
+        {
+            "sender": 2095,
+            "recipient": 2000,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        },
+        {
+            "sender": 2000,
+            "recipient": 2095,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        },
+        {
+            "sender": 2095,
+            "recipient": 2023,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        },
+        {
+            "sender": 2023,
+            "recipient": 2095,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        },
+        {
+            "sender": 2095,
+            "recipient": 1000,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        },
+        {
+            "sender": 1000,
+            "recipient": 2095,
+            "maxCapacity": 8,
+            "maxMessageSize": 512
+        }
+    ],
+    "finalization": false
+}
+
modified.docker/xcm-config/launch-config-xcm-unique-rococo.jsondiffbeforeafterboth
--- a/.docker/xcm-config/launch-config-xcm-unique-rococo.json
+++ b/.docker/xcm-config/launch-config-xcm-unique-rococo.json
@@ -90,8 +90,8 @@
                     "rpcPort": 9933,
                     "name": "alice",
                     "flags": [
-			"-lruntime=trace",
-			"-lxcm=trace",
+			            "-lruntime=trace",
+			            "-lxcm=trace",
                         "--unsafe-rpc-external",
                         "--unsafe-ws-external"
 		    ]
@@ -114,8 +114,8 @@
                     "port": 31202,
                     "name": "alice",
                     "flags": [
-			"-lruntime=trace",
-			"-lxcm=trace",
+			            "-lruntime=trace",
+			            "-lxcm=trace",
                         "--unsafe-rpc-external",
                         "--unsafe-ws-external"
 		    ]
@@ -133,11 +133,11 @@
                     "port": 31203,
                     "name": "alice",
                     "flags": [
-			"-lruntime=trace",
-			"-lxcm=trace",
+			            "-lruntime=trace",
+			            "-lxcm=trace",
                         "--unsafe-rpc-external",
                         "--unsafe-ws-external",
-  			"--",
+  			            "--",
                         "--execution=wasm"
                     ]
                 }
@@ -154,8 +154,8 @@
                     "port": 31204,
                     "name": "alice",
                     "flags": [
-			"-lruntime=trace",
-			"-lxcm=trace",
+			            "-lruntime=trace",
+			            "-lxcm=trace",
                         "--unsafe-rpc-external",
                         "--unsafe-ws-external"
 		    ]
modified.envdiffbeforeafterboth
--- a/.env
+++ b/.env
@@ -1,5 +1,5 @@
 RUST_TOOLCHAIN=nightly-2022-07-24
-POLKADOT_BUILD_BRANCH=release-v0.9.27
+POLKADOT_BUILD_BRANCH=release-v0.9.29
 
 POLKADOT_MAINNET_BRANCH=release-v0.9.26
 UNIQUE_MAINNET_TAG=v924010
@@ -13,7 +13,7 @@
 QUARTZ_REPLICA_FROM=wss://eu-ws-quartz.unique.network:443
 UNIQUE_REPLICA_FROM=wss://eu-ws.unique.network:443
 
-POLKADOT_LAUNCH_BRANCH=feature/rewrite-chain-id-in-spec
+POLKADOT_LAUNCH_BRANCH=unique-network
 
 KARURA_BUILD_BRANCH=2.9.1
 ACALA_BUILD_BRANCH=2.9.2
modified.github/workflows/testnet-build.ymldiffbeforeafterboth
--- a/.github/workflows/testnet-build.yml
+++ b/.github/workflows/testnet-build.yml
@@ -125,13 +125,10 @@
         run: docker pull uniquenetwork/builder-polkadot:${{ env.POLKADOT_BUILD_BRANCH }}           
 
       - name: Build the stack
-        run: cd .docker/ && docker build --file ./Dockerfile-testnet.${{ matrix.network }}.yml --tag uniquenetwork/${{ matrix.network }}-testnet-local:nightly-${{ steps.branchname.outputs.value }}-${{ github.sha }} --tag uniquenetwork/${{ matrix.network }}-testnet-local:latest . 
+        run: cd .docker/ && docker build --file ./Dockerfile-testnet.${{ matrix.network }}.yml --tag uniquenetwork/${{ matrix.network }}-testnet-local-nightly:nightly-${{ steps.branchname.outputs.value }}-${{ github.sha }} . 
 
       - name: Push docker version image
-        run: docker push uniquenetwork/${{ matrix.network }}-testnet-local:nightly-${{ steps.branchname.outputs.value }}-${{ github.sha }}
-
-      - name: Push docker latest image
-        run: docker push uniquenetwork/${{ matrix.network }}-testnet-local:latest
+        run: docker push uniquenetwork/${{ matrix.network }}-testnet-local-nightly:nightly-${{ steps.branchname.outputs.value }}-${{ github.sha }}
 
       - name: Clean Workspace
         if: always()
modifiedtests/src/config.tsdiffbeforeafterboth
--- a/tests/src/config.ts
+++ b/tests/src/config.ts
@@ -19,6 +19,12 @@
 const config = {
   substrateUrl: process.env.substrateUrl || 'ws://127.0.0.1:9944',
   frontierUrl: process.env.frontierUrl || 'http://127.0.0.1:9933',
+  relayUrl: process.env.relayUrl || 'ws://127.0.0.1:9844',
+  acalaUrl: process.env.acalaUrl || 'ws://127.0.0.1:9946',
+  karuraUrl: process.env.acalaUrl || 'ws://127.0.0.1:9946',
+  moonbeamUrl: process.env.moonbeamUrl || 'ws://127.0.0.1:9947',
+  moonriverUrl: process.env.moonbeamUrl || 'ws://127.0.0.1:9947',
+  westmintUrl: process.env.westmintUrl || 'ws://127.0.0.1:9948',
 };
 
-export default config;
\ No newline at end of file
+export default config;
deletedtests/src/deprecated-helpers/contracthelpers.tsdiffbeforeafterboth
--- a/tests/src/deprecated-helpers/contracthelpers.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
-import fs from 'fs';
-import {Abi, CodePromise, ContractPromise as Contract} from '@polkadot/api-contract';
-import {IKeyringPair} from '@polkadot/types/types';
-import {ApiPromise} from '@polkadot/api';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-import {findUnusedAddress, getGenericResult} from './helpers';
-
-const value = 0;
-const gasLimit = '200000000000';
-const endowment = '100000000000000000';
-
-/* eslint no-async-promise-executor: "off" */
-function deployContract(alice: IKeyringPair, code: CodePromise, constructor = 'default', ...args: any[]): Promise<Contract> {
-  return new Promise<Contract>(async (resolve) => {
-    const unsub = await (code as any)
-      .tx[constructor]({value: endowment, gasLimit}, ...args)
-      .signAndSend(alice, (result: any) => {
-        if (result.status.isInBlock || result.status.isFinalized) {
-          // here we have an additional field in the result, containing the blueprint
-          resolve((result as any).contract);
-          unsub();
-        }
-      });
-  });
-}
-
-async function prepareDeployer(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) {
-  // Find unused address
-  const deployer = await findUnusedAddress(api, privateKeyWrapper);
-
-  // Transfer balance to it
-  const alice = privateKeyWrapper('//Alice');
-  const amount = BigInt(endowment) + 10n**15n;
-  const tx = api.tx.balances.transfer(deployer.address, amount);
-  await submitTransactionAsync(alice, tx);
-
-  return deployer;
-}
-
-export async function deployFlipper(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
-  const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));
-  const abi = new Abi(metadata);
-
-  const deployer = await prepareDeployer(api, privateKeyWrapper);
-
-  const wasm = fs.readFileSync('./src/flipper/flipper.wasm');
-
-  const code = new CodePromise(api, abi, wasm);
-
-  const contract = (await deployContract(deployer, code, 'new', true)) as Contract;
-
-  const initialGetResponse = await getFlipValue(contract, deployer);
-  expect(initialGetResponse).to.be.true;
-
-  return [contract, deployer];
-}
-
-export async function getFlipValue(contract: Contract, deployer: IKeyringPair) {
-  const result = await contract.query.get(deployer.address, {value, gasLimit});
-
-  if(!result.result.isOk) {
-    throw 'Failed to get flipper value';
-  }
-  return (result.result.asOk.data[0] == 0x00) ? false : true;
-}
-
-export async function toggleFlipValueExpectSuccess(sender: IKeyringPair, contract: Contract) {
-  const tx = contract.tx.flip({value, gasLimit});
-  const events = await submitTransactionAsync(sender, tx);
-  const result = getGenericResult(events);
-
-  expect(result.success).to.be.true;
-}
-
-export async function toggleFlipValueExpectFailure(sender: IKeyringPair, contract: Contract) {
-  const tx = contract.tx.flip({value, gasLimit});
-  await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-}
-
-export async function deployTransferContract(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
-  const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));
-  const abi = new Abi(metadata);
-
-  const deployer = await prepareDeployer(api, privateKeyWrapper);
-
-  const wasm = fs.readFileSync('./src/transfer_contract/nft_transfer.wasm');
-
-  const code = new CodePromise(api, abi, wasm);
-
-  const contract = await deployContract(deployer, code);
-
-  return [contract, deployer];
-}
deletedtests/src/deprecated-helpers/eth/helpers.d.tsdiffbeforeafterboth
--- a/tests/src/deprecated-helpers/eth/helpers.d.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-declare module 'solc';
\ No newline at end of file
deletedtests/src/deprecated-helpers/eth/helpers.tsdiffbeforeafterboth
--- a/tests/src/deprecated-helpers/eth/helpers.ts
+++ /dev/null
@@ -1,451 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// eslint-disable-next-line @typescript-eslint/triple-slash-reference
-/// <reference path="helpers.d.ts" />
-
-import {ApiPromise} from '@polkadot/api';
-import {IKeyringPair} from '@polkadot/types/types';
-import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';
-import {expect} from 'chai';
-import * as solc from 'solc';
-import Web3 from 'web3';
-import config from '../../config';
-import getBalance from '../../substrate/get-balance';
-import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';
-import waitNewBlocks from '../../substrate/wait-new-blocks';
-import {CollectionMode, CrossAccountId, getDetailedCollectionInfo, getGenericResult, UNIQUE} from '../helpers';
-import collectionHelpersAbi from '../../eth/collectionHelpersAbi.json';
-import fungibleAbi from '../../eth/fungibleAbi.json';
-import nonFungibleAbi from '../../eth/nonFungibleAbi.json';
-import refungibleAbi from '../../eth/reFungibleAbi.json';
-import refungibleTokenAbi from '../../eth/reFungibleTokenAbi.json';
-import contractHelpersAbi from '../../eth/util/contractHelpersAbi.json';
-
-export const GAS_ARGS = {gas: 2500000};
-
-export enum SponsoringMode {
-  Disabled = 0,
-  Allowlisted = 1,
-  Generous = 2,
-}
-
-let web3Connected = false;
-export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {
-  if (web3Connected) throw new Error('do not nest usingWeb3 calls');
-  web3Connected = true;
-
-  const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);
-  const web3 = new Web3(provider);
-
-  try {
-    return await cb(web3);
-  } finally {
-    // provider.disconnect(3000, 'normal disconnect');
-    provider.connection.close();
-    web3Connected = false;
-  }
-}
-
-function encodeIntBE(v: number): number[] {
-  if (v >= 0xffffffff || v < 0) throw new Error('id overflow');
-  return [
-    v >> 24,
-    (v >> 16) & 0xff,
-    (v >> 8) & 0xff,
-    v & 0xff,
-  ];
-}
-
-export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {
-  const collectionIdAddress = normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
-  const collectionId = collectionIdFromAddress(collectionIdAddress);  
-  const collection = (await getDetailedCollectionInfo(api, collectionId))!;
-  return {collectionIdAddress, collectionId, collection};
-}
-
-export function collectionIdToAddress(collection: number): string {
-  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
-    ...encodeIntBE(collection),
-  ]);
-  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
-}
-export function collectionIdFromAddress(address: string): number {
-  if (!address.startsWith('0x'))
-    throw 'address not starts with "0x"';
-  if (address.length > 42)
-    throw 'address length is more than 20 bytes';
-  return Number('0x' + address.substring(address.length - 8));
-}
-  
-export function normalizeAddress(address: string): string {
-  return '0x' + address.substring(address.length - 40);
-}
-
-export function tokenIdToAddress(collection: number, token: number): string {
-  const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
-    ...encodeIntBE(collection),
-    ...encodeIntBE(token),
-  ]);
-  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
-}
-
-export function tokenIdFromAddress(address: string) {
-  if (!address.startsWith('0x'))
-    throw 'address not starts with "0x"';
-  if (address.length > 42)
-    throw 'address length is more than 20 bytes';
-  return {
-    collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),
-    tokenId: Number('0x' + address.substring(address.length - 8)),
-  };
-}
-
-export function tokenIdToCross(collection: number, token: number): CrossAccountId {
-  return {
-    Ethereum: tokenIdToAddress(collection, token),
-  };
-}
-
-export function createEthAccount(web3: Web3) {
-  const account = web3.eth.accounts.create();
-  web3.eth.accounts.wallet.add(account.privateKey);
-  return account.address;
-}
-
-export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair) {
-  const alice = privateKeyWrapper('//Alice');
-  const account = createEthAccount(web3);
-  await transferBalanceToEth(api, alice, account);
-
-  return account;
-}
-
-export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
-  const tx = api.tx.balances.transfer(evmToAddress(target), amount);
-  const events = await submitTransactionAsync(source, tx);
-  const result = getGenericResult(events);
-  expect(result.success).to.be.true;
-}
-
-export async function createRFTCollection(api: ApiPromise, web3: Web3, owner: string) {
-  const collectionHelper = evmCollectionHelpers(web3, owner);
-  const result = await collectionHelper.methods
-    .createRFTCollection('A', 'B', 'C')
-    .send({value: Number(2n * UNIQUE)});
-  return await getCollectionAddressFromResult(api, result);
-}
-
-
-export async function createNonfungibleCollection(api: ApiPromise, web3: Web3, owner: string) {
-  const collectionHelper = evmCollectionHelpers(web3, owner);
-  const result = await collectionHelper.methods
-    .createNonfungibleCollection('A', 'B', 'C')
-    .send({value: Number(2n * UNIQUE)});
-  return await getCollectionAddressFromResult(api, result);
-}
-
-export function uniqueNFT(web3: Web3, address: string, owner: string) {
-  return new web3.eth.Contract(nonFungibleAbi as any, address, {
-    from: owner,
-    ...GAS_ARGS,
-  });
-}
-
-export function uniqueRefungible(web3: Web3, collectionAddress: string, owner: string) {
-  return new web3.eth.Contract(refungibleAbi as any, collectionAddress, {
-    from: owner,
-    ...GAS_ARGS,
-  });
-}
-
-export function uniqueRefungibleToken(web3: Web3, tokenAddress: string, owner: string | undefined = undefined) {
-  return new web3.eth.Contract(refungibleTokenAbi as any, tokenAddress, {
-    from: owner,
-    ...GAS_ARGS,
-  });
-}
-
-export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
-  let i: any = it;
-  if (opts.only) i = i.only;
-  else if (opts.skip) i = i.skip;
-  i(name, async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      await usingWeb3(async web3 => {
-        await cb({api, web3, privateKeyWrapper});
-      });
-    });
-  });
-}
-itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {only: true});
-itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {skip: true});
-
-export async function generateSubstrateEthPair(web3: Web3) {
-  const account = web3.eth.accounts.create();
-  evmToAddress(account.address);
-}
-
-type NormalizedEvent = {
-    address: string,
-    event: string,
-    args: { [key: string]: string }
-};
-
-export function normalizeEvents(events: any): NormalizedEvent[] {
-  const output = [];
-  for (const key of Object.keys(events)) {
-    if (key.match(/^[0-9]+$/)) {
-      output.push(events[key]);
-    } else if (Array.isArray(events[key])) {
-      output.push(...events[key]);
-    } else {
-      output.push(events[key]);
-    }
-  }
-  output.sort((a, b) => a.logIndex - b.logIndex);
-  return output.map(({address, event, returnValues}) => {
-    const args: { [key: string]: string } = {};
-    for (const key of Object.keys(returnValues)) {
-      if (!key.match(/^[0-9]+$/)) {
-        args[key] = returnValues[key];
-      }
-    }
-    return {
-      address,
-      event,
-      args,
-    };
-  });
-}
-
-export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {
-  const out: any = [];
-  contract.events.allEvents((_: any, event: any) => {
-    out.push(event);
-  });
-  await action();
-  return normalizeEvents(out);
-}
-
-export function subToEthLowercase(eth: string): string {
-  const bytes = addressToEvm(eth);
-  return '0x' + Buffer.from(bytes).toString('hex');
-}
-
-export function subToEth(eth: string): string {
-  return Web3.utils.toChecksumAddress(subToEthLowercase(eth));
-}
-
-export interface CompiledContract {
-  abi: any,
-  object: string,
-}
-
-export function compileContract(name: string, src: string) : CompiledContract {
-  const out = JSON.parse(solc.compile(JSON.stringify({
-    language: 'Solidity',
-    sources: {
-      [`${name}.sol`]: {
-        content: `
-          // SPDX-License-Identifier: UNLICENSED
-          pragma solidity ^0.8.6;
-
-          ${src}
-        `,
-      },
-    },
-    settings: {
-      outputSelection: {
-        '*': {
-          '*': ['*'],
-        },
-      },
-    },
-  }))).contracts[`${name}.sol`][name];
-
-  return {
-    abi: out.abi,
-    object: '0x' + out.evm.bytecode.object,
-  };
-}
-
-export async function deployFlipper(web3: Web3, deployer: string) {
-  const compiled = compileContract('Flipper', `
-    contract Flipper {
-      bool value = false;
-      function flip() public {
-        value = !value;
-      }
-      function getValue() public view returns (bool) {
-        return value;
-      }
-    }
-  `);
-  const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {
-    data: compiled.object,
-    from: deployer,
-    ...GAS_ARGS,
-  });
-  const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});
-
-  return flipper;
-}
-
-export async function deployCollector(web3: Web3, deployer: string) {
-  const compiled = compileContract('Collector', `
-    contract Collector {
-      uint256 collected;
-      fallback() external payable {
-        giveMoney();
-      }
-      function giveMoney() public payable {
-        collected += msg.value;
-      }
-      function getCollected() public view returns (uint256) {
-        return collected;
-      }
-      function getUnaccounted() public view returns (uint256) {
-        return address(this).balance - collected;
-      }
-
-      function withdraw(address payable target) public {
-        target.transfer(collected);
-        collected = 0;
-      }
-    }
-  `);
-  const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {
-    data: compiled.object,
-    from: deployer,
-    ...GAS_ARGS,
-  });
-  const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});
-
-  return collector;
-}
-
-/** 
- * pallet evm_contract_helpers
- * @param web3 
- * @param caller - eth address
- * @returns 
- */
-export function contractHelpers(web3: Web3, caller: string) {
-  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});
-}
-
-/** 
- * evm collection helper
- * @param web3 
- * @param caller - eth address
- * @returns 
- */
-export function evmCollectionHelpers(web3: Web3, caller: string) {
-  return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
-}
-
-/** 
- * evm collection
- * @param web3 
- * @param caller - eth address
- * @returns 
- */
-export function evmCollection(web3: Web3, caller: string, collection: string, mode: CollectionMode = {type: 'NFT'}) {
-  let abi;
-  switch (mode.type) {
-    case 'Fungible':
-      abi = fungibleAbi;
-      break;
-    
-    case 'NFT':
-      abi = nonFungibleAbi;
-      break;
-    
-    case 'ReFungible':
-      abi = refungibleAbi;
-      break;
-
-    default:
-      throw 'Bad collection mode';
-  }
-  const contract = new web3.eth.Contract(abi as any, collection, {from: caller, ...GAS_ARGS});
-  return contract;
-}
-
-/**
- * Execute ethereum method call using substrate account
- * @param to target contract
- * @param mkTx - closure, receiving `contract.methods`, and returning method call,
- * to be used as following (assuming `to` = erc20 contract):
- * `m => m.transfer(to, amount)`
- *
- * # Example
- * ```ts
- * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));
- * ```
- */
-export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {
-  const tx = api.tx.evm.call(
-    subToEth(from.address),
-    to.options.address,
-    mkTx(to.methods).encodeABI(),
-    value,
-    GAS_ARGS.gas,
-    await web3.eth.getGasPrice(),
-    null,
-    null,
-    [],
-  );
-  const events = await submitTransactionAsync(from, tx);
-  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;
-}
-
-export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {
-  return (await getBalance(api, [evmToAddress(address)]))[0];
-}
-
-/**
- * Measure how much gas given closure consumes
- *
- * @param user which user balance will be checked
- */
-export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {
-  const before = await ethBalanceViaSub(api, user);
-
-  await call();
-
-  // In dev mode, the transaction might not finish processing in time
-  await waitNewBlocks(api, 1);
-  const after = await ethBalanceViaSub(api, user);
-
-  // Can't use .to.be.less, because chai doesn't supports bigint
-  expect(after < before).to.be.true;
-
-  return before - after;
-}
-
-type ElementOf<A> = A extends readonly (infer T)[] ? T : never;
-// I want a fancier api, not a memory efficiency
-export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {
-  if(args.length === 0) {
-    yield internalRest as any;
-    return;
-  }
-  for(const value of args[0]) {
-    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;
-  }
-}
\ No newline at end of file
deletedtests/src/deprecated-helpers/helpers.tsdiffbeforeafterboth
--- a/tests/src/deprecated-helpers/helpers.ts
+++ /dev/null
@@ -1,1881 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import '../interfaces/augment-api-rpc';
-import '../interfaces/augment-api-query';
-import {ApiPromise, Keyring} from '@polkadot/api';
-import type {AccountId, EventRecord, Event, BlockNumber} from '@polkadot/types/interfaces';
-import type {GenericEventData} from '@polkadot/types';
-import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';
-import {evmToAddress} from '@polkadot/util-crypto';
-import {AnyNumber} from '@polkadot/types-codec/types';
-import BN from 'bn.js';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';
-import {hexToStr, strToUTF16, utf16ToStr} from './util';
-import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';
-import {UpDataStructsTokenChild} from '../interfaces';
-import {Context} from 'mocha';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-export type CrossAccountId = {
-  Substrate: string,
-} | {
-  Ethereum: string,
-};
-
-
-export enum Pallets {
-  Inflation = 'inflation',
-  RmrkCore = 'rmrkcore',
-  RmrkEquip = 'rmrkequip',
-  ReFungible = 'refungible',
-  Fungible = 'fungible',
-  NFT = 'nonfungible',
-  Scheduler = 'scheduler',
-  AppPromotion = 'apppromotion',
-}
-
-export async function isUnique(): Promise<boolean> {
-  return usingApi(async api => {
-    const chain = await api.rpc.system.chain();
-
-    return chain.eq('UNIQUE');
-  });
-}
-
-export async function isQuartz(): Promise<boolean> {
-  return usingApi(async api => {
-    const chain = await api.rpc.system.chain();
-
-    return chain.eq('QUARTZ');
-  });
-}
-
-let modulesNames: any;
-export function getModuleNames(api: ApiPromise): string[] {
-  if (typeof modulesNames === 'undefined')
-    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());
-  return modulesNames;
-}
-
-export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {
-  return await usingApi(async api => {
-    const pallets = getModuleNames(api);
-
-    return requiredPallets.filter(p => !pallets.includes(p));
-  });
-}
-
-export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {
-  return (await missingRequiredPallets(requiredPallets)).length == 0;
-}
-
-export async function requirePallets(mocha: Context, requiredPallets: string[]) {
-  const missingPallets = await missingRequiredPallets(requiredPallets);
-
-  if (missingPallets.length > 0) {
-    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;
-    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;
-    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;
-
-    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);
-
-    mocha.skip();
-  }
-}
-
-export function bigIntToSub(api: ApiPromise, number: bigint) {
-  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();
-}
-
-export function bigIntToDecimals(number: bigint, decimals = 18): string {
-  const numberStr = number.toString();
-  const dotPos = numberStr.length - decimals;
-
-  if (dotPos <= 0) {
-    return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;
-  } else {
-    const intPart = numberStr.substring(0, dotPos);
-    const fractPart = numberStr.substring(dotPos);
-    return intPart + '.' + fractPart;
-  }
-}
-
-export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {
-  if (typeof input === 'string') {
-    if (input.length >= 47) {
-      return {Substrate: input};
-    } else if (input.length === 42 && input.startsWith('0x')) {
-      return {Ethereum: input.toLowerCase()};
-    } else if (input.length === 40 && !input.startsWith('0x')) {
-      return {Ethereum: '0x' + input.toLowerCase()};
-    } else {
-      throw new Error(`Unknown address format: "${input}"`);
-    }
-  }
-  if ('address' in input) {
-    return {Substrate: input.address};
-  }
-  if ('Ethereum' in input) {
-    return {
-      Ethereum: input.Ethereum.toLowerCase(),
-    };
-  } else if ('ethereum' in input) {
-    return {
-      Ethereum: (input as any).ethereum.toLowerCase(),
-    };
-  } else if ('Substrate' in input) {
-    return input;
-  } else if ('substrate' in input) {
-    return {
-      Substrate: (input as any).substrate,
-    };
-  }
-
-  // AccountId
-  return {Substrate: input.toString()};
-}
-export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {
-  input = normalizeAccountId(input);
-  if ('Substrate' in input) {
-    return input.Substrate;
-  } else {
-    return evmToAddress(input.Ethereum);
-  }
-}
-
-export const U128_MAX = (1n << 128n) - 1n;
-
-const MICROUNIQUE = 1_000_000_000_000n;
-const MILLIUNIQUE = 1_000n * MICROUNIQUE;
-const CENTIUNIQUE = 10n * MILLIUNIQUE;
-export const UNIQUE = 100n * CENTIUNIQUE;
-
-interface GenericResult<T> {
-  success: boolean;
-  data: T | null;
-}
-
-interface CreateCollectionResult {
-  success: boolean;
-  collectionId: number;
-}
-
-interface CreateItemResult {
-  success: boolean;
-  collectionId: number;
-  itemId: number;
-  recipient?: CrossAccountId;
-  amount?: number;
-}
-
-interface DestroyItemResult {
-  success: boolean;
-  collectionId: number;
-  itemId: number;
-  owner: CrossAccountId;
-  amount: number;
-}
-
-interface TransferResult {
-  collectionId: number;
-  itemId: number;
-  sender?: CrossAccountId;
-  recipient?: CrossAccountId;
-  value: bigint;
-}
-
-interface IReFungibleOwner {
-  fraction: BN;
-  owner: number[];
-}
-
-interface IGetMessage {
-  checkMsgUnqMethod: string;
-  checkMsgTrsMethod: string;
-  checkMsgSysMethod: string;
-}
-
-export interface IFungibleTokenDataType {
-  value: number;
-}
-
-export interface IChainLimits {
-  collectionNumbersLimit: number;
-  accountTokenOwnershipLimit: number;
-  collectionsAdminsLimit: number;
-  customDataLimit: number;
-  nftSponsorTransferTimeout: number;
-  fungibleSponsorTransferTimeout: number;
-  refungibleSponsorTransferTimeout: number;
-  //offchainSchemaLimit: number;
-  //constOnChainSchemaLimit: number;
-}
-
-export interface IReFungibleTokenDataType {
-  owner: IReFungibleOwner[];
-}
-
-export function uniqueEventMessage(events: EventRecord[]): IGetMessage {
-  let checkMsgUnqMethod = '';
-  let checkMsgTrsMethod = '';
-  let checkMsgSysMethod = '';
-  events.forEach(({event: {method, section}}) => {
-    if (section === 'common') {
-      checkMsgUnqMethod = method;
-    } else if (section === 'treasury') {
-      checkMsgTrsMethod = method;
-    } else if (section === 'system') {
-      checkMsgSysMethod = method;
-    } else { return null; }
-  });
-  const result: IGetMessage = {
-    checkMsgUnqMethod,
-    checkMsgTrsMethod,
-    checkMsgSysMethod,
-  };
-  return result;
-}
-
-export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {
-  const event = events.find(r => check(r.event));
-  if (!event) return;
-  return event.event as T;
-}
-
-export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;
-export function getGenericResult<T>(
-  events: EventRecord[],
-  expectSection: string,
-  expectMethod: string,
-  extractAction: (data: GenericEventData) => T
-): GenericResult<T>;
-
-export function getGenericResult<T>(
-  events: EventRecord[],
-  expectSection?: string,
-  expectMethod?: string,
-  extractAction?: (data: GenericEventData) => T,
-): GenericResult<T> {
-  let success = false;
-  let successData = null;
-
-  events.forEach(({event: {data, method, section}}) => {
-    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);
-    if (method === 'ExtrinsicSuccess') {
-      success = true;
-    } else if ((expectSection == section) && (expectMethod == method)) {
-      successData = extractAction!(data as any);
-    }
-  });
-
-  const result: GenericResult<T> = {
-    success,
-    data: successData,
-  };
-  return result;
-}
-
-export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {
-  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));
-  const result: CreateCollectionResult = {
-    success: genericResult.success,
-    collectionId: genericResult.data ?? 0,
-  };
-  return result;
-}
-
-export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {
-  const results: CreateItemResult[] = [];
-
-  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {
-    const collectionId = parseInt(data[0].toString(), 10);
-    const itemId = parseInt(data[1].toString(), 10);
-    const recipient = normalizeAccountId(data[2].toJSON() as any);
-    const amount = parseInt(data[3].toString(), 10);
-
-    const itemRes: CreateItemResult = {
-      success: true,
-      collectionId,
-      itemId,
-      recipient,
-      amount,
-    };
-
-    results.push(itemRes);
-    return results;
-  });
-
-  if (!genericResult.success) return [];
-  return results;
-}
-
-export function getCreateItemResult(events: EventRecord[]): CreateItemResult {
-  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));
-
-  if (genericResult.data == null)
-    return {
-      success: genericResult.success,
-      collectionId: 0,
-      itemId: 0,
-      amount: 0,
-    };
-  else
-    return {
-      success: genericResult.success,
-      collectionId: genericResult.data[0] as number,
-      itemId: genericResult.data[1] as number,
-      recipient: normalizeAccountId(genericResult.data![2] as any),
-      amount: genericResult.data[3] as number,
-    };
-}
-
-export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {
-  const results: DestroyItemResult[] = [];
-
-  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {
-    const collectionId = parseInt(data[0].toString(), 10);
-    const itemId = parseInt(data[1].toString(), 10);
-    const owner = normalizeAccountId(data[2].toJSON() as any);
-    const amount = parseInt(data[3].toString(), 10);
-
-    const itemRes: DestroyItemResult = {
-      success: true,
-      collectionId,
-      itemId,
-      owner,
-      amount,
-    };
-
-    results.push(itemRes);
-    return results;
-  });
-
-  if (!genericResult.success) return [];
-  return results;
-}
-
-export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {
-  for (const {event} of events) {
-    if (api.events.common.Transfer.is(event)) {
-      const [collection, token, sender, recipient, value] = event.data;
-      return {
-        collectionId: collection.toNumber(),
-        itemId: token.toNumber(),
-        sender: normalizeAccountId(sender.toJSON() as any),
-        recipient: normalizeAccountId(recipient.toJSON() as any),
-        value: value.toBigInt(),
-      };
-    }
-  }
-  throw new Error('no transfer event');
-}
-
-interface Nft {
-  type: 'NFT';
-}
-
-interface Fungible {
-  type: 'Fungible';
-  decimalPoints: number;
-}
-
-interface ReFungible {
-  type: 'ReFungible';
-}
-
-export type CollectionMode = Nft | Fungible | ReFungible;
-
-export type Property = {
-  key: any,
-  value: any,
-};
-
-type Permission = {
-  mutable: boolean;
-  collectionAdmin: boolean;
-  tokenOwner: boolean;
-}
-
-type PropertyPermission = {
-  key: any;
-  permission: Permission;
-}
-
-export type CreateCollectionParams = {
-  mode: CollectionMode,
-  name: string,
-  description: string,
-  tokenPrefix: string,
-  properties?: Array<Property>,
-  propPerm?: Array<PropertyPermission>
-};
-
-const defaultCreateCollectionParams: CreateCollectionParams = {
-  description: 'description',
-  mode: {type: 'NFT'},
-  name: 'name',
-  tokenPrefix: 'prefix',
-};
-
-export async function
-createCollection(
-  api: ApiPromise,
-  sender: IKeyringPair,
-  params: Partial<CreateCollectionParams> = {},
-): Promise<CreateCollectionResult> {
-  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
-  let modeprm = {};
-  if (mode.type === 'NFT') {
-    modeprm = {nft: null};
-  } else if (mode.type === 'Fungible') {
-    modeprm = {fungible: mode.decimalPoints};
-  } else if (mode.type === 'ReFungible') {
-    modeprm = {refungible: null};
-  }
-
-  const tx = api.tx.unique.createCollectionEx({
-    name: strToUTF16(name),
-    description: strToUTF16(description),
-    tokenPrefix: strToUTF16(tokenPrefix),
-    mode: modeprm as any,
-  });
-  const events = await executeTransaction(api, sender, tx);
-  return getCreateCollectionResult(events);
-}
-
-export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
-  const {name, description, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
-  let collectionId = 0;
-  await usingApi(async (api, privateKeyWrapper) => {
-    // Get number of collections before the transaction
-    const collectionCountBefore = await getCreatedCollectionCount(api);
-
-    // Run the CreateCollection transaction
-    const alicePrivateKey = privateKeyWrapper('//Alice');
-
-    const result = await createCollection(api, alicePrivateKey, params);
-
-    // Get number of collections after the transaction
-    const collectionCountAfter = await getCreatedCollectionCount(api);
-
-    // Get the collection
-    const collection = await queryCollectionExpectSuccess(api, result.collectionId);
-
-    // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.true;
-    expect(result.collectionId).to.be.equal(collectionCountAfter);
-    // tslint:disable-next-line:no-unused-expression
-    expect(collection).to.be.not.null;
-    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
-    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
-    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
-    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
-    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
-
-    collectionId = result.collectionId;
-  });
-
-  return collectionId;
-}
-
-export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
-  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
-  let collectionId = 0;
-  await usingApi(async (api, privateKeyWrapper) => {
-    // Get number of collections before the transaction
-    const collectionCountBefore = await getCreatedCollectionCount(api);
-
-    // Run the CreateCollection transaction
-    const alicePrivateKey = privateKeyWrapper('//Alice');
-
-    let modeprm = {};
-    if (mode.type === 'NFT') {
-      modeprm = {nft: null};
-    } else if (mode.type === 'Fungible') {
-      modeprm = {fungible: mode.decimalPoints};
-    } else if (mode.type === 'ReFungible') {
-      modeprm = {refungible: null};
-    }
-
-    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
-    const events = await submitTransactionAsync(alicePrivateKey, tx);
-    const result = getCreateCollectionResult(events);
-
-    // Get number of collections after the transaction
-    const collectionCountAfter = await getCreatedCollectionCount(api);
-
-    // Get the collection
-    const collection = await queryCollectionExpectSuccess(api, result.collectionId);
-
-    // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.true;
-    expect(result.collectionId).to.be.equal(collectionCountAfter);
-    // tslint:disable-next-line:no-unused-expression
-    expect(collection).to.be.not.null;
-    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');
-    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));
-    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);
-    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);
-    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);
-
-
-    collectionId = result.collectionId;
-  });
-
-  return collectionId;
-}
-
-export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {
-  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
-  await usingApi(async (api, privateKeyWrapper) => {
-    // Get number of collections before the transaction
-    const collectionCountBefore = await getCreatedCollectionCount(api);
-
-    // Run the CreateCollection transaction
-    const alicePrivateKey = privateKeyWrapper('//Alice');
-
-    let modeprm = {};
-    if (mode.type === 'NFT') {
-      modeprm = {nft: null};
-    } else if (mode.type === 'Fungible') {
-      modeprm = {fungible: mode.decimalPoints};
-    } else if (mode.type === 'ReFungible') {
-      modeprm = {refungible: null};
-    }
-
-    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});
-    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-
-
-    // Get number of collections after the transaction
-    const collectionCountAfter = await getCreatedCollectionCount(api);
-
-    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
-  });
-}
-
-export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {
-  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
-
-  let modeprm = {};
-  if (mode.type === 'NFT') {
-    modeprm = {nft: null};
-  } else if (mode.type === 'Fungible') {
-    modeprm = {fungible: mode.decimalPoints};
-  } else if (mode.type === 'ReFungible') {
-    modeprm = {refungible: null};
-  }
-
-  await usingApi(async (api, privateKeyWrapper) => {
-    // Get number of collections before the transaction
-    const collectionCountBefore = await getCreatedCollectionCount(api);
-
-    // Run the CreateCollection transaction
-    const alicePrivateKey = privateKeyWrapper('//Alice');
-    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
-    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-
-    // Get number of collections after the transaction
-    const collectionCountAfter = await getCreatedCollectionCount(api);
-
-    // What to expect
-    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
-  });
-}
-
-export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {
-  let bal = 0n;
-  let unused;
-  do {
-    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;
-    unused = privateKeyWrapper(`//${randomSeed}`);
-    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();
-  } while (bal !== 0n);
-  return unused;
-}
-
-export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {
-  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();
-}
-
-export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {
-  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));
-}
-
-export async function findNotExistingCollection(api: ApiPromise): Promise<number> {
-  const totalNumber = await getCreatedCollectionCount(api);
-  const newCollection: number = totalNumber + 1;
-  return newCollection;
-}
-
-function getDestroyResult(events: EventRecord[]): boolean {
-  let success = false;
-  events.forEach(({event: {method}}) => {
-    if (method == 'ExtrinsicSuccess') {
-      success = true;
-    }
-  });
-  return success;
-}
-
-export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {
-  await usingApi(async (api, privateKeyWrapper) => {
-    // Run the DestroyCollection transaction
-    const alicePrivateKey = privateKeyWrapper(senderSeed);
-    const tx = api.tx.unique.destroyCollection(collectionId);
-    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-  });
-}
-
-export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {
-  await usingApi(async (api, privateKeyWrapper) => {
-    // Run the DestroyCollection transaction
-    const alicePrivateKey = privateKeyWrapper(senderSeed);
-    const tx = api.tx.unique.destroyCollection(collectionId);
-    const events = await submitTransactionAsync(alicePrivateKey, tx);
-    const result = getDestroyResult(events);
-    expect(result).to.be.true;
-
-    // What to expect
-    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;
-  });
-}
-
-export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.true;
-  });
-}
-
-export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {
-  await usingApi(async(api) => {
-    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.true;
-  });
-};
-
-export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {
-  await usingApi(async (api, privateKeyWrapper) => {
-
-    // Run the transaction
-    const senderPrivateKey = privateKeyWrapper(sender);
-    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
-    const events = await submitTransactionAsync(senderPrivateKey, tx);
-    const result = getGenericResult(events);
-
-    // Get the collection
-    const collection = await queryCollectionExpectSuccess(api, collectionId);
-
-    // What to expect
-    expect(result.success).to.be.true;
-    expect(collection.sponsorship.toJSON()).to.deep.equal({
-      unconfirmed: sponsor,
-    });
-  });
-}
-
-export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {
-  await usingApi(async (api, privateKeyWrapper) => {
-
-    // Run the transaction
-    const alicePrivateKey = privateKeyWrapper(sender);
-    const tx = api.tx.unique.removeCollectionSponsor(collectionId);
-    const events = await submitTransactionAsync(alicePrivateKey, tx);
-    const result = getGenericResult(events);
-
-    // Get the collection
-    const collection = await queryCollectionExpectSuccess(api, collectionId);
-
-    // What to expect
-    expect(result.success).to.be.true;
-    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});
-  });
-}
-
-export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {
-  await usingApi(async (api, privateKeyWrapper) => {
-
-    // Run the transaction
-    const alicePrivateKey = privateKeyWrapper(senderSeed);
-    const tx = api.tx.unique.removeCollectionSponsor(collectionId);
-    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-  });
-}
-
-export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {
-  await usingApi(async (api, privateKeyWrapper) => {
-
-    // Run the transaction
-    const alicePrivateKey = privateKeyWrapper(senderSeed);
-    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);
-    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
-  });
-}
-
-export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
-  await usingApi(async (api, privateKeyWrapper) => {
-
-    // Run the transaction
-    const sender = privateKeyWrapper(senderSeed);
-    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
-  });
-}
-
-export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {
-  await usingApi(async (api) => {
-
-    // Run the transaction
-    const tx = api.tx.unique.confirmSponsorship(collectionId);
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    // Get the collection
-    const collection = await queryCollectionExpectSuccess(api, collectionId);
-
-    // What to expect
-    expect(result.success).to.be.true;
-    expect(collection.sponsorship.toJSON()).to.be.deep.equal({
-      confirmed: sender.address,
-    });
-  });
-}
-
-
-export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {
-  await usingApi(async (api, privateKeyWrapper) => {
-
-    // Run the transaction
-    const sender = privateKeyWrapper(senderSeed);
-    const tx = api.tx.unique.confirmSponsorship(collectionId);
-    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-  });
-}
-
-export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.true;
-  });
-}
-
-export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
-
-  await usingApi(async (api) => {
-
-    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.true;
-  });
-}
-
-export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
-
-  await usingApi(async (api) => {
-
-    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.true;
-  });
-}
-
-export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function getNextSponsored(
-  api: ApiPromise,
-  collectionId: number,
-  account: string | CrossAccountId,
-  tokenId: number,
-): Promise<number> {
-  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));
-}
-
-export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.true;
-  });
-}
-
-export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {
-  let allowlisted = false;
-  await usingApi(async (api) => {
-    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;
-  });
-  return allowlisted;
-}
-
-export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.true;
-  });
-}
-
-export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.true;
-  });
-}
-
-export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.false;
-  });
-}
-
-export interface CreateFungibleData {
-  readonly Value: bigint;
-}
-
-export interface CreateReFungibleData { }
-export interface CreateNftData { }
-
-export type CreateItemData = {
-  NFT: CreateNftData;
-} | {
-  Fungible: CreateFungibleData;
-} | {
-  ReFungible: CreateReFungibleData;
-};
-
-export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {
-  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
-  const events = await submitTransactionAsync(sender, tx);
-  return getGenericResult(events).success;
-}
-
-export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
-  await usingApi(async (api) => {
-    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
-    // if burning token by admin - use adminButnItemExpectSuccess
-    expect(balanceBefore >= BigInt(value)).to.be.true;
-
-    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;
-
-    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);
-    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);
-  });
-}
-
-export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);
-
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getCreateCollectionResult(events);
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);
-    const events = await submitTransactionAsync(sender, tx);
-    return getGenericResult(events).success;
-  });
-}
-
-export async function
-approve(
-  api: ApiPromise,
-  collectionId: number,
-  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,
-) {
-  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
-  const events = await submitTransactionAsync(owner, approveUniqueTx);
-  return getGenericResult(events).success;
-}
-
-export async function
-approveExpectSuccess(
-  collectionId: number,
-  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const result = await approve(api, collectionId, tokenId, owner, approved, amount);
-    expect(result).to.be.true;
-
-    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
-  });
-}
-
-export async function adminApproveFromExpectSuccess(
-  collectionId: number,
-  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
-    const events = await submitTransactionAsync(admin, approveUniqueTx);
-    const result = getGenericResult(events);
-    expect(result.success).to.be.true;
-
-    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));
-  });
-}
-
-export async function
-transferFrom(
-  api: ApiPromise,
-  collectionId: number,
-  tokenId: number,
-  accountApproved: IKeyringPair,
-  accountFrom: IKeyringPair | CrossAccountId,
-  accountTo: IKeyringPair | CrossAccountId,
-  value: number | bigint,
-) {
-  const from = normalizeAccountId(accountFrom);
-  const to = normalizeAccountId(accountTo);
-  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);
-  const events = await submitTransactionAsync(accountApproved, transferFromTx);
-  return getGenericResult(events).success;
-}
-
-export async function
-transferFromExpectSuccess(
-  collectionId: number,
-  tokenId: number,
-  accountApproved: IKeyringPair,
-  accountFrom: IKeyringPair | CrossAccountId,
-  accountTo: IKeyringPair | CrossAccountId,
-  value: number | bigint = 1,
-  type = 'NFT',
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const from = normalizeAccountId(accountFrom);
-    const to = normalizeAccountId(accountTo);
-    let balanceBefore = 0n;
-    if (type === 'Fungible' || type === 'ReFungible') {
-      balanceBefore = await getBalance(api, collectionId, to, tokenId);
-    }
-    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;
-    if (type === 'NFT') {
-      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
-    }
-    if (type === 'Fungible') {
-      const balanceAfter = await getBalance(api, collectionId, to, tokenId);
-      if (JSON.stringify(to) !== JSON.stringify(from)) {
-        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
-      } else {
-        expect(balanceAfter).to.be.equal(balanceBefore);
-      }
-    }
-    if (type === 'ReFungible') {
-      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));
-    }
-  });
-}
-
-export async function
-transferFromExpectFail(
-  collectionId: number,
-  tokenId: number,
-  accountApproved: IKeyringPair,
-  accountFrom: IKeyringPair,
-  accountTo: IKeyringPair,
-  value: number | bigint = 1,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);
-    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;
-    const result = getCreateCollectionResult(events);
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
-  });
-}
-
-/* eslint no-async-promise-executor: "off" */
-export async function getBlockNumber(api: ApiPromise): Promise<number> {
-  return new Promise<number>(async (resolve) => {
-    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {
-      unsubscribe();
-      resolve(head.number.toNumber());
-    });
-  });
-}
-
-export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {
-  await usingApi(async (api) => {
-    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));
-    const events = await submitTransactionAsync(sender, changeAdminTx);
-    const result = getCreateCollectionResult(events);
-    expect(result.success).to.be.true;
-  });
-}
-
-export async function adminApproveFromExpectFail(
-  collectionId: number,
-  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);
-    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;
-    const result = getGenericResult(events);
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function
-getFreeBalance(account: IKeyringPair): Promise<bigint> {
-  let balance = 0n;
-  await usingApi(async (api) => {
-    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());
-  });
-
-  return balance;
-}
-
-export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {
-  return usingApi(async api => {
-    // We are getting a *sibling* parachain sovereign account,
-    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c
-    const siblingPrefix = '0x7369626c';
-
-    const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);
-    const suffix = '000000000000000000000000000000000000000000000000';
-
-    return siblingPrefix + encodedParaId + suffix;
-  });
-}
-
-export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {
-  const tx = api.tx.balances.transfer(target, amount);
-  const events = await submitTransactionAsync(source, tx);
-  const result = getGenericResult(events);
-  expect(result.success).to.be.true;
-}
-
-export async function
-scheduleExpectSuccess(
-  operationTx: any,
-  sender: IKeyringPair,
-  blockSchedule: number,
-  scheduledId: string,
-  period = 1,
-  repetitions = 1,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const blockNumber: number | undefined = await getBlockNumber(api);
-    const expectedBlockNumber = blockNumber + blockSchedule;
-
-    expect(blockNumber).to.be.greaterThan(0);
-    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
-      scheduledId,
-      expectedBlockNumber,
-      repetitions > 1 ? [period, repetitions] : null,
-      0,
-      {Value: operationTx as any},
-    );
-
-    const events = await submitTransactionAsync(sender, scheduleTx);
-    expect(getGenericResult(events).success).to.be.true;
-  });
-}
-
-export async function
-scheduleExpectFailure(
-  operationTx: any,
-  sender: IKeyringPair,
-  blockSchedule: number,
-  scheduledId: string,
-  period = 1,
-  repetitions = 1,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const blockNumber: number | undefined = await getBlockNumber(api);
-    const expectedBlockNumber = blockNumber + blockSchedule;
-
-    expect(blockNumber).to.be.greaterThan(0);
-    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
-      scheduledId,
-      expectedBlockNumber,
-      repetitions <= 1 ? null : [period, repetitions],
-      0,
-      {Value: operationTx as any},
-    );
-
-    //const events =
-    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;
-    //expect(getGenericResult(events).success).to.be.false;
-  });
-}
-
-export async function
-scheduleTransferAndWaitExpectSuccess(
-  collectionId: number,
-  tokenId: number,
-  sender: IKeyringPair,
-  recipient: IKeyringPair,
-  value: number | bigint = 1,
-  blockSchedule: number,
-  scheduledId: string,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);
-
-    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
-
-    // sleep for n + 1 blocks
-    await waitNewBlocks(blockSchedule + 1);
-
-    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
-
-    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
-    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
-  });
-}
-
-export async function
-scheduleTransferExpectSuccess(
-  collectionId: number,
-  tokenId: number,
-  sender: IKeyringPair,
-  recipient: IKeyringPair,
-  value: number | bigint = 1,
-  blockSchedule: number,
-  scheduledId: string,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
-
-    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);
-
-    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
-  });
-}
-
-export async function
-scheduleTransferFundsPeriodicExpectSuccess(
-  amount: bigint,
-  sender: IKeyringPair,
-  recipient: IKeyringPair,
-  blockSchedule: number,
-  scheduledId: string,
-  period: number,
-  repetitions: number,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const transferTx = api.tx.balances.transfer(recipient.address, amount);
-
-    const balanceBefore = await getFreeBalance(recipient);
-
-    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);
-
-    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
-  });
-}
-
-export async function
-transfer(
-  api: ApiPromise,
-  collectionId: number,
-  tokenId: number,
-  sender: IKeyringPair,
-  recipient: IKeyringPair | CrossAccountId,
-  value: number | bigint,
-) : Promise<boolean> {
-  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
-  const events = await executeTransaction(api, sender, transferTx);
-  return getGenericResult(events).success;
-}
-
-export async function
-transferExpectSuccess(
-  collectionId: number,
-  tokenId: number,
-  sender: IKeyringPair,
-  recipient: IKeyringPair | CrossAccountId,
-  value: number | bigint = 1,
-  type = 'NFT',
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const from = normalizeAccountId(sender);
-    const to = normalizeAccountId(recipient);
-
-    let balanceBefore = 0n;
-    if (type === 'Fungible' || type === 'ReFungible') {
-      balanceBefore = await getBalance(api, collectionId, to, tokenId);
-    }
-
-    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
-    const events = await executeTransaction(api, sender, transferTx);
-    const result = getTransferResult(api, events);
-
-    expect(result.collectionId).to.be.equal(collectionId);
-    expect(result.itemId).to.be.equal(tokenId);
-    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));
-    expect(result.recipient).to.be.deep.equal(to);
-    expect(result.value).to.be.equal(BigInt(value));
-
-    if (type === 'NFT') {
-      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);
-    }
-    if (type === 'Fungible' || type === 'ReFungible') {
-      const balanceAfter = await getBalance(api, collectionId, to, tokenId);
-      if (JSON.stringify(to) !== JSON.stringify(from)) {
-        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));
-      } else {
-        expect(balanceAfter).to.be.equal(balanceBefore);
-      }
-    }
-  });
-}
-
-export async function
-transferExpectFailure(
-  collectionId: number,
-  tokenId: number,
-  sender: IKeyringPair,
-  recipient: IKeyringPair | CrossAccountId,
-  value: number | bigint = 1,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);
-    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;
-    const result = getGenericResult(events);
-    // if (events && Array.isArray(events)) {
-    //   const result = getCreateCollectionResult(events);
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
-    //}
-  });
-}
-
-export async function
-approveExpectFail(
-  collectionId: number,
-  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,
-) {
-  await usingApi(async (api: ApiPromise) => {
-    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);
-    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;
-    const result = getCreateCollectionResult(events);
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function getBalance(
-  api: ApiPromise,
-  collectionId: number,
-  owner: string | CrossAccountId | IKeyringPair,
-  token: number,
-): Promise<bigint> {
-  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();
-}
-export async function getTokenOwner(
-  api: ApiPromise,
-  collectionId: number,
-  token: number,
-): Promise<CrossAccountId> {
-  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;
-  if (owner == null) throw new Error('owner == null');
-  return normalizeAccountId(owner);
-}
-export async function getTopmostTokenOwner(
-  api: ApiPromise,
-  collectionId: number,
-  token: number,
-): Promise<CrossAccountId> {
-  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;
-  if (owner == null) throw new Error('owner == null');
-  return normalizeAccountId(owner);
-}
-export async function getTokenChildren(
-  api: ApiPromise,
-  collectionId: number,
-  tokenId: number,
-): Promise<UpDataStructsTokenChild[]> {
-  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;
-}
-export async function isTokenExists(
-  api: ApiPromise,
-  collectionId: number,
-  token: number,
-): Promise<boolean> {
-  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();
-}
-export async function getLastTokenId(
-  api: ApiPromise,
-  collectionId: number,
-): Promise<number> {
-  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();
-}
-export async function getAdminList(
-  api: ApiPromise,
-  collectionId: number,
-): Promise<string[]> {
-  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;
-}
-export async function getTokenProperties(
-  api: ApiPromise,
-  collectionId: number,
-  tokenId: number,
-  propertyKeys: string[],
-): Promise<UpDataStructsProperty[]> {
-  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;
-}
-
-export async function createFungibleItemExpectSuccess(
-  sender: IKeyringPair,
-  collectionId: number,
-  data: CreateFungibleData,
-  owner: CrossAccountId | string = sender.address,
-) {
-  return await usingApi(async (api) => {
-    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});
-
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getCreateItemResult(events);
-
-    expect(result.success).to.be.true;
-    return result.itemId;
-  });
-}
-
-export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
-  await usingApi(async (api) => {
-    const to = normalizeAccountId(owner);
-    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
-
-    const events = await submitTransactionAsync(sender, tx);
-    expect(getGenericResult(events).success).to.be.true;
-  });
-}
-
-export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {
-  await usingApi(async (api) => {
-    const to = normalizeAccountId(owner);
-    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);
-
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getCreateItemsResult(events);
-
-    for (const res of result) {
-      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
-    }
-  });
-}
-
-export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);
-
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getCreateItemsResult(events);
-
-    for (const res of result) {
-      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;
-    }
-  });
-}
-
-export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {
-  let newItemId = 0;
-  await usingApi(async (api) => {
-    const to = normalizeAccountId(owner);
-    const itemCountBefore = await getLastTokenId(api, collectionId);
-    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
-
-    let tx;
-    if (createMode === 'Fungible') {
-      const createData = {fungible: {value: 10}};
-      tx = api.tx.unique.createItem(collectionId, to, createData as any);
-    } else if (createMode === 'ReFungible') {
-      const createData = {refungible: {pieces: 100}};
-      tx = api.tx.unique.createItem(collectionId, to, createData as any);
-    } else {
-      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});
-      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);
-    }
-
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getCreateItemResult(events);
-
-    const itemCountAfter = await getLastTokenId(api, collectionId);
-    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
-
-    if (createMode === 'NFT') {
-      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;
-    }
-
-    // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.true;
-    if (createMode === 'Fungible') {
-      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
-    } else {
-      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
-    }
-    expect(collectionId).to.be.equal(result.collectionId);
-    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
-    expect(to).to.be.deep.equal(result.recipient);
-    newItemId = result.itemId;
-  });
-  return newItemId;
-}
-
-export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {
-  await usingApi(async (api) => {
-
-    let tx;
-    if (createMode === 'NFT') {
-      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;
-      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);
-    } else {
-      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
-    }
-
-
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;
-    const result = getCreateItemResult(events);
-
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
-  let newItemId = 0;
-  await usingApi(async (api) => {
-    const to = normalizeAccountId(owner);
-    const itemCountBefore = await getLastTokenId(api, collectionId);
-    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);
-
-    let tx;
-    if (createMode === 'Fungible') {
-      const createData = {fungible: {value: 10}};
-      tx = api.tx.unique.createItem(collectionId, to, createData as any);
-    } else if (createMode === 'ReFungible') {
-      const createData = {refungible: {pieces: 100}};
-      tx = api.tx.unique.createItem(collectionId, to, createData as any);
-    } else {
-      const createData = {nft: {}};
-      tx = api.tx.unique.createItem(collectionId, to, createData as any);
-    }
-
-    const events = await executeTransaction(api, sender, tx);
-    const result = getCreateItemResult(events);
-
-    const itemCountAfter = await getLastTokenId(api, collectionId);
-    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);
-
-    // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.true;
-    if (createMode === 'Fungible') {
-      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);
-    } else {
-      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);
-    }
-    expect(collectionId).to.be.equal(result.collectionId);
-    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());
-    expect(to).to.be.deep.equal(result.recipient);
-    newItemId = result.itemId;
-  });
-  return newItemId;
-}
-
-export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {
-  const createData = {refungible: {pieces: amount}};
-  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);
-
-  const events = await submitTransactionAsync(sender, tx);
-  return  getCreateItemResult(events);
-}
-
-export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);
-
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getCreateItemResult(events);
-
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function setPublicAccessModeExpectSuccess(
-  sender: IKeyringPair, collectionId: number,
-  accessMode: 'Normal' | 'AllowList',
-) {
-  await usingApi(async (api) => {
-
-    // Run the transaction
-    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    // Get the collection
-    const collection = await queryCollectionExpectSuccess(api, collectionId);
-
-    // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.true;
-    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);
-  });
-}
-
-export async function setPublicAccessModeExpectFail(
-  sender: IKeyringPair, collectionId: number,
-  accessMode: 'Normal' | 'AllowList',
-) {
-  await usingApi(async (api) => {
-
-    // Run the transaction
-    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getGenericResult(events);
-
-    // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
-  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');
-}
-
-export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {
-  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');
-}
-
-export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {
-  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');
-}
-
-export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {
-  await usingApi(async (api) => {
-
-    // Run the transaction
-    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-    expect(result.success).to.be.true;
-
-    // Get the collection
-    const collection = await queryCollectionExpectSuccess(api, collectionId);
-
-    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);
-  });
-}
-
-export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {
-  await setMintPermissionExpectSuccess(sender, collectionId, true);
-}
-
-export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {
-  await usingApi(async (api) => {
-    // Run the transaction
-    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getCreateCollectionResult(events);
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {
-  await usingApi(async (api) => {
-    // Run the transaction
-    const tx = api.tx.unique.setChainLimits(limits);
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getCreateCollectionResult(events);
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {
-  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();
-}
-
-export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
-  await usingApi(async (api) => {
-    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;
-
-    // Run the transaction
-    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-    expect(result.success).to.be.true;
-
-    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
-  });
-}
-
-export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
-  await usingApi(async (api) => {
-
-    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
-
-    // Run the transaction
-    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-    expect(result.success).to.be.true;
-
-    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
-  });
-}
-
-export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
-  await usingApi(async (api) => {
-
-    // Run the transaction
-    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getGenericResult(events);
-
-    // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
-  });
-}
-
-export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
-  await usingApi(async (api) => {
-    // Run the transaction
-    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.true;
-  });
-}
-
-export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {
-  await usingApi(async (api) => {
-    // Run the transaction
-    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getGenericResult(events);
-
-    // What to expect
-    // tslint:disable-next-line:no-unused-expression
-    expect(result.success).to.be.false;
-  });
-}
-
-export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)
-  : Promise<UpDataStructsRpcCollection | null> => {
-  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);
-};
-
-export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
-  // set global object - collectionsCount
-  return (await api.rpc.unique.collectionStats()).created.toNumber();
-};
-
-export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {
-  return (await api.rpc.unique.collectionById(collectionId)).unwrap();
-}
-
-export async function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {
-  (process.env.RUN_XCM_TESTS && !opts.skip
-    ? describe
-    : describe.skip)(title, fn);
-}
-
-describeXCM.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeXCM(name, fn, {skip: true});
-
-export async function waitNewBlocks(blocksCount = 1): Promise<void> {
-  await usingApi(async (api) => {
-    const promise = new Promise<void>(async (resolve) => {
-      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {
-        if (blocksCount > 0) {
-          blocksCount--;
-        } else {
-          unsubscribe();
-          resolve();
-        }
-      });
-    });
-    return promise;
-  });
-}
-
-export async function waitEvent(
-  api: ApiPromise,
-  maxBlocksToWait: number,
-  eventSection: string,
-  eventMethod: string,
-): Promise<EventRecord | null> {
-
-  const promise = new Promise<EventRecord | null>(async (resolve) => {
-    const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {
-      const blockNumber = header.number.toHuman();
-      const blockHash = header.hash;
-      const eventIdStr = `${eventSection}.${eventMethod}`;
-      const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;
-
-      console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);
-
-      const apiAt = await api.at(blockHash);
-      const eventRecords = await apiAt.query.system.events();
-
-      const neededEvent = eventRecords.find(r => {
-        return r.event.section == eventSection && r.event.method == eventMethod;
-      });
-
-      if (neededEvent) {
-        unsubscribe();
-        resolve(neededEvent);
-      } else if (maxBlocksToWait > 0) {
-        maxBlocksToWait--;
-      } else {
-        console.log(`Event \`${eventIdStr}\` is NOT found`);
-
-        unsubscribe();
-        resolve(null);
-      }
-    });
-  });
-  return promise;
-}
-
-export async function repartitionRFT(
-  api: ApiPromise,
-  collectionId: number,
-  sender: IKeyringPair,
-  tokenId: number,
-  amount: bigint,
-): Promise<boolean> {
-  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);
-  const events = await submitTransactionAsync(sender, tx);
-  const result = getGenericResult(events);
-
-  return result.success;
-}
-
-export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
-  let i: any = it;
-  if (opts.only) i = i.only;
-  else if (opts.skip) i = i.skip;
-  i(name, async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      await cb({api, privateKeyWrapper});
-    });
-  });
-}
-
-itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});
-itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});
-
-let accountSeed = 10000;
-export function generateKeyringPair(keyring: Keyring) {
-  const privateKey = `0xDEADBEEF${(Date.now() + (accountSeed++)).toString(16).padStart(64 - 8, '0')}`;
-  return keyring.addFromUri(privateKey);
-}
-
-export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {
-  const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
-  const subEvents = (await api.query.system.events.at(blockHash))
-    .filter(x => x.event.section === section)
-    .map((x) => x.toHuman());
-  const events = methods.map((m) => {
-    return {
-      event: {
-        method: m,
-        section,
-      },
-    };
-  });
-  if (!dryRun) {
-    expect(subEvents).to.be.like(events);
-  }
-  return subEvents;
-}
deletedtests/src/deprecated-helpers/util.tsdiffbeforeafterboth
--- a/tests/src/deprecated-helpers/util.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-export function strToUTF16(str: string): any {
-  const buf: number[] = [];
-  for (let i=0, strLen=str.length; i < strLen; i++) {
-    buf.push(str.charCodeAt(i));
-  }
-  return buf;
-}
-
-export function utf16ToStr(buf: number[]): string {
-  let str = '';
-  for (let i=0, strLen=buf.length; i < strLen; i++) {
-    if (buf[i] != 0) str += String.fromCharCode(buf[i]);
-    else break;
-  }
-  return str;
-}
-
-export function hexToStr(buf: string): string {
-  let str = '';
-  let hexStart = buf.indexOf('0x');
-  if (hexStart < 0) hexStart = 0;
-  else hexStart = 2;  
-  for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {
-    const ch = buf[i] + buf[i+1];
-    const num = parseInt(ch, 16);
-    if (num != 0) str += String.fromCharCode(num);
-    else break;
-  }
-  return str;
-}
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -361,6 +361,7 @@
   }
 
   clearApi() {
+    super.clearApi();
     this.web3 = null;
   }
 
modifiedtests/src/rmrk/acceptNft.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/acceptNft.seqtest.ts
+++ b/tests/src/rmrk/acceptNft.seqtest.ts
@@ -7,8 +7,7 @@
   acceptNft,
 } from './util/tx';
 import {NftIdTuple} from './util/fetch';
-import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
+import {isNftChildOfAnother, expectTxFailure, requirePallets, Pallets} from './util/helpers';
 
 describe('integration test: accept NFT', () => {
   let api: any;
@@ -104,5 +103,5 @@
     expect(isChild).to.be.false;
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/addResource.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/addResource.seqtest.ts
+++ b/tests/src/rmrk/addResource.seqtest.ts
@@ -1,7 +1,7 @@
 import {expect} from 'chai';
 import {getApiConnection} from '../substrate/substrate-api';
 import {NftIdTuple} from './util/fetch';
-import {expectTxFailure, getResourceById} from './util/helpers';
+import {expectTxFailure, getResourceById, requirePallets, Pallets} from './util/helpers';
 import {
   addNftBasicResource,
   acceptNftResource,
@@ -12,7 +12,6 @@
   addNftComposableResource,
 } from './util/tx';
 import {RmrkTraitsResourceResourceInfo as ResourceInfo} from '@polkadot/types/lookup';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
 
 describe('integration test: add NFT resource', () => {
   const alice = '//Alice';
@@ -433,6 +432,6 @@
 
 
   after(() => {
-    api.disconnect();
+    after(async() => { await api.disconnect(); });
   });
 });
modifiedtests/src/rmrk/addTheme.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/addTheme.seqtest.ts
+++ b/tests/src/rmrk/addTheme.seqtest.ts
@@ -1,9 +1,8 @@
 import {expect} from 'chai';
 import {getApiConnection} from '../substrate/substrate-api';
 import {createBase, addTheme} from './util/tx';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {getThemeNames} from './util/fetch';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
 
 describe('integration test: add Theme to Base', () => {
   let api: any;
@@ -126,5 +125,5 @@
     await expectTxFailure(/rmrkEquip\.PermissionError/, tx);
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/burnNft.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/burnNft.seqtest.ts
+++ b/tests/src/rmrk/burnNft.seqtest.ts
@@ -1,11 +1,10 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {NftIdTuple, getChildren} from './util/fetch';
 import {burnNft, createCollection, sendNft, mintNft} from './util/tx';
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -167,7 +166,5 @@
     });
   });
 
-  after(() => {
-    api.disconnect();
-  });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/changeCollectionIssuer.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/changeCollectionIssuer.seqtest.ts
+++ b/tests/src/rmrk/changeCollectionIssuer.seqtest.ts
@@ -1,6 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {
   changeIssuer,
   createCollection,
@@ -50,7 +49,5 @@
     });
   });
 
-  after(() => {
-    api.disconnect();
-  });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/createBase.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/createBase.seqtest.ts
+++ b/tests/src/rmrk/createBase.seqtest.ts
@@ -1,5 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
+import {requirePallets, Pallets} from './util/helpers';
 import {createCollection, createBase} from './util/tx';
 
 describe('integration test: create new Base', () => {
@@ -84,5 +84,5 @@
     ]);
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/createCollection.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/createCollection.seqtest.ts
+++ b/tests/src/rmrk/createCollection.seqtest.ts
@@ -1,5 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
+import {requirePallets, Pallets} from './util/helpers';
 import {createCollection} from './util/tx';
 
 describe('Integration test: create new collection', () => {
@@ -21,5 +21,5 @@
     await createCollection(api, alice, 'no-limit-metadata', null, 'no-limit-symbol');
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/deleteCollection.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/deleteCollection.seqtest.ts
+++ b/tests/src/rmrk/deleteCollection.seqtest.ts
@@ -1,6 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {createCollection, deleteCollection} from './util/tx';
 
 describe('integration test: delete collection', () => {
@@ -43,7 +42,5 @@
     });
   });
 
-  after(() => {
-    api.disconnect();
-  });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/equipNft.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/equipNft.seqtest.ts
+++ b/tests/src/rmrk/equipNft.seqtest.ts
@@ -1,9 +1,8 @@
 import {ApiPromise} from '@polkadot/api';
 import {expect} from 'chai';
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
 import {getNft, NftIdTuple} from './util/fetch';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {
   addNftComposableResource,
   addNftSlotResource,
@@ -337,7 +336,5 @@
     await expectTxFailure(/rmrkEquip\.CollectionNotEquippable/, tx);
   });
 
-  after(() => {
-    api.disconnect();
-  });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/getOwnedNfts.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/getOwnedNfts.seqtest.ts
+++ b/tests/src/rmrk/getOwnedNfts.seqtest.ts
@@ -1,6 +1,6 @@
 import {expect} from 'chai';
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
+import {requirePallets, Pallets} from './util/helpers';
 import {getOwnedNfts} from './util/fetch';
 import {mintNft, createCollection} from './util/tx';
 
@@ -76,5 +76,5 @@
     });
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/lockCollection.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/lockCollection.seqtest.ts
+++ b/tests/src/rmrk/lockCollection.seqtest.ts
@@ -1,6 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {createCollection, lockCollection, mintNft} from './util/tx';
 
 describe('integration test: lock collection', () => {
@@ -113,7 +112,5 @@
     });
   });
 
-  after(() => {
-    api.disconnect();
-  });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/mintNft.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/mintNft.seqtest.ts
+++ b/tests/src/rmrk/mintNft.seqtest.ts
@@ -1,8 +1,7 @@
 import {expect} from 'chai';
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
 import {getNft} from './util/fetch';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {createCollection, mintNft} from './util/tx';
 
 describe('integration test: mint new NFT', () => {
@@ -208,5 +207,5 @@
     expect(nft.isSome).to.be.false;
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/rejectNft.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/rejectNft.seqtest.ts
+++ b/tests/src/rmrk/rejectNft.seqtest.ts
@@ -7,8 +7,7 @@
   rejectNft,
 } from './util/tx';
 import {NftIdTuple} from './util/fetch';
-import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
+import {isNftChildOfAnother, expectTxFailure, requirePallets, Pallets} from './util/helpers';
 
 describe('integration test: reject NFT', () => {
   let api: any;
@@ -91,5 +90,5 @@
     await expectTxFailure(/rmrkCore\.CannotRejectNonPendingNft/, tx);
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/removeResource.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/removeResource.seqtest.ts
+++ b/tests/src/rmrk/removeResource.seqtest.ts
@@ -1,7 +1,6 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
 import {NftIdTuple} from './util/fetch';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {
   acceptResourceRemoval, addNftBasicResource, createCollection, mintNft, removeNftResource, sendNft,
 } from './util/tx';
@@ -337,7 +336,5 @@
     await expectTxFailure(/rmrkCore\.NoPermission/, tx);
   });
 
-  after(() => {
-    api.disconnect();
-  });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/rmrkIsolation.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/rmrkIsolation.seqtest.ts
+++ b/tests/src/rmrk/rmrkIsolation.seqtest.ts
@@ -1,85 +1,80 @@
-import {expect} from 'chai';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {
-  createCollectionExpectSuccess,
-  createItemExpectSuccess,
-  getCreateCollectionResult,
-  getDetailedCollectionInfo,
-  getGenericResult,
-  requirePallets,
-  normalizeAccountId,
-  Pallets,
-} from '../deprecated-helpers/helpers';
+import {executeTransaction} from '../substrate/substrate-api';
 import {IKeyringPair} from '@polkadot/types/types';
-import {ApiPromise} from '@polkadot/api';
-import {it} from 'mocha';
+import {itSub, expect, usingPlaygrounds, Pallets, requirePalletsOrSkip} from '../util';
+import {UniqueHelper} from '../util/playgrounds/unique';
 
 let alice: IKeyringPair;
 let bob: IKeyringPair;
 
-async function createRmrkCollection(api: ApiPromise, sender: IKeyringPair): Promise<{uniqueId: number, rmrkId: number}> {
-  const tx = api.tx.rmrkCore.createCollection('metadata', null, 'symbol');
-  const events = await executeTransaction(api, sender, tx);
+async function createRmrkCollection(helper: UniqueHelper, sender: IKeyringPair): Promise<{uniqueId: number, rmrkId: number}> {
+  const result = await helper.executeExtrinsic(sender, 'api.tx.rmrkCore.createCollection', ['metadata', null, 'symbol'], true);
+
+  const uniqueId = helper.util.extractCollectionIdFromCreationResult(result);
 
-  const uniqueResult = getCreateCollectionResult(events);
-  const rmrkResult = getGenericResult(events, 'rmrkCore', 'CollectionCreated', (data) => {
-    return parseInt(data[1].toString(), 10);
+  let rmrkId = null;
+  result.result.events.forEach(({event: {data, method, section}}) => {
+    if ((section === 'rmrkCore') && (method === 'CollectionCreated')) {
+      rmrkId = parseInt(data[1].toString(), 10);
+    }
   });
 
+  if (rmrkId === null) {
+    throw Error('No rmrkCore.CollectionCreated event was found!');
+  }
+
   return {
-    uniqueId: uniqueResult.collectionId,
-    rmrkId: rmrkResult.data!,
+    uniqueId,
+    rmrkId,
   };
 }
 
-async function createRmrkNft(api: ApiPromise, sender: IKeyringPair, collectionId: number): Promise<number> {
-  const tx = api.tx.rmrkCore.mintNft(
-    sender.address,
-    collectionId,
-    sender.address,
-    null,
-    'nft-metadata',
+async function createRmrkNft(helper: UniqueHelper, sender: IKeyringPair, collectionId: number): Promise<number> {
+  const result = await helper.executeExtrinsic(
+    sender,
+    'api.tx.rmrkCore.mintNft',
+    [
+      sender.address,
+      collectionId,
+      sender.address,
+      null,
+      'nft-metadata',
+      true,
+      null,
+    ],
     true,
-    null,
   );
-  const events = await executeTransaction(api, sender, tx);
-  const result = getGenericResult(events, 'rmrkCore', 'NftMinted', (data) => {
-    return parseInt(data[2].toString(), 10);
+
+  let rmrkNftId = null;
+  result.result.events.forEach(({event: {data, method, section}}) => {
+    if ((section === 'rmrkCore') && (method === 'NftMinted')) {
+      rmrkNftId = parseInt(data[2].toString(), 10);
+    }
   });
 
-  return result.data!;
-}
+  if (rmrkNftId === null) {
+    throw Error('No rmrkCore.NftMinted event was found!');
+  }
 
-async function isUnique(): Promise<boolean> {
-  return usingApi(async api => {
-    const chain = await api.rpc.system.chain();
-
-    return chain.eq('UNIQUE');
-  });
+  return rmrkNftId;
 }
 
 describe('RMRK External Integration Test', async () => {
-  const itRmrk = (await isUnique() ? it : it.skip);
-
   before(async function() {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      await requirePallets(this, [Pallets.RmrkCore]);
+    await usingPlaygrounds(async (_helper, privateKey) => {
+      alice = await privateKey('//Alice');
     });
   });
 
-  itRmrk('Creates a new RMRK collection that is mapped to a different ID and is tagged as external', async () => {
-    await usingApi(async api => {
-      // throwaway collection to bump last Unique collection ID to test ID mapping
-      await createCollectionExpectSuccess();
+  itSub.ifWithPallets('Creates a new RMRK collection that is mapped to a different ID and is tagged as external', [Pallets.RmrkCore], async ({helper}) => {
+    // throw away collection to bump last Unique collection ID to test ID mapping
+    await helper.nft.mintCollection(alice, {tokenPrefix: 'unqt'});
 
-      const collectionIds = await createRmrkCollection(api, alice);
+    const collectionIds = await createRmrkCollection(helper, alice);
 
-      expect(collectionIds.rmrkId).to.be.lessThan(collectionIds.uniqueId, 'collection ID mapping');
+    expect(collectionIds.rmrkId).to.be.lessThan(collectionIds.uniqueId, 'collection ID mapping');
 
-      const collection = (await getDetailedCollectionInfo(api, collectionIds.uniqueId))!;
-      expect(collection.readOnly.toHuman(), 'tagged external').to.be.true;
-    });
+    const collection = (await helper.nft.getCollectionObject(collectionIds.uniqueId).getData())!; // (await getDetailedCollectionInfo(api, collectionIds.uniqueId))!;
+    expect(collection.raw.readOnly, 'tagged external').to.be.true;
   });
 });
 
@@ -87,165 +82,144 @@
   let uniqueCollectionId: number;
   let rmrkCollectionId: number;
   let rmrkNftId: number;
+  let normalizedAlice: {Substrate: string};
 
-  const itRmrk = (await isUnique() ? it : it.skip);
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      alice = await privateKey('//Alice');
+      bob = await privateKey('//Bob');
+      normalizedAlice = {Substrate: helper.address.normalizeSubstrateToChainFormat(alice.address)};
 
-  before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
+      requirePalletsOrSkip(this, helper, [Pallets.RmrkCore]);
 
-      const collectionIds = await createRmrkCollection(api, alice);
+      const collectionIds = await createRmrkCollection(helper, alice);
       uniqueCollectionId = collectionIds.uniqueId;
       rmrkCollectionId = collectionIds.rmrkId;
 
-      rmrkNftId = await createRmrkNft(api, alice, rmrkCollectionId);
+      rmrkNftId = await createRmrkNft(helper, alice, rmrkCollectionId);
     });
   });
 
-  itRmrk('[Negative] Forbids Unique operations with an external collection, handled by dispatch_call', async () => {
-    await usingApi(async api => {
-      // Collection item creation
+  itSub.ifWithPallets('[Negative] Forbids Unique operations with an external collection, handled by dispatch_call', [Pallets.RmrkCore], async ({helper}) => {
+    // Collection item creation
 
-      const txCreateItem = api.tx.unique.createItem(uniqueCollectionId, normalizeAccountId(alice), 'NFT');
-      await expect(executeTransaction(api, alice, txCreateItem), 'creating item')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.mintToken(alice, {collectionId: uniqueCollectionId, owner: {Substrate: alice.address}}), 'creating item')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txCreateMultipleItems = api.tx.unique.createMultipleItems(uniqueCollectionId, normalizeAccountId(alice), [{NFT: {}}, {NFT: {}}]);
-      await expect(executeTransaction(api, alice, txCreateMultipleItems), 'creating multiple')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    const txCreateMultipleItems = helper.getApi().tx.unique.createMultipleItems(uniqueCollectionId, normalizedAlice, [{NFT: {}}, {NFT: {}}]);
+    await expect(executeTransaction(helper.getApi(), alice, txCreateMultipleItems), 'creating multiple')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
+  
+    await expect(helper.nft.mintMultipleTokens(alice, uniqueCollectionId, [{owner: {Substrate: alice.address}}]), 'creating multiple ex')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txCreateMultipleItemsEx = api.tx.unique.createMultipleItemsEx(uniqueCollectionId, {NFT: [{}]});
-      await expect(executeTransaction(api, alice, txCreateMultipleItemsEx), 'creating multiple ex')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    // Collection properties
 
-      // Collection properties
+    await expect(helper.nft.setProperties(alice, uniqueCollectionId, [{key: 'a', value: '1'}, {key: 'b'}]), 'setting collection properties')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txSetCollectionProperties = api.tx.unique.setCollectionProperties(uniqueCollectionId, [{key: 'a', value: '1'}, {key: 'b'}]);
-      await expect(executeTransaction(api, alice, txSetCollectionProperties), 'setting collection properties')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.deleteProperties(alice, uniqueCollectionId, ['a']), 'deleting collection properties')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txDeleteCollectionProperties = api.tx.unique.deleteCollectionProperties(uniqueCollectionId, ['a']);
-      await expect(executeTransaction(api, alice, txDeleteCollectionProperties), 'deleting collection properties')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.setTokenPropertyPermissions(alice, uniqueCollectionId, [{key: 'a', permission: {mutable: true}}]), 'setting property permissions')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txsetTokenPropertyPermissions = api.tx.unique.setTokenPropertyPermissions(uniqueCollectionId, [{key: 'a', permission: {mutable: true}}]);
-      await expect(executeTransaction(api, alice, txsetTokenPropertyPermissions), 'setting property permissions')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    // NFT
 
-      // NFT
+    await expect(helper.nft.burnToken(alice, uniqueCollectionId, rmrkNftId, 1n), 'burning')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txBurn = api.tx.unique.burnItem(uniqueCollectionId, rmrkNftId, 1);
-      await expect(executeTransaction(api, alice, txBurn), 'burning').to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.burnTokenFrom(alice, uniqueCollectionId, rmrkNftId, {Substrate: alice.address}, 1n), 'burning-from')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txBurnFrom = api.tx.unique.burnFrom(uniqueCollectionId, normalizeAccountId(alice), rmrkNftId, 1);
-      await expect(executeTransaction(api, alice, txBurnFrom), 'burning-from').to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.transferToken(alice, uniqueCollectionId, rmrkNftId, {Substrate: bob.address}), 'transferring')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txTransfer = api.tx.unique.transfer(normalizeAccountId(bob), uniqueCollectionId, rmrkNftId, 1);
-      await expect(executeTransaction(api, alice, txTransfer), 'transferring').to.be.rejectedWith(/common\.CollectionIsExternal/);
-
-      const txApprove = api.tx.unique.approve(normalizeAccountId(bob), uniqueCollectionId, rmrkNftId, 1);
-      await expect(executeTransaction(api, alice, txApprove), 'approving').to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.approveToken(alice, uniqueCollectionId, rmrkNftId, {Substrate: bob.address}), 'approving')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txTransferFrom = api.tx.unique.transferFrom(normalizeAccountId(alice), normalizeAccountId(bob), uniqueCollectionId, rmrkNftId, 1);
-      await expect(executeTransaction(api, alice, txTransferFrom), 'transferring-from').to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.transferTokenFrom(alice, uniqueCollectionId, rmrkNftId, {Substrate: alice.address}, {Substrate: bob.address}), 'transferring-from')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      // NFT properties
+    // NFT properties
 
-      const txSetTokenProperties = api.tx.unique.setTokenProperties(uniqueCollectionId, rmrkNftId, [{key: 'a', value: '2'}]);
-      await expect(executeTransaction(api, alice, txSetTokenProperties), 'setting token properties')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.setTokenProperties(alice, uniqueCollectionId, rmrkNftId, [{key: 'a', value: '2'}]), 'setting token properties')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txDeleteTokenProperties = api.tx.unique.deleteTokenProperties(uniqueCollectionId, rmrkNftId, ['a']);
-      await expect(executeTransaction(api, alice, txDeleteTokenProperties), 'deleting token properties')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
-    });
+    await expect(helper.nft.deleteTokenProperties(alice, uniqueCollectionId, rmrkNftId, ['a']))
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
   });
 
-  itRmrk('[Negative] Forbids Unique collection operations with an external collection', async () => {
-    await usingApi(async api => {
-      const txDestroyCollection = api.tx.unique.destroyCollection(uniqueCollectionId);
-      await expect(executeTransaction(api, alice, txDestroyCollection), 'destroying collection')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+  itSub.ifWithPallets('[Negative] Forbids Unique collection operations with an external collection', [Pallets.RmrkCore], async ({helper}) => {
+    await expect(helper.nft.burn(alice, uniqueCollectionId), 'destroying collection')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      // Allow list
+    // Allow list
 
-      const txAddAllowList = api.tx.unique.addToAllowList(uniqueCollectionId, normalizeAccountId(bob));
-      await expect(executeTransaction(api, alice, txAddAllowList), 'adding to allow list')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.addToAllowList(alice, uniqueCollectionId, {Substrate: bob.address}), 'adding to allow list')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txRemoveAllowList = api.tx.unique.removeFromAllowList(uniqueCollectionId, normalizeAccountId(bob));
-      await expect(executeTransaction(api, alice, txRemoveAllowList), 'removing from allowlist')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.removeFromAllowList(alice, uniqueCollectionId, {Substrate: bob.address}), 'removing from allowlist')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      // Owner / Admin / Sponsor
+    // Owner / Admin / Sponsor
 
-      const txChangeOwner = api.tx.unique.changeCollectionOwner(uniqueCollectionId, bob.address);
-      await expect(executeTransaction(api, alice, txChangeOwner), 'changing owner')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.changeOwner(alice, uniqueCollectionId, bob.address), 'changing owner')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txAddAdmin = api.tx.unique.addCollectionAdmin(uniqueCollectionId, normalizeAccountId(bob));
-      await expect(executeTransaction(api, alice, txAddAdmin), 'adding admin')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.addAdmin(alice, uniqueCollectionId, {Substrate: bob.address}), 'adding admin')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txRemoveAdmin = api.tx.unique.removeCollectionAdmin(uniqueCollectionId, normalizeAccountId(bob));
-      await expect(executeTransaction(api, alice, txRemoveAdmin), 'removing admin')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.removeAdmin(alice, uniqueCollectionId, {Substrate: bob.address}), 'removing admin')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txAddCollectionSponsor = api.tx.unique.setCollectionSponsor(uniqueCollectionId, bob.address);
-      await expect(executeTransaction(api, alice, txAddCollectionSponsor), 'setting sponsor')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.setSponsor(alice, uniqueCollectionId, bob.address), 'setting sponsor')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txConfirmCollectionSponsor = api.tx.unique.confirmSponsorship(uniqueCollectionId);
-      await expect(executeTransaction(api, alice, txConfirmCollectionSponsor), 'confirming sponsor')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.confirmSponsorship(alice, uniqueCollectionId), 'confirming sponsor')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txRemoveCollectionSponsor = api.tx.unique.removeCollectionSponsor(uniqueCollectionId);
-      await expect(executeTransaction(api, alice, txRemoveCollectionSponsor), 'removing sponsor')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
-      
-      // Limits / permissions / transfers
+    await expect(helper.nft.removeSponsor(alice, uniqueCollectionId), 'removing sponsor')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    
+    // Limits / permissions / transfers
 
-      const txSetTransfers = api.tx.unique.setTransfersEnabledFlag(uniqueCollectionId, true);
-      await expect(executeTransaction(api, alice, txSetTransfers), 'setting transfers enabled flag')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    const txSetTransfers = helper.getApi().tx.unique.setTransfersEnabledFlag(uniqueCollectionId, true);
+    await expect(executeTransaction(helper.getApi(), alice, txSetTransfers), 'setting transfers enabled flag')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txSetLimits = api.tx.unique.setCollectionLimits(uniqueCollectionId, {transfersEnabled: false});
-      await expect(executeTransaction(api, alice, txSetLimits), 'setting collection limits')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
+    await expect(helper.nft.setLimits(alice, uniqueCollectionId, {transfersEnabled: false}), 'setting collection limits')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
 
-      const txSetPermissions = api.tx.unique.setCollectionPermissions(uniqueCollectionId, {access: 'AllowList'});
-      await expect(executeTransaction(api, alice, txSetPermissions), 'setting collection permissions')
-        .to.be.rejectedWith(/common\.CollectionIsExternal/);
-    });
+    await expect(helper.nft.setPermissions(alice, uniqueCollectionId, {access: 'AllowList'}), 'setting collection permissions')
+      .to.be.rejectedWith(/common\.CollectionIsExternal/);
   });
 });
 
 describe('Negative Integration Test: Internal Collections, External Ops', async () => {
   let collectionId: number;
   let nftId: number;
-
-  const itRmrk = (await isUnique() ? it : it.skip);
 
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      alice = await privateKey('//Alice');
+      bob = await privateKey('//Bob');
 
-      collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      nftId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+      const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'iceo'});
+      collectionId = collection.collectionId;
+      nftId = (await collection.mintToken(alice)).tokenId;
     });
   });
 
-  itRmrk('[Negative] Forbids RMRK operations with the internal collection and NFT (due to the lack of mapping)', async () => {
-    await usingApi(async api => {
-      const txChangeOwner = api.tx.rmrkCore.changeCollectionIssuer(collectionId, bob.address);
-      await expect(executeTransaction(api, alice, txChangeOwner), 'changing collection issuer')
-        .to.be.rejectedWith(/rmrkCore\.CollectionUnknown/);
+  itSub.ifWithPallets('[Negative] Forbids RMRK operations with the internal collection and NFT (due to the lack of mapping)', [Pallets.RmrkCore], async ({helper}) => {
+    const api = helper.getApi();
+
+    const txChangeOwner = api.tx.rmrkCore.changeCollectionIssuer(collectionId, bob.address);
+    await expect(executeTransaction(api, alice, txChangeOwner), 'changing collection issuer')
+      .to.be.rejectedWith(/rmrkCore\.CollectionUnknown/);
 
-      const maxBurns = 10;
-      const txBurnItem = api.tx.rmrkCore.burnNft(collectionId, nftId, maxBurns);
-      await expect(executeTransaction(api, alice, txBurnItem), 'burning NFT').to.be.rejectedWith(/rmrkCore\.CollectionUnknown/);
-    });
+    const maxBurns = 10;
+    const txBurnItem = api.tx.rmrkCore.burnNft(collectionId, nftId, maxBurns);
+    await expect(executeTransaction(api, alice, txBurnItem), 'burning NFT').to.be.rejectedWith(/rmrkCore\.CollectionUnknown/);
   });
 });
modifiedtests/src/rmrk/sendNft.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/sendNft.seqtest.ts
+++ b/tests/src/rmrk/sendNft.seqtest.ts
@@ -2,8 +2,7 @@
 import {getApiConnection} from '../substrate/substrate-api';
 import {createCollection, mintNft, sendNft} from './util/tx';
 import {NftIdTuple} from './util/fetch';
-import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
+import {isNftChildOfAnother, expectTxFailure, requirePallets, Pallets} from './util/helpers';
 
 describe('integration test: send NFT', () => {
   let api: any;
@@ -252,5 +251,5 @@
     await expectTxFailure(/rmrkCore\.NoPermission/, tx);
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/setCollectionProperty.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/setCollectionProperty.seqtest.ts
+++ b/tests/src/rmrk/setCollectionProperty.seqtest.ts
@@ -1,6 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {createCollection, setPropertyCollection} from './util/tx';
 
 describe('integration test: set collection property', () => {
@@ -63,7 +62,5 @@
     });
   });
 
-  after(() => {
-    api.disconnect();
-  });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/setEquippableList.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/setEquippableList.seqtest.ts
+++ b/tests/src/rmrk/setEquippableList.seqtest.ts
@@ -1,6 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {createCollection, createBase, setEquippableList} from './util/tx';
 
 describe("integration test: set slot's Equippable List", () => {
@@ -111,5 +110,5 @@
     await expectTxFailure(/rmrkEquip\.PartDoesntExist/, tx);
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/setNftProperty.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/setNftProperty.seqtest.ts
+++ b/tests/src/rmrk/setNftProperty.seqtest.ts
@@ -1,7 +1,6 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
 import {NftIdTuple} from './util/fetch';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {createCollection, mintNft, sendNft, setNftProperty} from './util/tx';
 
 describe('integration test: set NFT property', () => {
@@ -85,5 +84,5 @@
     await expectTxFailure(/rmrkCore\.NoPermission/, tx);
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/setResourcePriorities.seqtest.tsdiffbeforeafterboth
--- a/tests/src/rmrk/setResourcePriorities.seqtest.ts
+++ b/tests/src/rmrk/setResourcePriorities.seqtest.ts
@@ -1,6 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {requirePallets, Pallets} from '../deprecated-helpers/helpers';
-import {expectTxFailure} from './util/helpers';
+import {expectTxFailure, requirePallets, Pallets} from './util/helpers';
 import {mintNft, createCollection, setResourcePriorities} from './util/tx';
 
 describe('integration test: set NFT resource priorities', () => {
@@ -53,5 +52,5 @@
     await expectTxFailure(/rmrkCore\.NoAvailableNftId/, tx);
   });
 
-  after(() => { api.disconnect(); });
+  after(async() => { await api.disconnect(); });
 });
modifiedtests/src/rmrk/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/rmrk/util/helpers.ts
+++ b/tests/src/rmrk/util/helpers.ts
@@ -10,6 +10,8 @@
 import {NftIdTuple, getChildren, getOwnedNfts, getCollectionProperties, getNftProperties, getResources} from './fetch';
 import chaiAsPromised from 'chai-as-promised';
 import chai from 'chai';
+import {getApiConnection} from '../../substrate/substrate-api';
+import {Context} from 'mocha';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -19,6 +21,46 @@
     successData: T | null;
 }
 
+export enum Pallets {
+  Inflation = 'inflation',
+  RmrkCore = 'rmrkcore',
+  RmrkEquip = 'rmrkequip',
+  ReFungible = 'refungible',
+  Fungible = 'fungible',
+  NFT = 'nonfungible',
+  Scheduler = 'scheduler',
+  AppPromotion = 'apppromotion',
+}
+
+let modulesNames: any;
+export function getModuleNames(api: ApiPromise): string[] {
+  if (typeof modulesNames === 'undefined')
+    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());
+  return modulesNames;
+}
+
+export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {
+  const api = await getApiConnection();
+  const pallets = getModuleNames(api);
+  await api.disconnect();
+
+  return requiredPallets.filter(p => !pallets.includes(p));
+}
+
+export async function requirePallets(mocha: Context, requiredPallets: string[]) {
+  const missingPallets = await missingRequiredPallets(requiredPallets);
+
+  if (missingPallets.length > 0) {
+    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;
+    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;
+    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;
+
+    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);
+
+    mocha.skip();
+  }
+}
+
 export function makeNftOwner(api: ApiPromise, owner: string | NftIdTuple): NftOwner {
   const isNftSending = (typeof owner !== 'string');
 
modifiedtests/src/util/index.tsdiffbeforeafterboth
--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -8,8 +8,9 @@
 import chaiAsPromised from 'chai-as-promised';
 import {Context} from 'mocha';
 import config from '../config';
-import '../interfaces/augment-api-events';
-import {DevUniqueHelper, SilentLogger, SilentConsole} from './playgrounds/unique.dev';
+import {ChainHelperBase} from './playgrounds/unique';
+import {ILogger} from './playgrounds/types';
+import {DevUniqueHelper, SilentLogger, SilentConsole, DevMoonbeamHelper, DevMoonriverHelper, DevAcalaHelper, DevKaruraHelper, DevRelayHelper, DevWestmintHelper} from './playgrounds/unique.dev';
 
 chai.use(chaiAsPromised);
 export const expect = chai.expect;
@@ -22,11 +23,11 @@
   return `//Alice+${getTestHash(filename)}`;
 };
 
-export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string | {filename: string, ignoreFundsPresence?: boolean}) => Promise<IKeyringPair>) => Promise<void>, url: string = config.substrateUrl) => {
+async function usingPlaygroundsGeneral<T extends ChainHelperBase>(helperType: new(logger: ILogger) => T, url: string, code: (helper: T, privateKey: (seed: string | {filename: string, ignoreFundsPresence?: boolean}) => Promise<IKeyringPair>) => Promise<void>) {
   const silentConsole = new SilentConsole();
   silentConsole.enable();
 
-  const helper = new DevUniqueHelper(new SilentLogger());
+  const helper = new helperType(new SilentLogger());
 
   try {
     await helper.connect(url);
@@ -38,7 +39,8 @@
       else {
         const actualSeed = getTestSeed(seed.filename);
         let account = helper.util.fromSeed(actualSeed, ss58Format);
-        if (!seed.ignoreFundsPresence && await helper.balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND) {
+        // here's to hoping that no 
+        if (!seed.ignoreFundsPresence && ((helper as any)['balance'] == undefined || await (helper as any).balance.getSubstrate(account.address) < MINIMUM_DONOR_FUND)) {
           console.warn(`${path.basename(seed.filename)}: Not enough funds present on the filename account. Using the default one as the donor instead.`);
           account = helper.util.fromSeed('//Alice', ss58Format);
         }
@@ -51,8 +53,36 @@
     await helper.disconnect();
     silentConsole.disable();
   }
+}
+
+export const usingPlaygrounds = (code: (helper: DevUniqueHelper, privateKey: (seed: string | {filename: string, ignoreFundsPresence?: boolean}) => Promise<IKeyringPair>) => Promise<void>, url: string = config.substrateUrl) => {
+  return usingPlaygroundsGeneral<DevUniqueHelper>(DevUniqueHelper, url, code);
+};
+
+export const usingWestmintPlaygrounds = async (url: string, code: (helper: DevWestmintHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
+  return usingPlaygroundsGeneral<DevWestmintHelper>(DevWestmintHelper, url, code);
+};
+
+export const usingRelayPlaygrounds = async (url: string, code: (helper: DevRelayHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
+  return usingPlaygroundsGeneral<DevRelayHelper>(DevRelayHelper, url, code);
+};
+
+export const usingAcalaPlaygrounds = async (url: string, code: (helper: DevAcalaHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
+  return usingPlaygroundsGeneral<DevAcalaHelper>(DevAcalaHelper, url, code);
+};
+
+export const usingKaruraPlaygrounds = async (url: string, code: (helper: DevKaruraHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
+  return usingPlaygroundsGeneral<DevKaruraHelper>(DevAcalaHelper, url, code);
+};
+
+export const usingMoonbeamPlaygrounds = async (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
+  return usingPlaygroundsGeneral<DevMoonbeamHelper>(DevMoonbeamHelper, url, code);
 };
 
+export const usingMoonriverPlaygrounds = async (url: string, code: (helper: DevMoonbeamHelper, privateKey: (seed: string) => Promise<IKeyringPair>) => Promise<void>) => {
+  return usingPlaygroundsGeneral<DevMoonriverHelper>(DevMoonriverHelper, url, code);
+};
+
 export const MINIMUM_DONOR_FUND = 100_000n;
 export const DONOR_FUNDING = 1_000_000n;
 
@@ -98,3 +128,11 @@
 itSubIfWithPallet.only = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {only: true});
 itSubIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});
 itSub.ifWithPallets = itSubIfWithPallet;
+
+export async function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {
+  (process.env.RUN_XCM_TESTS && !opts.skip
+    ? describe
+    : describe.skip)(title, fn);
+}
+
+describeXCM.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeXCM(name, fn, {skip: true});
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -172,8 +172,48 @@
   },
 }
 
+export interface IForeignAssetMetadata {
+  name?: number | Uint8Array,
+  symbol?: string,
+  decimals?: number,
+  minimalBalance?: bigint,
+}
+
+export interface MoonbeamAssetInfo {
+  location: any,
+  metadata: {
+    name: string,
+    symbol: string,
+    decimals: number,
+    isFrozen: boolean,
+    minimalBalance: bigint,
+  },
+  existentialDeposit: bigint,
+  isSufficient: boolean,
+  unitsPerSecond: bigint,
+  numAssetsWeightHint: number,
+}
+
+export interface AcalaAssetMetadata {
+  name: string,
+  symbol: string,
+  decimals: number,
+  minimalBalance: bigint,
+}
+
+export interface DemocracyStandardAccountVote {
+  balance: bigint,
+  vote: {
+    aye: boolean,
+    conviction: number,
+  },
+}
+
 export type TSubstrateAccount = string;
 export type TEthereumAccount = string;
 export type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';
 export type TUniqueNetworks = 'opal' | 'quartz' | 'unique';
+export type TSiblingNetworkds = 'moonbeam' | 'moonriver' | 'acala' | 'karura' | 'westmint';
+export type TRelayNetworks = 'rococo' | 'westend';
+export type TNetworks = TUniqueNetworks | TSiblingNetworkds | TRelayNetworks;
 export type TSigner = IKeyringPair; // | 'string'
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -3,11 +3,13 @@
 
 import {stringToU8a} from '@polkadot/util';
 import {encodeAddress, mnemonicGenerate} from '@polkadot/util-crypto';
-import {UniqueHelper} from './unique';
-import {ApiPromise, WsProvider} from '@polkadot/api';
+import {UniqueHelper, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper, WestmintHelper} from './unique';
+import {ApiPromise, Keyring, WsProvider} from '@polkadot/api';
 import * as defs from '../../interfaces/definitions';
 import {IKeyringPair} from '@polkadot/types/types';
+import {EventRecord} from '@polkadot/types/interfaces';
 import {ICrossAccountId} from './types';
+import {FrameSystemEventRecord} from '@polkadot/types/lookup';
 
 export class SilentLogger {
   log(_msg: any, _level: any): void { }
@@ -54,7 +56,6 @@
   }
 }
 
-
 export class DevUniqueHelper extends UniqueHelper {
   /**
    * Arrange methods for tests
@@ -109,6 +110,47 @@
   }
 }
 
+export class DevRelayHelper extends RelayHelper {}
+
+export class DevWestmintHelper extends WestmintHelper {
+  wait: WaitGroup;
+
+  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
+    options.helperBase = options.helperBase ?? DevWestmintHelper;
+
+    super(logger, options);
+    this.wait = new WaitGroup(this);
+  }
+}
+
+export class DevMoonbeamHelper extends MoonbeamHelper {
+  account: MoonbeamAccountGroup;
+  wait: WaitGroup;
+
+  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
+    options.helperBase = options.helperBase ?? DevMoonbeamHelper;
+
+    super(logger, options);
+    this.account = new MoonbeamAccountGroup(this);
+    this.wait = new WaitGroup(this);
+  }
+}
+
+export class DevMoonriverHelper extends DevMoonbeamHelper {}
+
+export class DevAcalaHelper extends AcalaHelper {
+  wait: WaitGroup;
+
+  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
+    options.helperBase = options.helperBase ?? DevAcalaHelper;
+
+    super(logger, options);
+    this.wait = new WaitGroup(this);
+  }
+}
+
+export class DevKaruraHelper extends DevAcalaHelper {}
+
 class ArrangeGroup {
   helper: DevUniqueHelper;
 
@@ -252,10 +294,48 @@
   }
 }
 
+class MoonbeamAccountGroup {
+  helper: MoonbeamHelper;
+
+  keyring: Keyring;
+  _alithAccount: IKeyringPair;
+  _baltatharAccount: IKeyringPair;
+  _dorothyAccount: IKeyringPair;
+
+  constructor(helper: MoonbeamHelper) {
+    this.helper = helper;
+
+    this.keyring = new Keyring({type: 'ethereum'});
+    const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';
+    const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';
+    const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';
+
+    this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');
+    this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');
+    this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');
+  }
+
+  alithAccount() {
+    return this._alithAccount;
+  }
+
+  baltatharAccount() {
+    return this._baltatharAccount;
+  }
+
+  dorothyAccount() {
+    return this._dorothyAccount;
+  }
+
+  create() {
+    return this.keyring.addFromUri(mnemonicGenerate());
+  }
+}
+
 class WaitGroup {
-  helper: DevUniqueHelper;
+  helper: ChainHelperBase;
 
-  constructor(helper: DevUniqueHelper) {
+  constructor(helper: ChainHelperBase) {
     this.helper = helper;
   }
 
@@ -303,6 +383,40 @@
       });
     });
   }
+
+  async event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {
+    // eslint-disable-next-line no-async-promise-executor
+    const promise = new Promise<EventRecord | null>(async (resolve) => {
+      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {
+        const blockNumber = header.number.toHuman();
+        const blockHash = header.hash;
+        const eventIdStr = `${eventSection}.${eventMethod}`;
+        const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;
+  
+        this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);
+  
+        const apiAt = await this.helper.getApi().at(blockHash);
+        const eventRecords = (await apiAt.query.system.events()) as any;
+  
+        const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {
+          return r.event.section == eventSection && r.event.method == eventMethod;
+        });
+  
+        if (neededEvent) {
+          unsubscribe();
+          resolve(neededEvent);
+        } else if (maxBlocksToWait > 0) {
+          maxBlocksToWait--;
+        } else {
+          this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);
+  
+          unsubscribe();
+          resolve(null);
+        }
+      });
+    });
+    return promise;
+  }
 }
 
 class AdminGroup {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15  Substrate?: TSubstrateAccount;16  Ethereum?: TEthereumAccount;1718  constructor(account: ICrossAccountId) {19    if (account.Substrate) this.Substrate = account.Substrate;20    if (account.Ethereum) this.Ethereum = account.Ethereum;21  }2223  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24    switch (domain) {25      case 'Substrate': return new CrossAccountId({Substrate: account.address});26      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27    }28  }2930  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32  }3334  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35    return encodeAddress(decodeAddress(address), ss58Format);36  }3738  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40  }41  42  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44    return this;45  }4647  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49  }5051  toEthereum(): CrossAccountId {52    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53    return this;54  }5556  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57    return evmToAddress(address, ss58Format);58  }5960  toSubstrate(ss58Format?: number): CrossAccountId {61    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62    return this;63  }64  65  toLowerCase(): CrossAccountId {66    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68    return this;69  }70}7172const nesting = {73  toChecksumAddress(address: string): string {74    if (typeof address === 'undefined') return '';7576    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778    address = address.toLowerCase().replace(/^0x/i,'');79    const addressHash = keccakAsHex(address).replace(/^0x/i,'');80    const checksumAddress = ['0x'];8182    for (let i = 0; i < address.length; i++) {83      // If ith character is 8 to f then make it uppercase84      if (parseInt(addressHash[i], 16) > 7) {85        checksumAddress.push(address[i].toUpperCase());86      } else {87        checksumAddress.push(address[i]);88      }89    }90    return checksumAddress.join('');91  },92  tokenIdToAddress(collectionId: number, tokenId: number) {93    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);94  },95};9697class UniqueUtil {98  static transactionStatus = {99    NOT_READY: 'NotReady',100    FAIL: 'Fail',101    SUCCESS: 'Success',102  };103104  static chainLogType = {105    EXTRINSIC: 'extrinsic',106    RPC: 'rpc',107  };108109  static getTokenAccount(token: IToken): CrossAccountId {110    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111  }112113  static getTokenAddress(token: IToken): string {114    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115  }116117  static getDefaultLogger(): ILogger {118    return {119      log(msg: any, level = 'INFO') {120        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121      },122      level: {123        ERROR: 'ERROR',124        WARNING: 'WARNING',125        INFO: 'INFO',126      },127    };128  }129130  static vec2str(arr: string[] | number[]) {131    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132  }133134  static str2vec(string: string) {135    if (typeof string !== 'string') return string;136    return Array.from(string).map(x => x.charCodeAt(0));137  }138139  static fromSeed(seed: string, ss58Format = 42) {140    const keyring = new Keyring({type: 'sr25519', ss58Format});141    return keyring.addFromUri(seed);142  }143144  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145    if (creationResult.status !== this.transactionStatus.SUCCESS) {146      throw Error('Unable to create collection!');147    }148149    let collectionId = null;150    creationResult.result.events.forEach(({event: {data, method, section}}) => {151      if ((section === 'common') && (method === 'CollectionCreated')) {152        collectionId = parseInt(data[0].toString(), 10);153      }154    });155156    if (collectionId === null) {157      throw Error('No CollectionCreated event was found!');158    }159160    return collectionId;161  }162163  static extractTokensFromCreationResult(creationResult: ITransactionResult): {164    success: boolean, 165    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166  } {167    if (creationResult.status !== this.transactionStatus.SUCCESS) {168      throw Error('Unable to create tokens!');169    }170    let success = false;171    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172    creationResult.result.events.forEach(({event: {data, method, section}}) => {173      if (method === 'ExtrinsicSuccess') {174        success = true;175      } else if ((section === 'common') && (method === 'ItemCreated')) {176        tokens.push({177          collectionId: parseInt(data[0].toString(), 10),178          tokenId: parseInt(data[1].toString(), 10),179          owner: data[2].toHuman(),180          amount: data[3].toBigInt(),181        });182      }183    });184    return {success, tokens};185  }186187  static extractTokensFromBurnResult(burnResult: ITransactionResult): {188    success: boolean, 189    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190  } {191    if (burnResult.status !== this.transactionStatus.SUCCESS) {192      throw Error('Unable to burn tokens!');193    }194    let success = false;195    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196    burnResult.result.events.forEach(({event: {data, method, section}}) => {197      if (method === 'ExtrinsicSuccess') {198        success = true;199      } else if ((section === 'common') && (method === 'ItemDestroyed')) {200        tokens.push({201          collectionId: parseInt(data[0].toString(), 10),202          tokenId: parseInt(data[1].toString(), 10),203          owner: data[2].toHuman(),204          amount: data[3].toBigInt(),205        });206      }207    });208    return {success, tokens};209  }210211  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212    let eventId = null;213    events.forEach(({event: {data, method, section}}) => {214      if ((section === expectedSection) && (method === expectedMethod)) {215        eventId = parseInt(data[0].toString(), 10);216      }217    });218219    if (eventId === null) {220      throw Error(`No ${expectedMethod} event was found!`);221    }222    return eventId === collectionId;223  }224225  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226    const normalizeAddress = (address: string | ICrossAccountId) => {227      if(typeof address === 'string') return address;228      const obj = {} as any;229      Object.keys(address).forEach(k => {230        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231      });232      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234      return address;235    };236    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237    events.forEach(({event: {data, method, section}}) => {238      if ((section === 'common') && (method === 'Transfer')) {239        const hData = (data as any).toJSON();240        transfer = {241          collectionId: hData[0],242          tokenId: hData[1],243          from: normalizeAddress(hData[2]),244          to: normalizeAddress(hData[3]),245          amount: BigInt(hData[4]),246        };247      }248    });249    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252    isSuccess = isSuccess && amount === transfer.amount;253    return isSuccess;254  }255}256257class UniqueEventHelper {258  private static extractIndex(index: any): [number, number] | string {259    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260    return index.toJSON();261  }262263  private static extractSub(data: any, subTypes: any): {[key: string]: any} {264    let obj: any = {};265    let index = 0;266267    if (data.entries) {268      for(const [key, value] of data.entries()) {269        obj[key] = this.extractData(value, subTypes[index]);270        index++;271      }272    } else obj = data.toJSON();273274    return obj;275  }276  277  private static extractData(data: any, type: any): any {278    if(!type) return data.toHuman();279    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();280    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();281    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);282    return data.toHuman();283  }284285  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {286    const parsedEvents: IEvent[] = [];287288    events.forEach((record) => {289      const {event, phase} = record;290      const types = event.typeDef;291292      const eventData: IEvent = {293        section: event.section.toString(),294        method: event.method.toString(),295        index: this.extractIndex(event.index),296        data: [],297        phase: phase.toJSON(),298      };299300      event.data.forEach((val: any, index: number) => {301        eventData.data.push(this.extractData(val, types[index]));302      });303304      parsedEvents.push(eventData);305    });306307    return parsedEvents;308  }309}310311class ChainHelperBase {312  transactionStatus = UniqueUtil.transactionStatus;313  chainLogType = UniqueUtil.chainLogType;314  util: typeof UniqueUtil;315  eventHelper: typeof UniqueEventHelper;316  logger: ILogger;317  api: ApiPromise | null;318  forcedNetwork: TUniqueNetworks | null;319  network: TUniqueNetworks | null;320  chainLog: IUniqueHelperLog[];321  children: ChainHelperBase[];322323  constructor(logger?: ILogger) {324    this.util = UniqueUtil;325    this.eventHelper = UniqueEventHelper;326    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();327    this.logger = logger;328    this.api = null;329    this.forcedNetwork = null;330    this.network = null;331    this.chainLog = [];332    this.children = [];333  }334335  getApi(): ApiPromise {336    if(this.api === null) throw Error('API not initialized');337    return this.api;338  }339340  clearChainLog(): void {341    this.chainLog = [];342  }343344  forceNetwork(value: TUniqueNetworks): void {345    this.forcedNetwork = value;346  }347348  async connect(wsEndpoint: string, listeners?: IApiListeners) {349    if (this.api !== null) throw Error('Already connected');350    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);351    this.api = api;352    this.network = network;353  }354355  async disconnect() {356    for (const child of this.children) {357      child.clearApi();358    }359360    if (this.api === null) return;361    await this.api.disconnect();362    this.clearApi();363  }364365  clearApi() {366    this.api = null;367    this.network = null;368  }369370  static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {371    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;372    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;373    return 'opal';374  }375376  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {377    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});378    await api.isReady;379380    const network = await this.detectNetwork(api);381382    await api.disconnect();383384    return network;385  }386387  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{388    api: ApiPromise;389    network: TUniqueNetworks;390  }> {391    if(typeof network === 'undefined' || network === null) network = 'opal';392    const supportedRPC = {393      opal: {394        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,395      },396      quartz: {397        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,398      },399      unique: {400        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,401      },402    };403    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);404    const rpc = supportedRPC[network];405406    // TODO: investigate how to replace rpc in runtime407    // api._rpcCore.addUserInterfaces(rpc);408409    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});410411    await api.isReadyOrError;412413    if (typeof listeners === 'undefined') listeners = {};414    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {415      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;416      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);417    }418419    return {api, network};420  }421422  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {423    const {events, status} = data;424    if (status.isReady) {425      return this.transactionStatus.NOT_READY;426    }427    if (status.isBroadcast) {428      return this.transactionStatus.NOT_READY;429    }430    if (status.isInBlock || status.isFinalized) {431      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');432      if (errors.length > 0) {433        return this.transactionStatus.FAIL;434      }435      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {436        return this.transactionStatus.SUCCESS;437      }438    }439440    return this.transactionStatus.FAIL;441  }442443  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {444    const sign = (callback: any) => {445      if(options !== null) return transaction.signAndSend(sender, options, callback);446      return transaction.signAndSend(sender, callback);447    };448    // eslint-disable-next-line no-async-promise-executor449    return new Promise(async (resolve, reject) => {450      try {451        const unsub = await sign((result: any) => {452          const status = this.getTransactionStatus(result);453454          if (status === this.transactionStatus.SUCCESS) {455            this.logger.log(`${label} successful`);456            unsub();457            resolve({result, status});458          } else if (status === this.transactionStatus.FAIL) {459            let moduleError = null;460461            if (result.hasOwnProperty('dispatchError')) {462              const dispatchError = result['dispatchError'];463464              if (dispatchError) {465                if (dispatchError.isModule) {466                  const modErr = dispatchError.asModule;467                  const errorMeta = dispatchError.registry.findMetaError(modErr);468469                  moduleError = `${errorMeta.section}.${errorMeta.name}`;470                } else {471                  moduleError = dispatchError.toHuman();472                }473              } else {474                this.logger.log(result, this.logger.level.ERROR);475              }476            }477478            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);479            unsub();480            reject({status, moduleError, result});481          }482        });483      } catch (e) {484        this.logger.log(e, this.logger.level.ERROR);485        reject(e);486      }487    });488  }489490  constructApiCall(apiCall: string, params: any[]) {491    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);492    let call = this.getApi() as any;493    for(const part of apiCall.slice(4).split('.')) {494      call = call[part];495    }496    return call(...params);497  }498499  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {500    if(this.api === null) throw Error('API not initialized');501    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);502503    const startTime = (new Date()).getTime();504    let result: ITransactionResult;505    let events: IEvent[] = [];506    try {507      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;508      events = this.eventHelper.extractEvents(result.result.events);509    }510    catch(e) {511      if(!(e as object).hasOwnProperty('status')) throw e;512      result = e as ITransactionResult;513    }514515    const endTime = (new Date()).getTime();516517    const log = {518      executedAt: endTime,519      executionTime: endTime - startTime,520      type: this.chainLogType.EXTRINSIC,521      status: result.status,522      call: extrinsic,523      signer: this.getSignerAddress(sender),524      params,525    } as IUniqueHelperLog;526527    if(result.status !== this.transactionStatus.SUCCESS) {528      if (result.moduleError) log.moduleError = result.moduleError;529      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;530    }531    if(events.length > 0) log.events = events;532533    this.chainLog.push(log);534535    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {536      if (result.moduleError) throw Error(`${result.moduleError}`);537      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));538    }539    return result;540  }541542  async callRpc(rpc: string, params?: any[]) {543    if(typeof params === 'undefined') params = [];544    if(this.api === null) throw Error('API not initialized');545    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);546547    const startTime = (new Date()).getTime();548    let result;549    let error = null;550    const log = {551      type: this.chainLogType.RPC,552      call: rpc,553      params,554    } as IUniqueHelperLog;555556    try {557      result = await this.constructApiCall(rpc, params);558    }559    catch(e) {560      error = e;561    }562563    const endTime = (new Date()).getTime();564565    log.executedAt = endTime;566    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';567    log.executionTime = endTime - startTime;568569    this.chainLog.push(log);570571    if(error !== null) throw error;572573    return result;574  }575576  getSignerAddress(signer: IKeyringPair | string): string {577    if(typeof signer === 'string') return signer;578    return signer.address;579  }580581  fetchAllPalletNames(): string[] {582    if(this.api === null) throw Error('API not initialized');583    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());584  }585586  fetchMissingPalletNames(requiredPallets: string[]): string[] {587    const palletNames = this.fetchAllPalletNames();588    return requiredPallets.filter(p => !palletNames.includes(p));589  }590}591592593class HelperGroup {594  helper: UniqueHelper;595596  constructor(uniqueHelper: UniqueHelper) {597    this.helper = uniqueHelper;598  }599}600601602class CollectionGroup extends HelperGroup {603  /**604 * Get number of blocks when sponsored transaction is available.605 *606 * @param collectionId ID of collection607 * @param tokenId ID of token608 * @param addressObj address for which the sponsorship is checked609 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});610 * @returns number of blocks or null if sponsorship hasn't been set611 */612  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {613    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();614  }615616  /**617   * Get the number of created collections.618   *619   * @returns number of created collections620   */621  async getTotalCount(): Promise<number> {622    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();623  }624625  /**626   * Get information about the collection with additional data,627   * including the number of tokens it contains, its administrators,628   * the normalized address of the collection's owner, and decoded name and description.629   *630   * @param collectionId ID of collection631   * @example await getData(2)632   * @returns collection information object633   */634  async getData(collectionId: number): Promise<{635    id: number;636    name: string;637    description: string;638    tokensCount: number;639    admins: CrossAccountId[];640    normalizedOwner: TSubstrateAccount;641    raw: any642  } | null> {643    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);644    const humanCollection = collection.toHuman(), collectionData = {645      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],646      raw: humanCollection,647    } as any, jsonCollection = collection.toJSON();648    if (humanCollection === null) return null;649    collectionData.raw.limits = jsonCollection.limits;650    collectionData.raw.permissions = jsonCollection.permissions;651    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);652    for (const key of ['name', 'description']) {653      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);654    }655656    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))657      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)658      : 0;659    collectionData.admins = await this.getAdmins(collectionId);660661    return collectionData;662  }663664  /**665   * Get the addresses of the collection's administrators, optionally normalized.666   *667   * @param collectionId ID of collection668   * @param normalize whether to normalize the addresses to the default ss58 format669   * @example await getAdmins(1)670   * @returns array of administrators671   */672  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {673    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();674675    return normalize676      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())677      : admins;678  }679680  /**681   * Get the addresses added to the collection allow-list, optionally normalized.682   * @param collectionId ID of collection683   * @param normalize whether to normalize the addresses to the default ss58 format684   * @example await getAllowList(1)685   * @returns array of allow-listed addresses686   */687  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {688    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();689    return normalize690      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())691      : allowListed;692  }693694  /**695   * Get the effective limits of the collection instead of null for default values696   *697   * @param collectionId ID of collection698   * @example await getEffectiveLimits(2)699   * @returns object of collection limits700   */701  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {702    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();703  }704705  /**706   * Burns the collection if the signer has sufficient permissions and collection is empty.707   *708   * @param signer keyring of signer709   * @param collectionId ID of collection710   * @example await helper.collection.burn(aliceKeyring, 3);711   * @returns ```true``` if extrinsic success, otherwise ```false```712   */713  async burn(signer: TSigner, collectionId: number): Promise<boolean> {714    const result = await this.helper.executeExtrinsic(715      signer,716      'api.tx.unique.destroyCollection', [collectionId],717      true,718    );719720    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');721  }722723  /**724   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.725   *726   * @param signer keyring of signer727   * @param collectionId ID of collection728   * @param sponsorAddress Sponsor substrate address729   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")730   * @returns ```true``` if extrinsic success, otherwise ```false```731   */732  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {733    const result = await this.helper.executeExtrinsic(734      signer,735      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],736      true,737    );738739    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');740  }741742  /**743   * Confirms consent to sponsor the collection on behalf of the signer.744   *745   * @param signer keyring of signer746   * @param collectionId ID of collection747   * @example confirmSponsorship(aliceKeyring, 10)748   * @returns ```true``` if extrinsic success, otherwise ```false```749   */750  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {751    const result = await this.helper.executeExtrinsic(752      signer,753      'api.tx.unique.confirmSponsorship', [collectionId],754      true,755    );756757    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');758  }759760  /**761   * Removes the sponsor of a collection, regardless if it consented or not.762   *763   * @param signer keyring of signer764   * @param collectionId ID of collection765   * @example removeSponsor(aliceKeyring, 10)766   * @returns ```true``` if extrinsic success, otherwise ```false```767   */768  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {769    const result = await this.helper.executeExtrinsic(770      signer,771      'api.tx.unique.removeCollectionSponsor', [collectionId],772      true,773    );774775    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');776  }777778  /**779   * Sets the limits of the collection. At least one limit must be specified for a correct call.780   *781   * @param signer keyring of signer782   * @param collectionId ID of collection783   * @param limits collection limits object784   * @example785   * await setLimits(786   *   aliceKeyring,787   *   10,788   *   {789   *     sponsorTransferTimeout: 0,790   *     ownerCanDestroy: false791   *   }792   * )793   * @returns ```true``` if extrinsic success, otherwise ```false```794   */795  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {796    const result = await this.helper.executeExtrinsic(797      signer,798      'api.tx.unique.setCollectionLimits', [collectionId, limits],799      true,800    );801802    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');803  }804805  /**806   * Changes the owner of the collection to the new Substrate address.807   *808   * @param signer keyring of signer809   * @param collectionId ID of collection810   * @param ownerAddress substrate address of new owner811   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")812   * @returns ```true``` if extrinsic success, otherwise ```false```813   */814  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {815    const result = await this.helper.executeExtrinsic(816      signer,817      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],818      true,819    );820821    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');822  }823824  /**825   * Adds a collection administrator.826   *827   * @param signer keyring of signer828   * @param collectionId ID of collection829   * @param adminAddressObj Administrator address (substrate or ethereum)830   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})831   * @returns ```true``` if extrinsic success, otherwise ```false```832   */833  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {834    const result = await this.helper.executeExtrinsic(835      signer,836      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],837      true,838    );839840    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');841  }842843  /**844   * Removes a collection administrator.845   *846   * @param signer keyring of signer847   * @param collectionId ID of collection848   * @param adminAddressObj Administrator address (substrate or ethereum)849   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})850   * @returns ```true``` if extrinsic success, otherwise ```false```851   */852  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {853    const result = await this.helper.executeExtrinsic(854      signer,855      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],856      true,857    );858859    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');860  }861862  /**863   * Check if user is in allow list.864   * 865   * @param collectionId ID of collection866   * @param user Account to check867   * @example await getAdmins(1)868   * @returns is user in allow list869   */870  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {871    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();872  }873874  /**875   * Adds an address to allow list876   * @param signer keyring of signer877   * @param collectionId ID of collection878   * @param addressObj address to add to the allow list879   * @returns ```true``` if extrinsic success, otherwise ```false```880   */881  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {882    const result = await this.helper.executeExtrinsic(883      signer,884      'api.tx.unique.addToAllowList', [collectionId, addressObj],885      true,886    );887888    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');889  }890891  /**892   * Removes an address from allow list893   *894   * @param signer keyring of signer895   * @param collectionId ID of collection896   * @param addressObj address to remove from the allow list897   * @returns ```true``` if extrinsic success, otherwise ```false```898   */899  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {900    const result = await this.helper.executeExtrinsic(901      signer,902      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],903      true,904    );905906    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');907  }908909  /**910   * Sets onchain permissions for selected collection.911   *912   * @param signer keyring of signer913   * @param collectionId ID of collection914   * @param permissions collection permissions object915   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});916   * @returns ```true``` if extrinsic success, otherwise ```false```917   */918  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {919    const result = await this.helper.executeExtrinsic(920      signer,921      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],922      true,923    );924925    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');926  }927928  /**929   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.930   *931   * @param signer keyring of signer932   * @param collectionId ID of collection933   * @param permissions nesting permissions object934   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});935   * @returns ```true``` if extrinsic success, otherwise ```false```936   */937  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {938    return await this.setPermissions(signer, collectionId, {nesting: permissions});939  }940941  /**942   * Disables nesting for selected collection.943   *944   * @param signer keyring of signer945   * @param collectionId ID of collection946   * @example disableNesting(aliceKeyring, 10);947   * @returns ```true``` if extrinsic success, otherwise ```false```948   */949  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {950    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});951  }952953  /**954   * Sets onchain properties to the collection.955   *956   * @param signer keyring of signer957   * @param collectionId ID of collection958   * @param properties array of property objects959   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);960   * @returns ```true``` if extrinsic success, otherwise ```false```961   */962  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {963    const result = await this.helper.executeExtrinsic(964      signer,965      'api.tx.unique.setCollectionProperties', [collectionId, properties],966      true,967    );968969    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');970  }971972  /**973   * Get collection properties.974   * 975   * @param collectionId ID of collection976   * @param propertyKeys optionally filter the returned properties to only these keys977   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);978   * @returns array of key-value pairs979   */980  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {981    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();982  }983984  /**985   * Deletes onchain properties from the collection.986   *987   * @param signer keyring of signer988   * @param collectionId ID of collection989   * @param propertyKeys array of property keys to delete990   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);991   * @returns ```true``` if extrinsic success, otherwise ```false```992   */993  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {994    const result = await this.helper.executeExtrinsic(995      signer,996      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],997      true,998    );9991000    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1001  }10021003  /**1004   * Changes the owner of the token.1005   *1006   * @param signer keyring of signer1007   * @param collectionId ID of collection1008   * @param tokenId ID of token1009   * @param addressObj address of a new owner1010   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1011   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1012   * @returns true if the token success, otherwise false1013   */1014  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1015    const result = await this.helper.executeExtrinsic(1016      signer,1017      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1018      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1019    );10201021    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1022  }10231024  /**1025   *1026   * Change ownership of a token(s) on behalf of the owner.1027   *1028   * @param signer keyring of signer1029   * @param collectionId ID of collection1030   * @param tokenId ID of token1031   * @param fromAddressObj address on behalf of which the token will be sent1032   * @param toAddressObj new token owner1033   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1034   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1035   * @returns true if the token success, otherwise false1036   */1037  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1038    const result = await this.helper.executeExtrinsic(1039      signer,1040      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1041      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1042    );1043    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1044  }10451046  /**1047   *1048   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1049   *1050   * @param signer keyring of signer1051   * @param collectionId ID of collection1052   * @param tokenId ID of token1053   * @param amount amount of tokens to be burned. For NFT must be set to 1n1054   * @example burnToken(aliceKeyring, 10, 5);1055   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1056   */1057  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1058    const burnResult = await this.helper.executeExtrinsic(1059      signer,1060      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1061      true, // `Unable to burn token for ${label}`,1062    );1063    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1064    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1065    return burnedTokens.success;1066  }10671068  /**1069   * Destroys a concrete instance of NFT on behalf of the owner1070   *1071   * @param signer keyring of signer1072   * @param collectionId ID of collection1073   * @param tokenId ID of token1074   * @param fromAddressObj address on behalf of which the token will be burnt1075   * @param amount amount of tokens to be burned. For NFT must be set to 1n1076   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1077   * @returns ```true``` if extrinsic success, otherwise ```false```1078   */1079  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1080    const burnResult = await this.helper.executeExtrinsic(1081      signer,1082      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1083      true, // `Unable to burn token from for ${label}`,1084    );1085    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1086    return burnedTokens.success && burnedTokens.tokens.length > 0;1087  }10881089  /**1090   * Set, change, or remove approved address to transfer the ownership of the NFT.1091   *1092   * @param signer keyring of signer1093   * @param collectionId ID of collection1094   * @param tokenId ID of token1095   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1096   * @param amount amount of token to be approved. For NFT must be set to 1n1097   * @returns ```true``` if extrinsic success, otherwise ```false```1098   */1099  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1100    const approveResult = await this.helper.executeExtrinsic(1101      signer,1102      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1103      true, // `Unable to approve token for ${label}`,1104    );11051106    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1107  }11081109  /**1110   * Get the amount of token pieces approved to transfer or burn. Normally 0.1111   *1112   * @param collectionId ID of collection1113   * @param tokenId ID of token1114   * @param toAccountObj address which is approved to use token pieces1115   * @param fromAccountObj address which may have allowed the use of its owned tokens1116   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1117   * @returns number of approved to transfer pieces1118   */1119  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1120    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1121  }11221123  /**1124   * Get the last created token ID in a collection1125   *1126   * @param collectionId ID of collection1127   * @example getLastTokenId(10);1128   * @returns id of the last created token1129   */1130  async getLastTokenId(collectionId: number): Promise<number> {1131    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1132  }11331134  /**1135   * Check if token exists1136   *1137   * @param collectionId ID of collection1138   * @param tokenId ID of token1139   * @example doesTokenExist(10, 20);1140   * @returns true if the token exists, otherwise false1141   */1142  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1143    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1144  }1145}11461147class NFTnRFT extends CollectionGroup {1148  /**1149   * Get tokens owned by account1150   *1151   * @param collectionId ID of collection1152   * @param addressObj tokens owner1153   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1154   * @returns array of token ids owned by account1155   */1156  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1157    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1158  }11591160  /**1161   * Get token data1162   *1163   * @param collectionId ID of collection1164   * @param tokenId ID of token1165   * @param propertyKeys optionally filter the token properties to only these keys1166   * @param blockHashAt optionally query the data at some block with this hash1167   * @example getToken(10, 5);1168   * @returns human readable token data1169   */1170  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1171    properties: IProperty[];1172    owner: CrossAccountId;1173    normalizedOwner: CrossAccountId;1174  }| null> {1175    let tokenData;1176    if(typeof blockHashAt === 'undefined') {1177      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1178    }1179    else {1180      if(propertyKeys.length == 0) {1181        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1182        if(!collection) return null;1183        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1184      }1185      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1186    }1187    tokenData = tokenData.toHuman();1188    if (tokenData === null || tokenData.owner === null) return null;1189    const owner = {} as any;1190    for (const key of Object.keys(tokenData.owner)) {1191      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1192        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1193        : tokenData.owner[key];1194    }1195    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1196    return tokenData;1197  }11981199  /**1200   * Set permissions to change token properties1201   *1202   * @param signer keyring of signer1203   * @param collectionId ID of collection1204   * @param permissions permissions to change a property by the collection admin or token owner1205   * @example setTokenPropertyPermissions(1206   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1207   * )1208   * @returns true if extrinsic success otherwise false1209   */1210  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1211    const result = await this.helper.executeExtrinsic(1212      signer,1213      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1214      true,1215    );12161217    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1218  }12191220  /**1221   * Get token property permissions.1222   * 1223   * @param collectionId ID of collection1224   * @param propertyKeys optionally filter the returned property permissions to only these keys1225   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1226   * @returns array of key-permission pairs1227   */1228  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1229    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1230  }12311232  /**1233   * Set token properties1234   *1235   * @param signer keyring of signer1236   * @param collectionId ID of collection1237   * @param tokenId ID of token1238   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1239   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1240   * @returns ```true``` if extrinsic success, otherwise ```false```1241   */1242  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1243    const result = await this.helper.executeExtrinsic(1244      signer,1245      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1246      true,1247    );12481249    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1250  }12511252  /**1253   * Get properties, metadata assigned to a token.1254   * 1255   * @param collectionId ID of collection1256   * @param tokenId ID of token1257   * @param propertyKeys optionally filter the returned properties to only these keys1258   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1259   * @returns array of key-value pairs1260   */1261  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1262    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1263  }12641265  /**1266   * Delete the provided properties of a token1267   * @param signer keyring of signer1268   * @param collectionId ID of collection1269   * @param tokenId ID of token1270   * @param propertyKeys property keys to be deleted1271   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1272   * @returns ```true``` if extrinsic success, otherwise ```false```1273   */1274  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1275    const result = await this.helper.executeExtrinsic(1276      signer,1277      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1278      true,1279    );12801281    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1282  }12831284  /**1285   * Mint new collection1286   *1287   * @param signer keyring of signer1288   * @param collectionOptions basic collection options and properties1289   * @param mode NFT or RFT type of a collection1290   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1291   * @returns object of the created collection1292   */1293  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1294    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1295    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1296    for (const key of ['name', 'description', 'tokenPrefix']) {1297      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);1298    }1299    const creationResult = await this.helper.executeExtrinsic(1300      signer,1301      'api.tx.unique.createCollectionEx', [collectionOptions],1302      true, // errorLabel,1303    );1304    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1305  }13061307  getCollectionObject(_collectionId: number): any {1308    return null;1309  }13101311  getTokenObject(_collectionId: number, _tokenId: number): any {1312    return null;1313  }1314}131513161317class NFTGroup extends NFTnRFT {1318  /**1319   * Get collection object1320   * @param collectionId ID of collection1321   * @example getCollectionObject(2);1322   * @returns instance of UniqueNFTCollection1323   */1324  getCollectionObject(collectionId: number): UniqueNFTCollection {1325    return new UniqueNFTCollection(collectionId, this.helper);1326  }13271328  /**1329   * Get token object1330   * @param collectionId ID of collection1331   * @param tokenId ID of token1332   * @example getTokenObject(10, 5);1333   * @returns instance of UniqueNFTToken1334   */1335  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1336    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1337  }13381339  /**1340   * Get token's owner1341   * @param collectionId ID of collection1342   * @param tokenId ID of token1343   * @param blockHashAt optionally query the data at the block with this hash1344   * @example getTokenOwner(10, 5);1345   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1346   */1347  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1348    let owner;1349    if (typeof blockHashAt === 'undefined') {1350      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1351    } else {1352      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1353    }1354    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1355  }13561357  /**1358   * Is token approved to transfer1359   * @param collectionId ID of collection1360   * @param tokenId ID of token1361   * @param toAccountObj address to be approved1362   * @returns ```true``` if extrinsic success, otherwise ```false```1363   */1364  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1365    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1366  }13671368  /**1369   * Changes the owner of the token.1370   *1371   * @param signer keyring of signer1372   * @param collectionId ID of collection1373   * @param tokenId ID of token1374   * @param addressObj address of a new owner1375   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1376   * @returns ```true``` if extrinsic success, otherwise ```false```1377   */1378  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1379    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1380  }13811382  /**1383   *1384   * Change ownership of a NFT on behalf of the owner.1385   *1386   * @param signer keyring of signer1387   * @param collectionId ID of collection1388   * @param tokenId ID of token1389   * @param fromAddressObj address on behalf of which the token will be sent1390   * @param toAddressObj new token owner1391   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1392   * @returns ```true``` if extrinsic success, otherwise ```false```1393   */1394  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1395    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1396  }13971398  /**1399   * Recursively find the address that owns the token1400   * @param collectionId ID of collection1401   * @param tokenId ID of token1402   * @param blockHashAt1403   * @example getTokenTopmostOwner(10, 5);1404   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1405   */1406  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1407    let owner;1408    if (typeof blockHashAt === 'undefined') {1409      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1410    } else {1411      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1412    }14131414    if (owner === null) return null;14151416    return owner.toHuman();1417  }14181419  /**1420   * Get tokens nested in the provided token1421   * @param collectionId ID of collection1422   * @param tokenId ID of token1423   * @param blockHashAt optionally query the data at the block with this hash1424   * @example getTokenChildren(10, 5);1425   * @returns tokens whose depth of nesting is <= 51426   */1427  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1428    let children;1429    if(typeof blockHashAt === 'undefined') {1430      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1431    } else {1432      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1433    }14341435    return children.toJSON().map((x: any) => {1436      return {collectionId: x.collection, tokenId: x.token};1437    });1438  }14391440  /**1441   * Nest one token into another1442   * @param signer keyring of signer1443   * @param tokenObj token to be nested1444   * @param rootTokenObj token to be parent1445   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1446   * @returns ```true``` if extrinsic success, otherwise ```false```1447   */1448  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1449    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1450    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1451    if(!result) {1452      throw Error('Unable to nest token!');1453    }1454    return result;1455  }14561457  /**1458   * Remove token from nested state1459   * @param signer keyring of signer1460   * @param tokenObj token to unnest1461   * @param rootTokenObj parent of a token1462   * @param toAddressObj address of a new token owner1463   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1464   * @returns ```true``` if extrinsic success, otherwise ```false```1465   */1466  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1467    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1468    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1469    if(!result) {1470      throw Error('Unable to unnest token!');1471    }1472    return result;1473  }14741475  /**1476   * Mint new collection1477   * @param signer keyring of signer1478   * @param collectionOptions Collection options1479   * @example1480   * mintCollection(aliceKeyring, {1481   *   name: 'New',1482   *   description: 'New collection',1483   *   tokenPrefix: 'NEW',1484   * })1485   * @returns object of the created collection1486   */1487  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1488    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1489  }14901491  /**1492   * Mint new token1493   * @param signer keyring of signer1494   * @param data token data1495   * @returns created token object1496   */1497  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1498    const creationResult = await this.helper.executeExtrinsic(1499      signer,1500      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1501        nft: {1502          properties: data.properties,1503        },1504      }],1505      true,1506    );1507    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1508    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1509    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1510    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1511  }15121513  /**1514   * Mint multiple NFT tokens1515   * @param signer keyring of signer1516   * @param collectionId ID of collection1517   * @param tokens array of tokens with owner and properties1518   * @example1519   * mintMultipleTokens(aliceKeyring, 10, [{1520   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1521   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1522   *   },{1523   *     owner: {Ethereum: "0x9F0583DbB855d..."},1524   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1525   * }]);1526   * @returns ```true``` if extrinsic success, otherwise ```false```1527   */1528  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1529    const creationResult = await this.helper.executeExtrinsic(1530      signer,1531      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1532      true,1533    );1534    const collection = this.getCollectionObject(collectionId);1535    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1536  }15371538  /**1539   * Mint multiple NFT tokens with one owner1540   * @param signer keyring of signer1541   * @param collectionId ID of collection1542   * @param owner tokens owner1543   * @param tokens array of tokens with owner and properties1544   * @example1545   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1546   *   properties: [{1547   *   key: "gender",1548   *   value: "female",1549   *  },{1550   *   key: "age",1551   *   value: "33",1552   *  }],1553   * }]);1554   * @returns array of newly created tokens1555   */1556  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1557    const rawTokens = [];1558    for (const token of tokens) {1559      const raw = {NFT: {properties: token.properties}};1560      rawTokens.push(raw);1561    }1562    const creationResult = await this.helper.executeExtrinsic(1563      signer,1564      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1565      true,1566    );1567    const collection = this.getCollectionObject(collectionId);1568    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1569  }15701571  /**1572   * Set, change, or remove approved address to transfer the ownership of the NFT.1573   *1574   * @param signer keyring of signer1575   * @param collectionId ID of collection1576   * @param tokenId ID of token1577   * @param toAddressObj address to approve1578   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1579   * @returns ```true``` if extrinsic success, otherwise ```false```1580   */1581  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1582    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1583  }1584}158515861587class RFTGroup extends NFTnRFT {1588  /**1589   * Get collection object1590   * @param collectionId ID of collection1591   * @example getCollectionObject(2);1592   * @returns instance of UniqueRFTCollection1593   */1594  getCollectionObject(collectionId: number): UniqueRFTCollection {1595    return new UniqueRFTCollection(collectionId, this.helper);1596  }15971598  /**1599   * Get token object1600   * @param collectionId ID of collection1601   * @param tokenId ID of token1602   * @example getTokenObject(10, 5);1603   * @returns instance of UniqueNFTToken1604   */1605  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1606    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1607  }16081609  /**1610   * Get top 10 token owners with the largest number of pieces1611   * @param collectionId ID of collection1612   * @param tokenId ID of token1613   * @example getTokenTop10Owners(10, 5);1614   * @returns array of top 10 owners1615   */1616  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1617    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1618  }16191620  /**1621   * Get number of pieces owned by address1622   * @param collectionId ID of collection1623   * @param tokenId ID of token1624   * @param addressObj address token owner1625   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1626   * @returns number of pieces ownerd by address1627   */1628  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1629    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1630  }16311632  /**1633   * Transfer pieces of token to another address1634   * @param signer keyring of signer1635   * @param collectionId ID of collection1636   * @param tokenId ID of token1637   * @param addressObj address of a new owner1638   * @param amount number of pieces to be transfered1639   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1640   * @returns ```true``` if extrinsic success, otherwise ```false```1641   */1642  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1643    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1644  }16451646  /**1647   * Change ownership of some pieces of RFT on behalf of the owner.1648   * @param signer keyring of signer1649   * @param collectionId ID of collection1650   * @param tokenId ID of token1651   * @param fromAddressObj address on behalf of which the token will be sent1652   * @param toAddressObj new token owner1653   * @param amount number of pieces to be transfered1654   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1655   * @returns ```true``` if extrinsic success, otherwise ```false```1656   */1657  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1658    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1659  }16601661  /**1662   * Mint new collection1663   * @param signer keyring of signer1664   * @param collectionOptions Collection options1665   * @example1666   * mintCollection(aliceKeyring, {1667   *   name: 'New',1668   *   description: 'New collection',1669   *   tokenPrefix: 'NEW',1670   * })1671   * @returns object of the created collection1672   */1673  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1674    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1675  }16761677  /**1678   * Mint new token1679   * @param signer keyring of signer1680   * @param data token data1681   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1682   * @returns created token object1683   */1684  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1685    const creationResult = await this.helper.executeExtrinsic(1686      signer,1687      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1688        refungible: {1689          pieces: data.pieces,1690          properties: data.properties,1691        },1692      }],1693      true,1694    );1695    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1696    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1697    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1698    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1699  }17001701  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1702    throw Error('Not implemented');1703    const creationResult = await this.helper.executeExtrinsic(1704      signer,1705      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1706      true, // `Unable to mint RFT tokens for ${label}`,1707    );1708    const collection = this.getCollectionObject(collectionId);1709    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1710  }17111712  /**1713   * Mint multiple RFT tokens with one owner1714   * @param signer keyring of signer1715   * @param collectionId ID of collection1716   * @param owner tokens owner1717   * @param tokens array of tokens with properties and pieces1718   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1719   * @returns array of newly created RFT tokens1720   */1721  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1722    const rawTokens = [];1723    for (const token of tokens) {1724      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1725      rawTokens.push(raw);1726    }1727    const creationResult = await this.helper.executeExtrinsic(1728      signer,1729      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1730      true,1731    );1732    const collection = this.getCollectionObject(collectionId);1733    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1734  }17351736  /**1737   * Destroys a concrete instance of RFT.1738   * @param signer keyring of signer1739   * @param collectionId ID of collection1740   * @param tokenId ID of token1741   * @param amount number of pieces to be burnt1742   * @example burnToken(aliceKeyring, 10, 5);1743   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1744   */1745  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1746    return await super.burnToken(signer, collectionId, tokenId, amount);1747  }17481749  /**1750   * Destroys a concrete instance of RFT on behalf of the owner.1751   * @param signer keyring of signer1752   * @param collectionId ID of collection1753   * @param tokenId ID of token1754   * @param fromAddressObj address on behalf of which the token will be burnt1755   * @param amount number of pieces to be burnt1756   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1757   * @returns ```true``` if extrinsic success, otherwise ```false```1758   */1759  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1760    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1761  }17621763  /**1764   * Set, change, or remove approved address to transfer the ownership of the RFT.1765   *1766   * @param signer keyring of signer1767   * @param collectionId ID of collection1768   * @param tokenId ID of token1769   * @param toAddressObj address to approve1770   * @param amount number of pieces to be approved1771   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1772   * @returns true if the token success, otherwise false1773   */1774  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1775    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1776  }17771778  /**1779   * Get total number of pieces1780   * @param collectionId ID of collection1781   * @param tokenId ID of token1782   * @example getTokenTotalPieces(10, 5);1783   * @returns number of pieces1784   */1785  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1786    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1787  }17881789  /**1790   * Change number of token pieces. Signer must be the owner of all token pieces.1791   * @param signer keyring of signer1792   * @param collectionId ID of collection1793   * @param tokenId ID of token1794   * @param amount new number of pieces1795   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1796   * @returns true if the repartion was success, otherwise false1797   */1798  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1799    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1800    const repartitionResult = await this.helper.executeExtrinsic(1801      signer,1802      'api.tx.unique.repartition', [collectionId, tokenId, amount],1803      true,1804    );1805    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1806    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1807  }1808}180918101811class FTGroup extends CollectionGroup {1812  /**1813   * Get collection object1814   * @param collectionId ID of collection1815   * @example getCollectionObject(2);1816   * @returns instance of UniqueFTCollection1817   */1818  getCollectionObject(collectionId: number): UniqueFTCollection {1819    return new UniqueFTCollection(collectionId, this.helper);1820  }18211822  /**1823   * Mint new fungible collection1824   * @param signer keyring of signer1825   * @param collectionOptions Collection options1826   * @param decimalPoints number of token decimals1827   * @example1828   * mintCollection(aliceKeyring, {1829   *   name: 'New',1830   *   description: 'New collection',1831   *   tokenPrefix: 'NEW',1832   * }, 18)1833   * @returns newly created fungible collection1834   */1835  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1836    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1837    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1838    collectionOptions.mode = {fungible: decimalPoints};1839    for (const key of ['name', 'description', 'tokenPrefix']) {1840      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);1841    }1842    const creationResult = await this.helper.executeExtrinsic(1843      signer,1844      'api.tx.unique.createCollectionEx', [collectionOptions],1845      true,1846    );1847    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1848  }18491850  /**1851   * Mint tokens1852   * @param signer keyring of signer1853   * @param collectionId ID of collection1854   * @param owner address owner of new tokens1855   * @param amount amount of tokens to be meanted1856   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1857   * @returns ```true``` if extrinsic success, otherwise ```false```1858   */1859  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1860    const creationResult = await this.helper.executeExtrinsic(1861      signer,1862      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1863        fungible: {1864          value: amount,1865        },1866      }],1867      true, // `Unable to mint fungible tokens for ${label}`,1868    );1869    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1870  }18711872  /**1873   * Mint multiple Fungible tokens with one owner1874   * @param signer keyring of signer1875   * @param collectionId ID of collection1876   * @param owner tokens owner1877   * @param tokens array of tokens with properties and pieces1878   * @returns ```true``` if extrinsic success, otherwise ```false```1879   */1880  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1881    const rawTokens = [];1882    for (const token of tokens) {1883      const raw = {Fungible: {Value: token.value}};1884      rawTokens.push(raw);1885    }1886    const creationResult = await this.helper.executeExtrinsic(1887      signer,1888      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1889      true,1890    );1891    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1892  }18931894  /**1895   * Get the top 10 owners with the largest balance for the Fungible collection1896   * @param collectionId ID of collection1897   * @example getTop10Owners(10);1898   * @returns array of ```ICrossAccountId```1899   */1900  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1901    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1902  }19031904  /**1905   * Get account balance1906   * @param collectionId ID of collection1907   * @param addressObj address of owner1908   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1909   * @returns amount of fungible tokens owned by address1910   */1911  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1912    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1913  }19141915  /**1916   * Transfer tokens to address1917   * @param signer keyring of signer1918   * @param collectionId ID of collection1919   * @param toAddressObj address recipient1920   * @param amount amount of tokens to be sent1921   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1922   * @returns ```true``` if extrinsic success, otherwise ```false```1923   */1924  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1925    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1926  }19271928  /**1929   * Transfer some tokens on behalf of the owner.1930   * @param signer keyring of signer1931   * @param collectionId ID of collection1932   * @param fromAddressObj address on behalf of which tokens will be sent1933   * @param toAddressObj address where token to be sent1934   * @param amount number of tokens to be sent1935   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1936   * @returns ```true``` if extrinsic success, otherwise ```false```1937   */1938  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1939    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1940  }19411942  /**1943   * Destroy some amount of tokens1944   * @param signer keyring of signer1945   * @param collectionId ID of collection1946   * @param amount amount of tokens to be destroyed1947   * @example burnTokens(aliceKeyring, 10, 1000n);1948   * @returns ```true``` if extrinsic success, otherwise ```false```1949   */1950  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1951    return await super.burnToken(signer, collectionId, 0, amount);1952  }19531954  /**1955   * Burn some tokens on behalf of the owner.1956   * @param signer keyring of signer1957   * @param collectionId ID of collection1958   * @param fromAddressObj address on behalf of which tokens will be burnt1959   * @param amount amount of tokens to be burnt1960   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1961   * @returns ```true``` if extrinsic success, otherwise ```false```1962   */1963  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1964    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1965  }19661967  /**1968   * Get total collection supply1969   * @param collectionId1970   * @returns1971   */1972  async getTotalPieces(collectionId: number): Promise<bigint> {1973    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1974  }19751976  /**1977   * Set, change, or remove approved address to transfer tokens.1978   *1979   * @param signer keyring of signer1980   * @param collectionId ID of collection1981   * @param toAddressObj address to be approved1982   * @param amount amount of tokens to be approved1983   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1984   * @returns ```true``` if extrinsic success, otherwise ```false```1985   */1986  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1987    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1988  }19891990  /**1991   * Get amount of fungible tokens approved to transfer1992   * @param collectionId ID of collection1993   * @param fromAddressObj owner of tokens1994   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1995   * @returns number of tokens approved for the transfer1996   */1997  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1998    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1999  }2000}200120022003class ChainGroup extends HelperGroup {2004  /**2005   * Get system properties of a chain2006   * @example getChainProperties();2007   * @returns ss58Format, token decimals, and token symbol2008   */2009  getChainProperties(): IChainProperties {2010    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2011    return {2012      ss58Format: properties.ss58Format.toJSON(),2013      tokenDecimals: properties.tokenDecimals.toJSON(),2014      tokenSymbol: properties.tokenSymbol.toJSON(),2015    };2016  }20172018  /**2019   * Get chain header2020   * @example getLatestBlockNumber();2021   * @returns the number of the last block2022   */2023  async getLatestBlockNumber(): Promise<number> {2024    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2025  }20262027  /**2028   * Get block hash by block number2029   * @param blockNumber number of block2030   * @example getBlockHashByNumber(12345);2031   * @returns hash of a block2032   */2033  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2034    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2035    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2036    return blockHash;2037  }20382039  // TODO add docs2040  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2041    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2042    if (!blockHash) return null;2043    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2044  }20452046  /**2047   * Get account nonce2048   * @param address substrate address2049   * @example getNonce("5GrwvaEF5zXb26Fz...");2050   * @returns number, account's nonce2051   */2052  async getNonce(address: TSubstrateAccount): Promise<number> {2053    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2054  }2055}205620572058class BalanceGroup extends HelperGroup {2059  getCollectionCreationPrice(): bigint {2060    return 2n * this.helper.balance.getOneTokenNominal();2061  }2062  /**2063   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2064   * @example getOneTokenNominal()2065   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2066   */2067  getOneTokenNominal(): bigint {2068    const chainProperties = this.helper.chain.getChainProperties();2069    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2070  }20712072  /**2073   * Get substrate address balance2074   * @param address substrate address2075   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2076   * @returns amount of tokens on address2077   */2078  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2079    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2080  }20812082  /**2083   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2084   * @param address substrate address2085   * @returns2086   */2087  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2088    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2089    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2090  }20912092  /**2093   * Get ethereum address balance2094   * @param address ethereum address2095   * @example getEthereum("0x9F0583DbB855d...")2096   * @returns amount of tokens on address2097   */2098  async getEthereum(address: TEthereumAccount): Promise<bigint> {2099    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2100  }21012102  /**2103   * Transfer tokens to substrate address2104   * @param signer keyring of signer2105   * @param address substrate address of a recipient2106   * @param amount amount of tokens to be transfered2107   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2108   * @returns ```true``` if extrinsic success, otherwise ```false```2109   */2110  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2111    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}`*/);21122113    let transfer = {from: null, to: null, amount: 0n} as any;2114    result.result.events.forEach(({event: {data, method, section}}) => {2115      if ((section === 'balances') && (method === 'Transfer')) {2116        transfer = {2117          from: this.helper.address.normalizeSubstrate(data[0]),2118          to: this.helper.address.normalizeSubstrate(data[1]),2119          amount: BigInt(data[2]),2120        };2121      }2122    });2123    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2124      && this.helper.address.normalizeSubstrate(address) === transfer.to 2125      && BigInt(amount) === transfer.amount;2126    return isSuccess;2127  }2128}212921302131class AddressGroup extends HelperGroup {2132  /**2133   * Normalizes the address to the specified ss58 format, by default ```42```.2134   * @param address substrate address2135   * @param ss58Format format for address conversion, by default ```42```2136   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2137   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2138   */2139  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2140    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2141  }21422143  /**2144   * Get address in the connected chain format2145   * @param address substrate address2146   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2147   * @returns address in chain format2148   */2149  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2150    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2151  }21522153  /**2154   * Get substrate mirror of an ethereum address2155   * @param ethAddress ethereum address2156   * @param toChainFormat false for normalized account2157   * @example ethToSubstrate('0x9F0583DbB855d...')2158   * @returns substrate mirror of a provided ethereum address2159   */2160  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2161    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2162  }21632164  /**2165   * Get ethereum mirror of a substrate address2166   * @param subAddress substrate account2167   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2168   * @returns ethereum mirror of a provided substrate address2169   */2170  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2171    return CrossAccountId.translateSubToEth(subAddress);2172  }2173}21742175class StakingGroup extends HelperGroup {2176  /**2177   * Stake tokens for App Promotion2178   * @param signer keyring of signer2179   * @param amountToStake amount of tokens to stake2180   * @param label extra label for log2181   * @returns2182   */2183  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2184    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2185    const _stakeResult = await this.helper.executeExtrinsic(2186      signer, 'api.tx.appPromotion.stake',2187      [amountToStake], true,2188    );2189    // TODO extract info from stakeResult2190    return true;2191  }21922193  /**2194   * Unstake tokens for App Promotion2195   * @param signer keyring of signer2196   * @param amountToUnstake amount of tokens to unstake2197   * @param label extra label for log2198   * @returns block number where balances will be unlocked2199   */2200  async unstake(signer: TSigner, label?: string): Promise<number> {2201    if(typeof label === 'undefined') label = `${signer.address}`;2202    const _unstakeResult = await this.helper.executeExtrinsic(2203      signer, 'api.tx.appPromotion.unstake',2204      [], true,2205    );2206    // TODO extract block number fron events2207    return 1;2208  }22092210  /**2211   * Get total staked amount for address2212   * @param address substrate or ethereum address2213   * @returns total staked amount2214   */2215  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2216    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2217    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2218  }22192220  /**2221   * Get total staked per block2222   * @param address substrate or ethereum address2223   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2224   */2225  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2226    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2227    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2228      return { 2229        block: block.toBigInt(),2230        amount: amount.toBigInt(),2231      };2232    });2233  }22342235  /**2236   * Get total pending unstake amount for address2237   * @param address substrate or ethereum address2238   * @returns total pending unstake amount2239   */2240  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2241    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2242  }22432244  /**2245   * Get pending unstake amount per block for address2246   * @param address substrate or ethereum address2247   * @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 block2248   */2249  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2250    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2251    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2252      return {2253        block: block.toBigInt(),2254        amount: amount.toBigInt(),2255      };2256    });2257    return result;2258  }2259}22602261class SchedulerGroup extends HelperGroup {2262  constructor(helper: UniqueHelper) {2263    super(helper);2264  }22652266  async cancelScheduled(signer: TSigner, scheduledId: string) {2267    return this.helper.executeExtrinsic(2268      signer,2269      'api.tx.scheduler.cancelNamed',2270      [scheduledId],2271      true,2272    );2273  }22742275  async changePriority(signer: TSigner, scheduledId: string, priority: number) {2276    return this.helper.executeExtrinsic(2277      signer,2278      'api.tx.scheduler.changeNamedPriority',2279      [scheduledId, priority],2280      true,2281    );2282  }22832284  scheduleAt<T extends UniqueHelper>(2285    scheduledId: string,2286    executionBlockNumber: number,2287    options: ISchedulerOptions = {},2288  ) {2289    return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2290  }22912292  scheduleAfter<T extends UniqueHelper>(2293    scheduledId: string,2294    blocksBeforeExecution: number,2295    options: ISchedulerOptions = {},2296  ) {2297    return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2298  }22992300  schedule<T extends UniqueHelper>(2301    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2302    scheduledId: string,2303    blocksNum: number,2304    options: ISchedulerOptions = {},2305  ) {2306    // eslint-disable-next-line @typescript-eslint/naming-convention2307    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2308    return this.helper.clone(ScheduledHelperType, {2309      scheduleFn,2310      scheduledId,2311      blocksNum,2312      options,2313    }) as T;2314  }2315}23162317export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;23182319export class UniqueHelper extends ChainHelperBase {2320  helperBase: any;23212322  chain: ChainGroup;2323  balance: BalanceGroup;2324  address: AddressGroup;2325  collection: CollectionGroup;2326  nft: NFTGroup;2327  rft: RFTGroup;2328  ft: FTGroup;2329  staking: StakingGroup;2330  scheduler: SchedulerGroup;23312332  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2333    super(logger);23342335    this.helperBase = options.helperBase ?? UniqueHelper;23362337    this.chain = new ChainGroup(this);2338    this.balance = new BalanceGroup(this);2339    this.address = new AddressGroup(this);2340    this.collection = new CollectionGroup(this);2341    this.nft = new NFTGroup(this);2342    this.rft = new RFTGroup(this);2343    this.ft = new FTGroup(this);2344    this.staking = new StakingGroup(this);2345    this.scheduler = new SchedulerGroup(this);2346  }23472348  clone(helperCls: UniqueHelperConstructor, options: {[key: string]: any} = {}) {2349    Object.setPrototypeOf(helperCls.prototype, this);2350    const newHelper = new helperCls(this.logger, options);23512352    newHelper.api = this.api;2353    newHelper.network = this.network;2354    newHelper.forceNetwork = this.forceNetwork;23552356    this.children.push(newHelper);23572358    return newHelper;2359  }23602361  getSudo<T extends UniqueHelper>() {2362    // eslint-disable-next-line @typescript-eslint/naming-convention2363    const SudoHelperType = SudoUniqueHelper(this.helperBase);2364    return this.clone(SudoHelperType) as T;2365  }2366}23672368// eslint-disable-next-line @typescript-eslint/naming-convention2369function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2370  return class extends Base {2371    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2372    scheduledId: string;2373    blocksNum: number;2374    options: ISchedulerOptions;23752376    constructor(...args: any[]) {2377      const logger = args[0] as ILogger;2378      const options = args[1] as {2379        scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2380        scheduledId: string,2381        blocksNum: number,2382        options: ISchedulerOptions2383      };23842385      super(logger);23862387      this.scheduleFn = options.scheduleFn;2388      this.scheduledId = options.scheduledId;2389      this.blocksNum = options.blocksNum;2390      this.options = options.options;2391    }23922393    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2394      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2395      const extrinsic = 'api.tx.scheduler.' +  this.scheduleFn;23962397      return super.executeExtrinsic(2398        sender,2399        extrinsic,2400        [2401          this.scheduledId,2402          this.blocksNum,2403          this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2404          this.options.priority ?? null,2405          {Value: scheduledTx},2406        ],2407        expectSuccess,2408      );2409    }2410  };2411}24122413// eslint-disable-next-line @typescript-eslint/naming-convention2414function SudoUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2415  return class extends Base {2416    constructor(...args: any[]) {2417      super(...args);2418    }24192420    executeExtrinsic (2421      sender: IKeyringPair,2422      extrinsic: string,2423      params: any[],2424      expectSuccess?: boolean,2425    ): Promise<ITransactionResult> {2426      const call = this.constructApiCall(extrinsic, params);24272428      return super.executeExtrinsic(2429        sender,2430        'api.tx.sudo.sudo',2431        [call],2432        expectSuccess,2433      );2434    }2435  };2436}24372438export class UniqueBaseCollection {2439  helper: UniqueHelper;2440  collectionId: number;24412442  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2443    this.collectionId = collectionId;2444    this.helper = uniqueHelper;2445  }24462447  async getData() {2448    return await this.helper.collection.getData(this.collectionId);2449  }24502451  async getLastTokenId() {2452    return await this.helper.collection.getLastTokenId(this.collectionId);2453  }24542455  async doesTokenExist(tokenId: number) {2456    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2457  }24582459  async getAdmins() {2460    return await this.helper.collection.getAdmins(this.collectionId);2461  }24622463  async getAllowList() {2464    return await this.helper.collection.getAllowList(this.collectionId);2465  }24662467  async getEffectiveLimits() {2468    return await this.helper.collection.getEffectiveLimits(this.collectionId);2469  }24702471  async getProperties(propertyKeys?: string[] | null) {2472    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2473  }24742475  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2476    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2477  }24782479  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2480    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2481  }24822483  async confirmSponsorship(signer: TSigner) {2484    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2485  }24862487  async removeSponsor(signer: TSigner) {2488    return await this.helper.collection.removeSponsor(signer, this.collectionId);2489  }24902491  async setLimits(signer: TSigner, limits: ICollectionLimits) {2492    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2493  }24942495  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2496    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2497  }24982499  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2500    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2501  }25022503  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2504    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2505  }25062507  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2508    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2509  }25102511  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2512    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2513  }25142515  async setProperties(signer: TSigner, properties: IProperty[]) {2516    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2517  }25182519  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2520    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2521  }25222523  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2524    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2525  }25262527  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2528    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2529  }25302531  async disableNesting(signer: TSigner) {2532    return await this.helper.collection.disableNesting(signer, this.collectionId);2533  }25342535  async burn(signer: TSigner) {2536    return await this.helper.collection.burn(signer, this.collectionId);2537  }25382539  scheduleAt<T extends UniqueHelper>(2540    scheduledId: string,2541    executionBlockNumber: number,2542    options: ISchedulerOptions = {},2543  ) {2544    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2545    return new UniqueBaseCollection(this.collectionId, scheduledHelper);2546  }25472548  scheduleAfter<T extends UniqueHelper>(2549    scheduledId: string,2550    blocksBeforeExecution: number,2551    options: ISchedulerOptions = {},2552  ) {2553    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2554    return new UniqueBaseCollection(this.collectionId, scheduledHelper);2555  }25562557  getSudo<T extends UniqueHelper>() {2558    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2559  }2560}256125622563export class UniqueNFTCollection extends UniqueBaseCollection {2564  getTokenObject(tokenId: number) {2565    return new UniqueNFToken(tokenId, this);2566  }25672568  async getTokensByAddress(addressObj: ICrossAccountId) {2569    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2570  }25712572  async getToken(tokenId: number, blockHashAt?: string) {2573    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2574  }25752576  async getTokenOwner(tokenId: number, blockHashAt?: string) {2577    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2578  }25792580  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2581    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2582  }25832584  async getTokenChildren(tokenId: number, blockHashAt?: string) {2585    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2586  }25872588  async getPropertyPermissions(propertyKeys: string[] | null = null) {2589    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2590  }25912592  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2593    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2594  }25952596  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2597    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2598  }25992600  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2601    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2602  }26032604  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2605    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2606  }26072608  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2609    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2610  }26112612  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2613    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2614  }26152616  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2617    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2618  }26192620  async burnToken(signer: TSigner, tokenId: number) {2621    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2622  }26232624  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2625    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2626  }26272628  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2629    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2630  }26312632  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2633    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2634  }26352636  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2637    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2638  }26392640  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2641    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2642  }26432644  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2645    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2646  }26472648  scheduleAt<T extends UniqueHelper>(2649    scheduledId: string,2650    executionBlockNumber: number,2651    options: ISchedulerOptions = {},2652  ) {2653    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2654    return new UniqueNFTCollection(this.collectionId, scheduledHelper);2655  }26562657  scheduleAfter<T extends UniqueHelper>(2658    scheduledId: string,2659    blocksBeforeExecution: number,2660    options: ISchedulerOptions = {},2661  ) {2662    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2663    return new UniqueNFTCollection(this.collectionId, scheduledHelper);2664  }26652666  getSudo<T extends UniqueHelper>() {2667    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());2668  }2669}267026712672export class UniqueRFTCollection extends UniqueBaseCollection {2673  getTokenObject(tokenId: number) {2674    return new UniqueRFToken(tokenId, this);2675  }26762677  async getToken(tokenId: number, blockHashAt?: string) {2678    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2679  }26802681  async getTokensByAddress(addressObj: ICrossAccountId) {2682    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2683  }26842685  async getTop10TokenOwners(tokenId: number) {2686    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2687  }26882689  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2690    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2691  }26922693  async getTokenTotalPieces(tokenId: number) {2694    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2695  }26962697  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2698    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2699  }27002701  async getPropertyPermissions(propertyKeys: string[] | null = null) {2702    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2703  }27042705  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2706    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2707  }27082709  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2710    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2711  }27122713  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2714    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2715  }27162717  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2718    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2719  }27202721  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2722    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2723  }27242725  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2726    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2727  }27282729  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2730    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2731  }27322733  async burnToken(signer: TSigner, tokenId: number, amount=1n) {2734    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2735  }27362737  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {2738    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2739  }27402741  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2742    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2743  }27442745  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2746    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2747  }27482749  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2750    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2751  }27522753  scheduleAt<T extends UniqueHelper>(2754    scheduledId: string,2755    executionBlockNumber: number,2756    options: ISchedulerOptions = {},2757  ) {2758    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2759    return new UniqueRFTCollection(this.collectionId, scheduledHelper);2760  }27612762  scheduleAfter<T extends UniqueHelper>(2763    scheduledId: string,2764    blocksBeforeExecution: number,2765    options: ISchedulerOptions = {},2766  ) {2767    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2768    return new UniqueRFTCollection(this.collectionId, scheduledHelper);2769  }27702771  getSudo<T extends UniqueHelper>() {2772    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());2773  }2774}277527762777export class UniqueFTCollection extends UniqueBaseCollection {2778  async getBalance(addressObj: ICrossAccountId) {2779    return await this.helper.ft.getBalance(this.collectionId, addressObj);2780  }27812782  async getTotalPieces() {2783    return await this.helper.ft.getTotalPieces(this.collectionId);2784  }27852786  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2787    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2788  }27892790  async getTop10Owners() {2791    return await this.helper.ft.getTop10Owners(this.collectionId);2792  }27932794  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2795    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2796  }27972798  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2799    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2800  }28012802  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2803    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2804  }28052806  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2807    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2808  }28092810  async burnTokens(signer: TSigner, amount=1n) {2811    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2812  }28132814  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2815    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2816  }28172818  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2819    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2820  }28212822  scheduleAt<T extends UniqueHelper>(2823    scheduledId: string,2824    executionBlockNumber: number,2825    options: ISchedulerOptions = {},2826  ) {2827    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2828    return new UniqueFTCollection(this.collectionId, scheduledHelper);2829  }28302831  scheduleAfter<T extends UniqueHelper>(2832    scheduledId: string,2833    blocksBeforeExecution: number,2834    options: ISchedulerOptions = {},2835  ) {2836    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2837    return new UniqueFTCollection(this.collectionId, scheduledHelper);2838  }28392840  getSudo<T extends UniqueHelper>() {2841    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());2842  }2843}284428452846export class UniqueBaseToken {2847  collection: UniqueNFTCollection | UniqueRFTCollection;2848  collectionId: number;2849  tokenId: number;28502851  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2852    this.collection = collection;2853    this.collectionId = collection.collectionId;2854    this.tokenId = tokenId;2855  }28562857  async getNextSponsored(addressObj: ICrossAccountId) {2858    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2859  }28602861  async getProperties(propertyKeys?: string[] | null) {2862    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2863  }28642865  async setProperties(signer: TSigner, properties: IProperty[]) {2866    return await this.collection.setTokenProperties(signer, this.tokenId, properties);2867  }28682869  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2870    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2871  }28722873  async doesExist() {2874    return await this.collection.doesTokenExist(this.tokenId);2875  }28762877  nestingAccount() {2878    return this.collection.helper.util.getTokenAccount(this);2879  }28802881  scheduleAt<T extends UniqueHelper>(2882    scheduledId: string,2883    executionBlockNumber: number,2884    options: ISchedulerOptions = {},2885  ) {2886    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2887    return new UniqueBaseToken(this.tokenId, scheduledCollection);2888  }28892890  scheduleAfter<T extends UniqueHelper>(2891    scheduledId: string,2892    blocksBeforeExecution: number,2893    options: ISchedulerOptions = {},2894  ) {2895    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2896    return new UniqueBaseToken(this.tokenId, scheduledCollection);2897  }28982899  getSudo<T extends UniqueHelper>() {2900    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());2901  }2902}290329042905export class UniqueNFToken extends UniqueBaseToken {2906  collection: UniqueNFTCollection;29072908  constructor(tokenId: number, collection: UniqueNFTCollection) {2909    super(tokenId, collection);2910    this.collection = collection;2911  }29122913  async getData(blockHashAt?: string) {2914    return await this.collection.getToken(this.tokenId, blockHashAt);2915  }29162917  async getOwner(blockHashAt?: string) {2918    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2919  }29202921  async getTopmostOwner(blockHashAt?: string) {2922    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2923  }29242925  async getChildren(blockHashAt?: string) {2926    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2927  }29282929  async nest(signer: TSigner, toTokenObj: IToken) {2930    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2931  }29322933  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2934    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2935  }29362937  async transfer(signer: TSigner, addressObj: ICrossAccountId) {2938    return await this.collection.transferToken(signer, this.tokenId, addressObj);2939  }29402941  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2942    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2943  }29442945  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2946    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2947  }29482949  async isApproved(toAddressObj: ICrossAccountId) {2950    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2951  }29522953  async burn(signer: TSigner) {2954    return await this.collection.burnToken(signer, this.tokenId);2955  }29562957  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2958    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2959  }29602961  scheduleAt<T extends UniqueHelper>(2962    scheduledId: string,2963    executionBlockNumber: number,2964    options: ISchedulerOptions = {},2965  ) {2966    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2967    return new UniqueNFToken(this.tokenId, scheduledCollection);2968  }29692970  scheduleAfter<T extends UniqueHelper>(2971    scheduledId: string,2972    blocksBeforeExecution: number,2973    options: ISchedulerOptions = {},2974  ) {2975    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2976    return new UniqueNFToken(this.tokenId, scheduledCollection);2977  }29782979  getSudo<T extends UniqueHelper>() {2980    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());2981  }2982}29832984export class UniqueRFToken extends UniqueBaseToken {2985  collection: UniqueRFTCollection;29862987  constructor(tokenId: number, collection: UniqueRFTCollection) {2988    super(tokenId, collection);2989    this.collection = collection;2990  }29912992  async getData(blockHashAt?: string) {2993    return await this.collection.getToken(this.tokenId, blockHashAt);2994  }29952996  async getTop10Owners() {2997    return await this.collection.getTop10TokenOwners(this.tokenId);2998  }29993000  async getBalance(addressObj: ICrossAccountId) {3001    return await this.collection.getTokenBalance(this.tokenId, addressObj);3002  }30033004  async getTotalPieces() {3005    return await this.collection.getTokenTotalPieces(this.tokenId);3006  }30073008  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3009    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3010  }30113012  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3013    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3014  }30153016  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3017    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3018  }30193020  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3021    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3022  }30233024  async repartition(signer: TSigner, amount: bigint) {3025    return await this.collection.repartitionToken(signer, this.tokenId, amount);3026  }30273028  async burn(signer: TSigner, amount=1n) {3029    return await this.collection.burnToken(signer, this.tokenId, amount);3030  }30313032  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3033    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3034  }30353036  scheduleAt<T extends UniqueHelper>(3037    scheduledId: string,3038    executionBlockNumber: number,3039    options: ISchedulerOptions = {},3040  ) {3041    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3042    return new UniqueRFToken(this.tokenId, scheduledCollection);3043  }30443045  scheduleAfter<T extends UniqueHelper>(3046    scheduledId: string,3047    blocksBeforeExecution: number,3048    options: ISchedulerOptions = {},3049  ) {3050    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3051    return new UniqueRFToken(this.tokenId, scheduledCollection);3052  }30533054  getSudo<T extends UniqueHelper>() {3055    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3056  }3057}
after · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';1314export class CrossAccountId implements ICrossAccountId {15  Substrate?: TSubstrateAccount;16  Ethereum?: TEthereumAccount;1718  constructor(account: ICrossAccountId) {19    if (account.Substrate) this.Substrate = account.Substrate;20    if (account.Ethereum) this.Ethereum = account.Ethereum;21  }2223  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24    switch (domain) {25      case 'Substrate': return new CrossAccountId({Substrate: account.address});26      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27    }28  }2930  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32  }3334  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35    return encodeAddress(decodeAddress(address), ss58Format);36  }3738  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40  }41  42  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44    return this;45  }4647  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49  }5051  toEthereum(): CrossAccountId {52    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53    return this;54  }5556  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57    return evmToAddress(address, ss58Format);58  }5960  toSubstrate(ss58Format?: number): CrossAccountId {61    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62    return this;63  }64  65  toLowerCase(): CrossAccountId {66    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68    return this;69  }70}7172const nesting = {73  toChecksumAddress(address: string): string {74    if (typeof address === 'undefined') return '';7576    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778    address = address.toLowerCase().replace(/^0x/i,'');79    const addressHash = keccakAsHex(address).replace(/^0x/i,'');80    const checksumAddress = ['0x'];8182    for (let i = 0; i < address.length; i++) {83      // If ith character is 8 to f then make it uppercase84      if (parseInt(addressHash[i], 16) > 7) {85        checksumAddress.push(address[i].toUpperCase());86      } else {87        checksumAddress.push(address[i]);88      }89    }90    return checksumAddress.join('');91  },92  tokenIdToAddress(collectionId: number, tokenId: number) {93    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);94  },95};9697class UniqueUtil {98  static transactionStatus = {99    NOT_READY: 'NotReady',100    FAIL: 'Fail',101    SUCCESS: 'Success',102  };103104  static chainLogType = {105    EXTRINSIC: 'extrinsic',106    RPC: 'rpc',107  };108109  static getTokenAccount(token: IToken): CrossAccountId {110    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111  }112113  static getTokenAddress(token: IToken): string {114    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115  }116117  static getDefaultLogger(): ILogger {118    return {119      log(msg: any, level = 'INFO') {120        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121      },122      level: {123        ERROR: 'ERROR',124        WARNING: 'WARNING',125        INFO: 'INFO',126      },127    };128  }129130  static vec2str(arr: string[] | number[]) {131    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132  }133134  static str2vec(string: string) {135    if (typeof string !== 'string') return string;136    return Array.from(string).map(x => x.charCodeAt(0));137  }138139  static fromSeed(seed: string, ss58Format = 42) {140    const keyring = new Keyring({type: 'sr25519', ss58Format});141    return keyring.addFromUri(seed);142  }143144  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145    if (creationResult.status !== this.transactionStatus.SUCCESS) {146      throw Error('Unable to create collection!');147    }148149    let collectionId = null;150    creationResult.result.events.forEach(({event: {data, method, section}}) => {151      if ((section === 'common') && (method === 'CollectionCreated')) {152        collectionId = parseInt(data[0].toString(), 10);153      }154    });155156    if (collectionId === null) {157      throw Error('No CollectionCreated event was found!');158    }159160    return collectionId;161  }162163  static extractTokensFromCreationResult(creationResult: ITransactionResult): {164    success: boolean, 165    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166  } {167    if (creationResult.status !== this.transactionStatus.SUCCESS) {168      throw Error('Unable to create tokens!');169    }170    let success = false;171    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172    creationResult.result.events.forEach(({event: {data, method, section}}) => {173      if (method === 'ExtrinsicSuccess') {174        success = true;175      } else if ((section === 'common') && (method === 'ItemCreated')) {176        tokens.push({177          collectionId: parseInt(data[0].toString(), 10),178          tokenId: parseInt(data[1].toString(), 10),179          owner: data[2].toHuman(),180          amount: data[3].toBigInt(),181        });182      }183    });184    return {success, tokens};185  }186187  static extractTokensFromBurnResult(burnResult: ITransactionResult): {188    success: boolean, 189    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190  } {191    if (burnResult.status !== this.transactionStatus.SUCCESS) {192      throw Error('Unable to burn tokens!');193    }194    let success = false;195    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196    burnResult.result.events.forEach(({event: {data, method, section}}) => {197      if (method === 'ExtrinsicSuccess') {198        success = true;199      } else if ((section === 'common') && (method === 'ItemDestroyed')) {200        tokens.push({201          collectionId: parseInt(data[0].toString(), 10),202          tokenId: parseInt(data[1].toString(), 10),203          owner: data[2].toHuman(),204          amount: data[3].toBigInt(),205        });206      }207    });208    return {success, tokens};209  }210211  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212    let eventId = null;213    events.forEach(({event: {data, method, section}}) => {214      if ((section === expectedSection) && (method === expectedMethod)) {215        eventId = parseInt(data[0].toString(), 10);216      }217    });218219    if (eventId === null) {220      throw Error(`No ${expectedMethod} event was found!`);221    }222    return eventId === collectionId;223  }224225  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226    const normalizeAddress = (address: string | ICrossAccountId) => {227      if(typeof address === 'string') return address;228      const obj = {} as any;229      Object.keys(address).forEach(k => {230        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231      });232      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234      return address;235    };236    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237    events.forEach(({event: {data, method, section}}) => {238      if ((section === 'common') && (method === 'Transfer')) {239        const hData = (data as any).toJSON();240        transfer = {241          collectionId: hData[0],242          tokenId: hData[1],243          from: normalizeAddress(hData[2]),244          to: normalizeAddress(hData[3]),245          amount: BigInt(hData[4]),246        };247      }248    });249    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252    isSuccess = isSuccess && amount === transfer.amount;253    return isSuccess;254  }255256  static bigIntToDecimals(number: bigint, decimals = 18) {257    const numberStr = number.toString();258    const dotPos = numberStr.length - decimals;259  260    if (dotPos <= 0) {261      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;262    } else {263      const intPart = numberStr.substring(0, dotPos);264      const fractPart = numberStr.substring(dotPos);265      return intPart + '.' + fractPart;266    }267  }268}269270class UniqueEventHelper {271  private static extractIndex(index: any): [number, number] | string {272    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];273    return index.toJSON();274  }275276  private static extractSub(data: any, subTypes: any): {[key: string]: any} {277    let obj: any = {};278    let index = 0;279280    if (data.entries) {281      for(const [key, value] of data.entries()) {282        obj[key] = this.extractData(value, subTypes[index]);283        index++;284      }285    } else obj = data.toJSON();286287    return obj;288  }289  290  private static extractData(data: any, type: any): any {291    if(!type) return data.toHuman();292    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();293    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();294    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);295    return data.toHuman();296  }297298  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {299    const parsedEvents: IEvent[] = [];300301    events.forEach((record) => {302      const {event, phase} = record;303      const types = event.typeDef;304305      const eventData: IEvent = {306        section: event.section.toString(),307        method: event.method.toString(),308        index: this.extractIndex(event.index),309        data: [],310        phase: phase.toJSON(),311      };312313      event.data.forEach((val: any, index: number) => {314        eventData.data.push(this.extractData(val, types[index]));315      });316317      parsedEvents.push(eventData);318    });319320    return parsedEvents;321  }322}323324export class ChainHelperBase {325  helperBase: any;326327  transactionStatus = UniqueUtil.transactionStatus;328  chainLogType = UniqueUtil.chainLogType;329  util: typeof UniqueUtil;330  eventHelper: typeof UniqueEventHelper;331  logger: ILogger;332  api: ApiPromise | null;333  forcedNetwork: TNetworks | null;334  network: TNetworks | null;335  chainLog: IUniqueHelperLog[];336  children: ChainHelperBase[];337  address: AddressGroup;338  chain: ChainGroup;339340  constructor(logger?: ILogger, helperBase?: any) {341    this.helperBase = helperBase;342343    this.util = UniqueUtil;344    this.eventHelper = UniqueEventHelper;345    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();346    this.logger = logger;347    this.api = null;348    this.forcedNetwork = null;349    this.network = null;350    this.chainLog = [];351    this.children = [];352    this.address = new AddressGroup(this);353    this.chain = new ChainGroup(this);354  }355356  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {357    Object.setPrototypeOf(helperCls.prototype, this);358    const newHelper = new helperCls(this.logger, options);359360    newHelper.api = this.api;361    newHelper.network = this.network;362    newHelper.forceNetwork = this.forceNetwork;363364    this.children.push(newHelper);365366    return newHelper;367  }368369  getApi(): ApiPromise {370    if(this.api === null) throw Error('API not initialized');371    return this.api;372  }373374  clearChainLog(): void {375    this.chainLog = [];376  }377378  forceNetwork(value: TNetworks): void {379    this.forcedNetwork = value;380  }381382  async connect(wsEndpoint: string, listeners?: IApiListeners) {383    if (this.api !== null) throw Error('Already connected');384    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);385    this.api = api;386    this.network = network;387  }388389  async disconnect() {390    for (const child of this.children) {391      child.clearApi();392    }393394    if (this.api === null) return;395    await this.api.disconnect();396    this.clearApi();397  }398399  clearApi() {400    this.api = null;401    this.network = null;402  }403404  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {405    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;406    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];407408    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;409410    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;411    return 'opal';412  }413414  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {415    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});416    await api.isReady;417418    const network = await this.detectNetwork(api);419420    await api.disconnect();421422    return network;423  }424425  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{426    api: ApiPromise;427    network: TNetworks;428  }> {429    if(typeof network === 'undefined' || network === null) network = 'opal';430    const supportedRPC = {431      opal: {432        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,433      },434      quartz: {435        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,436      },437      unique: {438        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,439      },440      rococo: {},441      westend: {},442      moonbeam: {},443      moonriver: {},444      acala: {},445      karura: {},446      westmint: {},447    };448    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);449    const rpc = supportedRPC[network];450451    // TODO: investigate how to replace rpc in runtime452    // api._rpcCore.addUserInterfaces(rpc);453454    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});455456    await api.isReadyOrError;457458    if (typeof listeners === 'undefined') listeners = {};459    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {460      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;461      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);462    }463464    return {api, network};465  }466467  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {468    const {events, status} = data;469    if (status.isReady) {470      return this.transactionStatus.NOT_READY;471    }472    if (status.isBroadcast) {473      return this.transactionStatus.NOT_READY;474    }475    if (status.isInBlock || status.isFinalized) {476      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');477      if (errors.length > 0) {478        return this.transactionStatus.FAIL;479      }480      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {481        return this.transactionStatus.SUCCESS;482      }483    }484485    return this.transactionStatus.FAIL;486  }487488  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {489    const sign = (callback: any) => {490      if(options !== null) return transaction.signAndSend(sender, options, callback);491      return transaction.signAndSend(sender, callback);492    };493    // eslint-disable-next-line no-async-promise-executor494    return new Promise(async (resolve, reject) => {495      try {496        const unsub = await sign((result: any) => {497          const status = this.getTransactionStatus(result);498499          if (status === this.transactionStatus.SUCCESS) {500            this.logger.log(`${label} successful`);501            unsub();502            resolve({result, status});503          } else if (status === this.transactionStatus.FAIL) {504            let moduleError = null;505506            if (result.hasOwnProperty('dispatchError')) {507              const dispatchError = result['dispatchError'];508509              if (dispatchError) {510                if (dispatchError.isModule) {511                  const modErr = dispatchError.asModule;512                  const errorMeta = dispatchError.registry.findMetaError(modErr);513514                  moduleError = `${errorMeta.section}.${errorMeta.name}`;515                } else {516                  moduleError = dispatchError.toHuman();517                }518              } else {519                this.logger.log(result, this.logger.level.ERROR);520              }521            }522523            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);524            unsub();525            reject({status, moduleError, result});526          }527        });528      } catch (e) {529        this.logger.log(e, this.logger.level.ERROR);530        reject(e);531      }532    });533  }534535  constructApiCall(apiCall: string, params: any[]) {536    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);537    let call = this.getApi() as any;538    for(const part of apiCall.slice(4).split('.')) {539      call = call[part];540    }541    return call(...params);542  }543544  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {545    if(this.api === null) throw Error('API not initialized');546    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);547548    const startTime = (new Date()).getTime();549    let result: ITransactionResult;550    let events: IEvent[] = [];551    try {552      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;553      events = this.eventHelper.extractEvents(result.result.events);554    }555    catch(e) {556      if(!(e as object).hasOwnProperty('status')) throw e;557      result = e as ITransactionResult;558    }559560    const endTime = (new Date()).getTime();561562    const log = {563      executedAt: endTime,564      executionTime: endTime - startTime,565      type: this.chainLogType.EXTRINSIC,566      status: result.status,567      call: extrinsic,568      signer: this.getSignerAddress(sender),569      params,570    } as IUniqueHelperLog;571572    if(result.status !== this.transactionStatus.SUCCESS) {573      if (result.moduleError) log.moduleError = result.moduleError;574      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;575    }576    if(events.length > 0) log.events = events;577578    this.chainLog.push(log);579580    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {581      if (result.moduleError) throw Error(`${result.moduleError}`);582      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));583    }584    return result;585  }586587  async callRpc(rpc: string, params?: any[]) {588    if(typeof params === 'undefined') params = [];589    if(this.api === null) throw Error('API not initialized');590    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);591592    const startTime = (new Date()).getTime();593    let result;594    let error = null;595    const log = {596      type: this.chainLogType.RPC,597      call: rpc,598      params,599    } as IUniqueHelperLog;600601    try {602      result = await this.constructApiCall(rpc, params);603    }604    catch(e) {605      error = e;606    }607608    const endTime = (new Date()).getTime();609610    log.executedAt = endTime;611    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';612    log.executionTime = endTime - startTime;613614    this.chainLog.push(log);615616    if(error !== null) throw error;617618    return result;619  }620621  getSignerAddress(signer: IKeyringPair | string): string {622    if(typeof signer === 'string') return signer;623    return signer.address;624  }625626  fetchAllPalletNames(): string[] {627    if(this.api === null) throw Error('API not initialized');628    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());629  }630631  fetchMissingPalletNames(requiredPallets: string[]): string[] {632    const palletNames = this.fetchAllPalletNames();633    return requiredPallets.filter(p => !palletNames.includes(p));634  }635}636637638class HelperGroup<T extends ChainHelperBase> {639  helper: T;640641  constructor(uniqueHelper: T) {642    this.helper = uniqueHelper;643  }644}645646647class CollectionGroup extends HelperGroup<UniqueHelper> {648  /**649 * Get number of blocks when sponsored transaction is available.650 *651 * @param collectionId ID of collection652 * @param tokenId ID of token653 * @param addressObj address for which the sponsorship is checked654 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});655 * @returns number of blocks or null if sponsorship hasn't been set656 */657  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {658    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();659  }660661  /**662   * Get the number of created collections.663   *664   * @returns number of created collections665   */666  async getTotalCount(): Promise<number> {667    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();668  }669670  /**671   * Get information about the collection with additional data,672   * including the number of tokens it contains, its administrators,673   * the normalized address of the collection's owner, and decoded name and description.674   *675   * @param collectionId ID of collection676   * @example await getData(2)677   * @returns collection information object678   */679  async getData(collectionId: number): Promise<{680    id: number;681    name: string;682    description: string;683    tokensCount: number;684    admins: CrossAccountId[];685    normalizedOwner: TSubstrateAccount;686    raw: any687  } | null> {688    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);689    const humanCollection = collection.toHuman(), collectionData = {690      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],691      raw: humanCollection,692    } as any, jsonCollection = collection.toJSON();693    if (humanCollection === null) return null;694    collectionData.raw.limits = jsonCollection.limits;695    collectionData.raw.permissions = jsonCollection.permissions;696    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);697    for (const key of ['name', 'description']) {698      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);699    }700701    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))702      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)703      : 0;704    collectionData.admins = await this.getAdmins(collectionId);705706    return collectionData;707  }708709  /**710   * Get the addresses of the collection's administrators, optionally normalized.711   *712   * @param collectionId ID of collection713   * @param normalize whether to normalize the addresses to the default ss58 format714   * @example await getAdmins(1)715   * @returns array of administrators716   */717  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {718    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();719720    return normalize721      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())722      : admins;723  }724725  /**726   * Get the addresses added to the collection allow-list, optionally normalized.727   * @param collectionId ID of collection728   * @param normalize whether to normalize the addresses to the default ss58 format729   * @example await getAllowList(1)730   * @returns array of allow-listed addresses731   */732  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {733    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();734    return normalize735      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())736      : allowListed;737  }738739  /**740   * Get the effective limits of the collection instead of null for default values741   *742   * @param collectionId ID of collection743   * @example await getEffectiveLimits(2)744   * @returns object of collection limits745   */746  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {747    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();748  }749750  /**751   * Burns the collection if the signer has sufficient permissions and collection is empty.752   *753   * @param signer keyring of signer754   * @param collectionId ID of collection755   * @example await helper.collection.burn(aliceKeyring, 3);756   * @returns ```true``` if extrinsic success, otherwise ```false```757   */758  async burn(signer: TSigner, collectionId: number): Promise<boolean> {759    const result = await this.helper.executeExtrinsic(760      signer,761      'api.tx.unique.destroyCollection', [collectionId],762      true,763    );764765    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');766  }767768  /**769   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.770   *771   * @param signer keyring of signer772   * @param collectionId ID of collection773   * @param sponsorAddress Sponsor substrate address774   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")775   * @returns ```true``` if extrinsic success, otherwise ```false```776   */777  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {778    const result = await this.helper.executeExtrinsic(779      signer,780      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],781      true,782    );783784    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');785  }786787  /**788   * Confirms consent to sponsor the collection on behalf of the signer.789   *790   * @param signer keyring of signer791   * @param collectionId ID of collection792   * @example confirmSponsorship(aliceKeyring, 10)793   * @returns ```true``` if extrinsic success, otherwise ```false```794   */795  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {796    const result = await this.helper.executeExtrinsic(797      signer,798      'api.tx.unique.confirmSponsorship', [collectionId],799      true,800    );801802    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');803  }804805  /**806   * Removes the sponsor of a collection, regardless if it consented or not.807   *808   * @param signer keyring of signer809   * @param collectionId ID of collection810   * @example removeSponsor(aliceKeyring, 10)811   * @returns ```true``` if extrinsic success, otherwise ```false```812   */813  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {814    const result = await this.helper.executeExtrinsic(815      signer,816      'api.tx.unique.removeCollectionSponsor', [collectionId],817      true,818    );819820    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');821  }822823  /**824   * Sets the limits of the collection. At least one limit must be specified for a correct call.825   *826   * @param signer keyring of signer827   * @param collectionId ID of collection828   * @param limits collection limits object829   * @example830   * await setLimits(831   *   aliceKeyring,832   *   10,833   *   {834   *     sponsorTransferTimeout: 0,835   *     ownerCanDestroy: false836   *   }837   * )838   * @returns ```true``` if extrinsic success, otherwise ```false```839   */840  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {841    const result = await this.helper.executeExtrinsic(842      signer,843      'api.tx.unique.setCollectionLimits', [collectionId, limits],844      true,845    );846847    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');848  }849850  /**851   * Changes the owner of the collection to the new Substrate address.852   *853   * @param signer keyring of signer854   * @param collectionId ID of collection855   * @param ownerAddress substrate address of new owner856   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")857   * @returns ```true``` if extrinsic success, otherwise ```false```858   */859  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {860    const result = await this.helper.executeExtrinsic(861      signer,862      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],863      true,864    );865866    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');867  }868869  /**870   * Adds a collection administrator.871   *872   * @param signer keyring of signer873   * @param collectionId ID of collection874   * @param adminAddressObj Administrator address (substrate or ethereum)875   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})876   * @returns ```true``` if extrinsic success, otherwise ```false```877   */878  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {879    const result = await this.helper.executeExtrinsic(880      signer,881      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],882      true,883    );884885    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');886  }887888  /**889   * Removes a collection administrator.890   *891   * @param signer keyring of signer892   * @param collectionId ID of collection893   * @param adminAddressObj Administrator address (substrate or ethereum)894   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})895   * @returns ```true``` if extrinsic success, otherwise ```false```896   */897  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {898    const result = await this.helper.executeExtrinsic(899      signer,900      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],901      true,902    );903904    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');905  }906907  /**908   * Check if user is in allow list.909   * 910   * @param collectionId ID of collection911   * @param user Account to check912   * @example await getAdmins(1)913   * @returns is user in allow list914   */915  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {916    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();917  }918919  /**920   * Adds an address to allow list921   * @param signer keyring of signer922   * @param collectionId ID of collection923   * @param addressObj address to add to the allow list924   * @returns ```true``` if extrinsic success, otherwise ```false```925   */926  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {927    const result = await this.helper.executeExtrinsic(928      signer,929      'api.tx.unique.addToAllowList', [collectionId, addressObj],930      true,931    );932933    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');934  }935936  /**937   * Removes an address from allow list938   *939   * @param signer keyring of signer940   * @param collectionId ID of collection941   * @param addressObj address to remove from the allow list942   * @returns ```true``` if extrinsic success, otherwise ```false```943   */944  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {945    const result = await this.helper.executeExtrinsic(946      signer,947      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],948      true,949    );950951    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');952  }953954  /**955   * Sets onchain permissions for selected collection.956   *957   * @param signer keyring of signer958   * @param collectionId ID of collection959   * @param permissions collection permissions object960   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});961   * @returns ```true``` if extrinsic success, otherwise ```false```962   */963  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {964    const result = await this.helper.executeExtrinsic(965      signer,966      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],967      true,968    );969970    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');971  }972973  /**974   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.975   *976   * @param signer keyring of signer977   * @param collectionId ID of collection978   * @param permissions nesting permissions object979   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});980   * @returns ```true``` if extrinsic success, otherwise ```false```981   */982  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {983    return await this.setPermissions(signer, collectionId, {nesting: permissions});984  }985986  /**987   * Disables nesting for selected collection.988   *989   * @param signer keyring of signer990   * @param collectionId ID of collection991   * @example disableNesting(aliceKeyring, 10);992   * @returns ```true``` if extrinsic success, otherwise ```false```993   */994  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {995    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});996  }997998  /**999   * Sets onchain properties to the collection.1000   *1001   * @param signer keyring of signer1002   * @param collectionId ID of collection1003   * @param properties array of property objects1004   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1005   * @returns ```true``` if extrinsic success, otherwise ```false```1006   */1007  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1008    const result = await this.helper.executeExtrinsic(1009      signer,1010      'api.tx.unique.setCollectionProperties', [collectionId, properties],1011      true,1012    );10131014    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1015  }10161017  /**1018   * Get collection properties.1019   * 1020   * @param collectionId ID of collection1021   * @param propertyKeys optionally filter the returned properties to only these keys1022   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1023   * @returns array of key-value pairs1024   */1025  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1026    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1027  }10281029  /**1030   * Deletes onchain properties from the collection.1031   *1032   * @param signer keyring of signer1033   * @param collectionId ID of collection1034   * @param propertyKeys array of property keys to delete1035   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1036   * @returns ```true``` if extrinsic success, otherwise ```false```1037   */1038  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1039    const result = await this.helper.executeExtrinsic(1040      signer,1041      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1042      true,1043    );10441045    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1046  }10471048  /**1049   * Changes the owner of the token.1050   *1051   * @param signer keyring of signer1052   * @param collectionId ID of collection1053   * @param tokenId ID of token1054   * @param addressObj address of a new owner1055   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1056   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1057   * @returns true if the token success, otherwise false1058   */1059  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1060    const result = await this.helper.executeExtrinsic(1061      signer,1062      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1063      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1064    );10651066    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1067  }10681069  /**1070   *1071   * Change ownership of a token(s) on behalf of the owner.1072   *1073   * @param signer keyring of signer1074   * @param collectionId ID of collection1075   * @param tokenId ID of token1076   * @param fromAddressObj address on behalf of which the token will be sent1077   * @param toAddressObj new token owner1078   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1079   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1080   * @returns true if the token success, otherwise false1081   */1082  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1083    const result = await this.helper.executeExtrinsic(1084      signer,1085      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1086      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1087    );1088    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1089  }10901091  /**1092   *1093   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1094   *1095   * @param signer keyring of signer1096   * @param collectionId ID of collection1097   * @param tokenId ID of token1098   * @param amount amount of tokens to be burned. For NFT must be set to 1n1099   * @example burnToken(aliceKeyring, 10, 5);1100   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1101   */1102  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1103    const burnResult = await this.helper.executeExtrinsic(1104      signer,1105      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1106      true, // `Unable to burn token for ${label}`,1107    );1108    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1109    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1110    return burnedTokens.success;1111  }11121113  /**1114   * Destroys a concrete instance of NFT on behalf of the owner1115   *1116   * @param signer keyring of signer1117   * @param collectionId ID of collection1118   * @param tokenId ID of token1119   * @param fromAddressObj address on behalf of which the token will be burnt1120   * @param amount amount of tokens to be burned. For NFT must be set to 1n1121   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1122   * @returns ```true``` if extrinsic success, otherwise ```false```1123   */1124  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1125    const burnResult = await this.helper.executeExtrinsic(1126      signer,1127      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1128      true, // `Unable to burn token from for ${label}`,1129    );1130    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1131    return burnedTokens.success && burnedTokens.tokens.length > 0;1132  }11331134  /**1135   * Set, change, or remove approved address to transfer the ownership of the NFT.1136   *1137   * @param signer keyring of signer1138   * @param collectionId ID of collection1139   * @param tokenId ID of token1140   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1141   * @param amount amount of token to be approved. For NFT must be set to 1n1142   * @returns ```true``` if extrinsic success, otherwise ```false```1143   */1144  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1145    const approveResult = await this.helper.executeExtrinsic(1146      signer,1147      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1148      true, // `Unable to approve token for ${label}`,1149    );11501151    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1152  }11531154  /**1155   * Get the amount of token pieces approved to transfer or burn. Normally 0.1156   *1157   * @param collectionId ID of collection1158   * @param tokenId ID of token1159   * @param toAccountObj address which is approved to use token pieces1160   * @param fromAccountObj address which may have allowed the use of its owned tokens1161   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1162   * @returns number of approved to transfer pieces1163   */1164  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1165    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1166  }11671168  /**1169   * Get the last created token ID in a collection1170   *1171   * @param collectionId ID of collection1172   * @example getLastTokenId(10);1173   * @returns id of the last created token1174   */1175  async getLastTokenId(collectionId: number): Promise<number> {1176    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1177  }11781179  /**1180   * Check if token exists1181   *1182   * @param collectionId ID of collection1183   * @param tokenId ID of token1184   * @example doesTokenExist(10, 20);1185   * @returns true if the token exists, otherwise false1186   */1187  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1188    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1189  }1190}11911192class NFTnRFT extends CollectionGroup {1193  /**1194   * Get tokens owned by account1195   *1196   * @param collectionId ID of collection1197   * @param addressObj tokens owner1198   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1199   * @returns array of token ids owned by account1200   */1201  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1202    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1203  }12041205  /**1206   * Get token data1207   *1208   * @param collectionId ID of collection1209   * @param tokenId ID of token1210   * @param propertyKeys optionally filter the token properties to only these keys1211   * @param blockHashAt optionally query the data at some block with this hash1212   * @example getToken(10, 5);1213   * @returns human readable token data1214   */1215  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1216    properties: IProperty[];1217    owner: CrossAccountId;1218    normalizedOwner: CrossAccountId;1219  }| null> {1220    let tokenData;1221    if(typeof blockHashAt === 'undefined') {1222      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1223    }1224    else {1225      if(propertyKeys.length == 0) {1226        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1227        if(!collection) return null;1228        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1229      }1230      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1231    }1232    tokenData = tokenData.toHuman();1233    if (tokenData === null || tokenData.owner === null) return null;1234    const owner = {} as any;1235    for (const key of Object.keys(tokenData.owner)) {1236      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1237        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1238        : tokenData.owner[key];1239    }1240    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1241    return tokenData;1242  }12431244  /**1245   * Set permissions to change token properties1246   *1247   * @param signer keyring of signer1248   * @param collectionId ID of collection1249   * @param permissions permissions to change a property by the collection admin or token owner1250   * @example setTokenPropertyPermissions(1251   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1252   * )1253   * @returns true if extrinsic success otherwise false1254   */1255  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1256    const result = await this.helper.executeExtrinsic(1257      signer,1258      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1259      true,1260    );12611262    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1263  }12641265  /**1266   * Get token property permissions.1267   * 1268   * @param collectionId ID of collection1269   * @param propertyKeys optionally filter the returned property permissions to only these keys1270   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1271   * @returns array of key-permission pairs1272   */1273  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1274    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1275  }12761277  /**1278   * Set token properties1279   *1280   * @param signer keyring of signer1281   * @param collectionId ID of collection1282   * @param tokenId ID of token1283   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1284   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1285   * @returns ```true``` if extrinsic success, otherwise ```false```1286   */1287  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1288    const result = await this.helper.executeExtrinsic(1289      signer,1290      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1291      true,1292    );12931294    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1295  }12961297  /**1298   * Get properties, metadata assigned to a token.1299   * 1300   * @param collectionId ID of collection1301   * @param tokenId ID of token1302   * @param propertyKeys optionally filter the returned properties to only these keys1303   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1304   * @returns array of key-value pairs1305   */1306  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1307    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1308  }13091310  /**1311   * Delete the provided properties of a token1312   * @param signer keyring of signer1313   * @param collectionId ID of collection1314   * @param tokenId ID of token1315   * @param propertyKeys property keys to be deleted1316   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1317   * @returns ```true``` if extrinsic success, otherwise ```false```1318   */1319  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1320    const result = await this.helper.executeExtrinsic(1321      signer,1322      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1323      true,1324    );13251326    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1327  }13281329  /**1330   * Mint new collection1331   *1332   * @param signer keyring of signer1333   * @param collectionOptions basic collection options and properties1334   * @param mode NFT or RFT type of a collection1335   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1336   * @returns object of the created collection1337   */1338  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1339    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1340    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1341    for (const key of ['name', 'description', 'tokenPrefix']) {1342      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);1343    }1344    const creationResult = await this.helper.executeExtrinsic(1345      signer,1346      'api.tx.unique.createCollectionEx', [collectionOptions],1347      true, // errorLabel,1348    );1349    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1350  }13511352  getCollectionObject(_collectionId: number): any {1353    return null;1354  }13551356  getTokenObject(_collectionId: number, _tokenId: number): any {1357    return null;1358  }1359}136013611362class NFTGroup extends NFTnRFT {1363  /**1364   * Get collection object1365   * @param collectionId ID of collection1366   * @example getCollectionObject(2);1367   * @returns instance of UniqueNFTCollection1368   */1369  getCollectionObject(collectionId: number): UniqueNFTCollection {1370    return new UniqueNFTCollection(collectionId, this.helper);1371  }13721373  /**1374   * Get token object1375   * @param collectionId ID of collection1376   * @param tokenId ID of token1377   * @example getTokenObject(10, 5);1378   * @returns instance of UniqueNFTToken1379   */1380  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1381    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1382  }13831384  /**1385   * Get token's owner1386   * @param collectionId ID of collection1387   * @param tokenId ID of token1388   * @param blockHashAt optionally query the data at the block with this hash1389   * @example getTokenOwner(10, 5);1390   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1391   */1392  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1393    let owner;1394    if (typeof blockHashAt === 'undefined') {1395      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1396    } else {1397      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1398    }1399    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1400  }14011402  /**1403   * Is token approved to transfer1404   * @param collectionId ID of collection1405   * @param tokenId ID of token1406   * @param toAccountObj address to be approved1407   * @returns ```true``` if extrinsic success, otherwise ```false```1408   */1409  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1410    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1411  }14121413  /**1414   * Changes the owner of the token.1415   *1416   * @param signer keyring of signer1417   * @param collectionId ID of collection1418   * @param tokenId ID of token1419   * @param addressObj address of a new owner1420   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1421   * @returns ```true``` if extrinsic success, otherwise ```false```1422   */1423  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1424    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1425  }14261427  /**1428   *1429   * Change ownership of a NFT on behalf of the owner.1430   *1431   * @param signer keyring of signer1432   * @param collectionId ID of collection1433   * @param tokenId ID of token1434   * @param fromAddressObj address on behalf of which the token will be sent1435   * @param toAddressObj new token owner1436   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1437   * @returns ```true``` if extrinsic success, otherwise ```false```1438   */1439  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1440    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1441  }14421443  /**1444   * Recursively find the address that owns the token1445   * @param collectionId ID of collection1446   * @param tokenId ID of token1447   * @param blockHashAt1448   * @example getTokenTopmostOwner(10, 5);1449   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1450   */1451  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1452    let owner;1453    if (typeof blockHashAt === 'undefined') {1454      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1455    } else {1456      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1457    }14581459    if (owner === null) return null;14601461    return owner.toHuman();1462  }14631464  /**1465   * Get tokens nested in the provided token1466   * @param collectionId ID of collection1467   * @param tokenId ID of token1468   * @param blockHashAt optionally query the data at the block with this hash1469   * @example getTokenChildren(10, 5);1470   * @returns tokens whose depth of nesting is <= 51471   */1472  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1473    let children;1474    if(typeof blockHashAt === 'undefined') {1475      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1476    } else {1477      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1478    }14791480    return children.toJSON().map((x: any) => {1481      return {collectionId: x.collection, tokenId: x.token};1482    });1483  }14841485  /**1486   * Nest one token into another1487   * @param signer keyring of signer1488   * @param tokenObj token to be nested1489   * @param rootTokenObj token to be parent1490   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1491   * @returns ```true``` if extrinsic success, otherwise ```false```1492   */1493  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1494    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1495    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1496    if(!result) {1497      throw Error('Unable to nest token!');1498    }1499    return result;1500  }15011502  /**1503   * Remove token from nested state1504   * @param signer keyring of signer1505   * @param tokenObj token to unnest1506   * @param rootTokenObj parent of a token1507   * @param toAddressObj address of a new token owner1508   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1509   * @returns ```true``` if extrinsic success, otherwise ```false```1510   */1511  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1512    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1513    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1514    if(!result) {1515      throw Error('Unable to unnest token!');1516    }1517    return result;1518  }15191520  /**1521   * Mint new collection1522   * @param signer keyring of signer1523   * @param collectionOptions Collection options1524   * @example1525   * mintCollection(aliceKeyring, {1526   *   name: 'New',1527   *   description: 'New collection',1528   *   tokenPrefix: 'NEW',1529   * })1530   * @returns object of the created collection1531   */1532  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1533    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1534  }15351536  /**1537   * Mint new token1538   * @param signer keyring of signer1539   * @param data token data1540   * @returns created token object1541   */1542  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1543    const creationResult = await this.helper.executeExtrinsic(1544      signer,1545      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1546        nft: {1547          properties: data.properties,1548        },1549      }],1550      true,1551    );1552    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1553    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1554    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1555    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1556  }15571558  /**1559   * Mint multiple NFT tokens1560   * @param signer keyring of signer1561   * @param collectionId ID of collection1562   * @param tokens array of tokens with owner and properties1563   * @example1564   * mintMultipleTokens(aliceKeyring, 10, [{1565   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1566   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1567   *   },{1568   *     owner: {Ethereum: "0x9F0583DbB855d..."},1569   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1570   * }]);1571   * @returns ```true``` if extrinsic success, otherwise ```false```1572   */1573  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1574    const creationResult = await this.helper.executeExtrinsic(1575      signer,1576      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1577      true,1578    );1579    const collection = this.getCollectionObject(collectionId);1580    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1581  }15821583  /**1584   * Mint multiple NFT tokens with one owner1585   * @param signer keyring of signer1586   * @param collectionId ID of collection1587   * @param owner tokens owner1588   * @param tokens array of tokens with owner and properties1589   * @example1590   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1591   *   properties: [{1592   *   key: "gender",1593   *   value: "female",1594   *  },{1595   *   key: "age",1596   *   value: "33",1597   *  }],1598   * }]);1599   * @returns array of newly created tokens1600   */1601  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1602    const rawTokens = [];1603    for (const token of tokens) {1604      const raw = {NFT: {properties: token.properties}};1605      rawTokens.push(raw);1606    }1607    const creationResult = await this.helper.executeExtrinsic(1608      signer,1609      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1610      true,1611    );1612    const collection = this.getCollectionObject(collectionId);1613    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1614  }16151616  /**1617   * Set, change, or remove approved address to transfer the ownership of the NFT.1618   *1619   * @param signer keyring of signer1620   * @param collectionId ID of collection1621   * @param tokenId ID of token1622   * @param toAddressObj address to approve1623   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1624   * @returns ```true``` if extrinsic success, otherwise ```false```1625   */1626  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1627    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1628  }1629}163016311632class RFTGroup extends NFTnRFT {1633  /**1634   * Get collection object1635   * @param collectionId ID of collection1636   * @example getCollectionObject(2);1637   * @returns instance of UniqueRFTCollection1638   */1639  getCollectionObject(collectionId: number): UniqueRFTCollection {1640    return new UniqueRFTCollection(collectionId, this.helper);1641  }16421643  /**1644   * Get token object1645   * @param collectionId ID of collection1646   * @param tokenId ID of token1647   * @example getTokenObject(10, 5);1648   * @returns instance of UniqueNFTToken1649   */1650  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1651    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1652  }16531654  /**1655   * Get top 10 token owners with the largest number of pieces1656   * @param collectionId ID of collection1657   * @param tokenId ID of token1658   * @example getTokenTop10Owners(10, 5);1659   * @returns array of top 10 owners1660   */1661  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1662    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1663  }16641665  /**1666   * Get number of pieces owned by address1667   * @param collectionId ID of collection1668   * @param tokenId ID of token1669   * @param addressObj address token owner1670   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1671   * @returns number of pieces ownerd by address1672   */1673  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1674    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1675  }16761677  /**1678   * Transfer pieces of token to another address1679   * @param signer keyring of signer1680   * @param collectionId ID of collection1681   * @param tokenId ID of token1682   * @param addressObj address of a new owner1683   * @param amount number of pieces to be transfered1684   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1685   * @returns ```true``` if extrinsic success, otherwise ```false```1686   */1687  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1688    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1689  }16901691  /**1692   * Change ownership of some pieces of RFT on behalf of the owner.1693   * @param signer keyring of signer1694   * @param collectionId ID of collection1695   * @param tokenId ID of token1696   * @param fromAddressObj address on behalf of which the token will be sent1697   * @param toAddressObj new token owner1698   * @param amount number of pieces to be transfered1699   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1700   * @returns ```true``` if extrinsic success, otherwise ```false```1701   */1702  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1703    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1704  }17051706  /**1707   * Mint new collection1708   * @param signer keyring of signer1709   * @param collectionOptions Collection options1710   * @example1711   * mintCollection(aliceKeyring, {1712   *   name: 'New',1713   *   description: 'New collection',1714   *   tokenPrefix: 'NEW',1715   * })1716   * @returns object of the created collection1717   */1718  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1719    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1720  }17211722  /**1723   * Mint new token1724   * @param signer keyring of signer1725   * @param data token data1726   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1727   * @returns created token object1728   */1729  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1730    const creationResult = await this.helper.executeExtrinsic(1731      signer,1732      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1733        refungible: {1734          pieces: data.pieces,1735          properties: data.properties,1736        },1737      }],1738      true,1739    );1740    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1741    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1742    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1743    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1744  }17451746  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1747    throw Error('Not implemented');1748    const creationResult = await this.helper.executeExtrinsic(1749      signer,1750      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1751      true, // `Unable to mint RFT tokens for ${label}`,1752    );1753    const collection = this.getCollectionObject(collectionId);1754    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1755  }17561757  /**1758   * Mint multiple RFT tokens with one owner1759   * @param signer keyring of signer1760   * @param collectionId ID of collection1761   * @param owner tokens owner1762   * @param tokens array of tokens with properties and pieces1763   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1764   * @returns array of newly created RFT tokens1765   */1766  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1767    const rawTokens = [];1768    for (const token of tokens) {1769      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1770      rawTokens.push(raw);1771    }1772    const creationResult = await this.helper.executeExtrinsic(1773      signer,1774      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1775      true,1776    );1777    const collection = this.getCollectionObject(collectionId);1778    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1779  }17801781  /**1782   * Destroys a concrete instance of RFT.1783   * @param signer keyring of signer1784   * @param collectionId ID of collection1785   * @param tokenId ID of token1786   * @param amount number of pieces to be burnt1787   * @example burnToken(aliceKeyring, 10, 5);1788   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1789   */1790  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1791    return await super.burnToken(signer, collectionId, tokenId, amount);1792  }17931794  /**1795   * Destroys a concrete instance of RFT on behalf of the owner.1796   * @param signer keyring of signer1797   * @param collectionId ID of collection1798   * @param tokenId ID of token1799   * @param fromAddressObj address on behalf of which the token will be burnt1800   * @param amount number of pieces to be burnt1801   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1802   * @returns ```true``` if extrinsic success, otherwise ```false```1803   */1804  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1805    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1806  }18071808  /**1809   * Set, change, or remove approved address to transfer the ownership of the RFT.1810   *1811   * @param signer keyring of signer1812   * @param collectionId ID of collection1813   * @param tokenId ID of token1814   * @param toAddressObj address to approve1815   * @param amount number of pieces to be approved1816   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1817   * @returns true if the token success, otherwise false1818   */1819  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1820    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1821  }18221823  /**1824   * Get total number of pieces1825   * @param collectionId ID of collection1826   * @param tokenId ID of token1827   * @example getTokenTotalPieces(10, 5);1828   * @returns number of pieces1829   */1830  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1831    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1832  }18331834  /**1835   * Change number of token pieces. Signer must be the owner of all token pieces.1836   * @param signer keyring of signer1837   * @param collectionId ID of collection1838   * @param tokenId ID of token1839   * @param amount new number of pieces1840   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1841   * @returns true if the repartion was success, otherwise false1842   */1843  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1844    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1845    const repartitionResult = await this.helper.executeExtrinsic(1846      signer,1847      'api.tx.unique.repartition', [collectionId, tokenId, amount],1848      true,1849    );1850    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1851    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1852  }1853}185418551856class FTGroup extends CollectionGroup {1857  /**1858   * Get collection object1859   * @param collectionId ID of collection1860   * @example getCollectionObject(2);1861   * @returns instance of UniqueFTCollection1862   */1863  getCollectionObject(collectionId: number): UniqueFTCollection {1864    return new UniqueFTCollection(collectionId, this.helper);1865  }18661867  /**1868   * Mint new fungible collection1869   * @param signer keyring of signer1870   * @param collectionOptions Collection options1871   * @param decimalPoints number of token decimals1872   * @example1873   * mintCollection(aliceKeyring, {1874   *   name: 'New',1875   *   description: 'New collection',1876   *   tokenPrefix: 'NEW',1877   * }, 18)1878   * @returns newly created fungible collection1879   */1880  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1881    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1882    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1883    collectionOptions.mode = {fungible: decimalPoints};1884    for (const key of ['name', 'description', 'tokenPrefix']) {1885      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);1886    }1887    const creationResult = await this.helper.executeExtrinsic(1888      signer,1889      'api.tx.unique.createCollectionEx', [collectionOptions],1890      true,1891    );1892    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1893  }18941895  /**1896   * Mint tokens1897   * @param signer keyring of signer1898   * @param collectionId ID of collection1899   * @param owner address owner of new tokens1900   * @param amount amount of tokens to be meanted1901   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1902   * @returns ```true``` if extrinsic success, otherwise ```false```1903   */1904  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1905    const creationResult = await this.helper.executeExtrinsic(1906      signer,1907      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1908        fungible: {1909          value: amount,1910        },1911      }],1912      true, // `Unable to mint fungible tokens for ${label}`,1913    );1914    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1915  }19161917  /**1918   * Mint multiple Fungible tokens with one owner1919   * @param signer keyring of signer1920   * @param collectionId ID of collection1921   * @param owner tokens owner1922   * @param tokens array of tokens with properties and pieces1923   * @returns ```true``` if extrinsic success, otherwise ```false```1924   */1925  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1926    const rawTokens = [];1927    for (const token of tokens) {1928      const raw = {Fungible: {Value: token.value}};1929      rawTokens.push(raw);1930    }1931    const creationResult = await this.helper.executeExtrinsic(1932      signer,1933      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1934      true,1935    );1936    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1937  }19381939  /**1940   * Get the top 10 owners with the largest balance for the Fungible collection1941   * @param collectionId ID of collection1942   * @example getTop10Owners(10);1943   * @returns array of ```ICrossAccountId```1944   */1945  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1946    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1947  }19481949  /**1950   * Get account balance1951   * @param collectionId ID of collection1952   * @param addressObj address of owner1953   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1954   * @returns amount of fungible tokens owned by address1955   */1956  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1957    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1958  }19591960  /**1961   * Transfer tokens to address1962   * @param signer keyring of signer1963   * @param collectionId ID of collection1964   * @param toAddressObj address recipient1965   * @param amount amount of tokens to be sent1966   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1967   * @returns ```true``` if extrinsic success, otherwise ```false```1968   */1969  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1970    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1971  }19721973  /**1974   * Transfer some tokens on behalf of the owner.1975   * @param signer keyring of signer1976   * @param collectionId ID of collection1977   * @param fromAddressObj address on behalf of which tokens will be sent1978   * @param toAddressObj address where token to be sent1979   * @param amount number of tokens to be sent1980   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1981   * @returns ```true``` if extrinsic success, otherwise ```false```1982   */1983  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1984    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1985  }19861987  /**1988   * Destroy some amount of tokens1989   * @param signer keyring of signer1990   * @param collectionId ID of collection1991   * @param amount amount of tokens to be destroyed1992   * @example burnTokens(aliceKeyring, 10, 1000n);1993   * @returns ```true``` if extrinsic success, otherwise ```false```1994   */1995  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1996    return await super.burnToken(signer, collectionId, 0, amount);1997  }19981999  /**2000   * Burn some tokens on behalf of the owner.2001   * @param signer keyring of signer2002   * @param collectionId ID of collection2003   * @param fromAddressObj address on behalf of which tokens will be burnt2004   * @param amount amount of tokens to be burnt2005   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2006   * @returns ```true``` if extrinsic success, otherwise ```false```2007   */2008  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2009    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2010  }20112012  /**2013   * Get total collection supply2014   * @param collectionId2015   * @returns2016   */2017  async getTotalPieces(collectionId: number): Promise<bigint> {2018    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2019  }20202021  /**2022   * Set, change, or remove approved address to transfer tokens.2023   *2024   * @param signer keyring of signer2025   * @param collectionId ID of collection2026   * @param toAddressObj address to be approved2027   * @param amount amount of tokens to be approved2028   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2029   * @returns ```true``` if extrinsic success, otherwise ```false```2030   */2031  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2032    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2033  }20342035  /**2036   * Get amount of fungible tokens approved to transfer2037   * @param collectionId ID of collection2038   * @param fromAddressObj owner of tokens2039   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2040   * @returns number of tokens approved for the transfer2041   */2042  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2043    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2044  }2045}204620472048class ChainGroup extends HelperGroup<ChainHelperBase> {2049  /**2050   * Get system properties of a chain2051   * @example getChainProperties();2052   * @returns ss58Format, token decimals, and token symbol2053   */2054  getChainProperties(): IChainProperties {2055    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2056    return {2057      ss58Format: properties.ss58Format.toJSON(),2058      tokenDecimals: properties.tokenDecimals.toJSON(),2059      tokenSymbol: properties.tokenSymbol.toJSON(),2060    };2061  }20622063  /**2064   * Get chain header2065   * @example getLatestBlockNumber();2066   * @returns the number of the last block2067   */2068  async getLatestBlockNumber(): Promise<number> {2069    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2070  }20712072  /**2073   * Get block hash by block number2074   * @param blockNumber number of block2075   * @example getBlockHashByNumber(12345);2076   * @returns hash of a block2077   */2078  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2079    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2080    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2081    return blockHash;2082  }20832084  // TODO add docs2085  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2086    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2087    if (!blockHash) return null;2088    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2089  }20902091  /**2092   * Get account nonce2093   * @param address substrate address2094   * @example getNonce("5GrwvaEF5zXb26Fz...");2095   * @returns number, account's nonce2096   */2097  async getNonce(address: TSubstrateAccount): Promise<number> {2098    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2099  }2100}21012102class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2103  /**2104 * Get substrate address balance2105 * @param address substrate address2106 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2107 * @returns amount of tokens on address2108 */2109  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2110    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2111  }21122113  /**2114   * Transfer tokens to substrate address2115   * @param signer keyring of signer2116   * @param address substrate address of a recipient2117   * @param amount amount of tokens to be transfered2118   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2119   * @returns ```true``` if extrinsic success, otherwise ```false```2120   */2121  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2122    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}`*/);21232124    let transfer = {from: null, to: null, amount: 0n} as any;2125    result.result.events.forEach(({event: {data, method, section}}) => {2126      if ((section === 'balances') && (method === 'Transfer')) {2127        transfer = {2128          from: this.helper.address.normalizeSubstrate(data[0]),2129          to: this.helper.address.normalizeSubstrate(data[1]),2130          amount: BigInt(data[2]),2131        };2132      }2133    });2134    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2135      && this.helper.address.normalizeSubstrate(address) === transfer.to 2136      && BigInt(amount) === transfer.amount;2137    return isSuccess;2138  }21392140  /**2141   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2142   * @param address substrate address2143   * @returns2144   */2145  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2146    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2147    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2148  }2149}21502151class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2152  /**2153   * Get ethereum address balance2154   * @param address ethereum address2155   * @example getEthereum("0x9F0583DbB855d...")2156   * @returns amount of tokens on address2157   */2158  async getEthereum(address: TEthereumAccount): Promise<bigint> {2159    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2160  }21612162  /**2163   * Transfer tokens to address2164   * @param signer keyring of signer2165   * @param address Ethereum address of a recipient2166   * @param amount amount of tokens to be transfered2167   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2168   * @returns ```true``` if extrinsic success, otherwise ```false```2169   */2170  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2171    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21722173    let transfer = {from: null, to: null, amount: 0n} as any;2174    result.result.events.forEach(({event: {data, method, section}}) => {2175      if ((section === 'balances') && (method === 'Transfer')) {2176        transfer = {2177          from: data[0].toString(),2178          to: data[1].toString(),2179          amount: BigInt(data[2]),2180        };2181      }2182    });2183    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2184      && address === transfer.to 2185      && BigInt(amount) === transfer.amount;2186    return isSuccess;2187  }2188}21892190class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2191  subBalanceGroup: SubstrateBalanceGroup<T>;2192  ethBalanceGroup: EthereumBalanceGroup<T>;21932194  constructor(helper: T) {2195    super(helper);2196    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2197    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2198  }21992200  getCollectionCreationPrice(): bigint {2201    return 2n * this.getOneTokenNominal();2202  }2203  /**2204   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2205   * @example getOneTokenNominal()2206   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2207   */2208  getOneTokenNominal(): bigint {2209    const chainProperties = this.helper.chain.getChainProperties();2210    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2211  }22122213  /**2214   * Get substrate address balance2215   * @param address substrate address2216   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2217   * @returns amount of tokens on address2218   */2219  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2220    return this.subBalanceGroup.getSubstrate(address);2221  }22222223  /**2224   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2225   * @param address substrate address2226   * @returns2227   */2228  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2229    return this.subBalanceGroup.getSubstrateFull(address);2230  }22312232  /**2233   * Get ethereum address balance2234   * @param address ethereum address2235   * @example getEthereum("0x9F0583DbB855d...")2236   * @returns amount of tokens on address2237   */2238  async getEthereum(address: TEthereumAccount): Promise<bigint> {2239    return this.ethBalanceGroup.getEthereum(address);2240  }22412242  /**2243   * Transfer tokens to substrate address2244   * @param signer keyring of signer2245   * @param address substrate address of a recipient2246   * @param amount amount of tokens to be transfered2247   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2248   * @returns ```true``` if extrinsic success, otherwise ```false```2249   */2250  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2251    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2252  }2253}22542255class AddressGroup extends HelperGroup<ChainHelperBase> {2256  /**2257   * Normalizes the address to the specified ss58 format, by default ```42```.2258   * @param address substrate address2259   * @param ss58Format format for address conversion, by default ```42```2260   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2261   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2262   */2263  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2264    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2265  }22662267  /**2268   * Get address in the connected chain format2269   * @param address substrate address2270   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2271   * @returns address in chain format2272   */2273  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2274    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2275  }22762277  /**2278   * Get substrate mirror of an ethereum address2279   * @param ethAddress ethereum address2280   * @param toChainFormat false for normalized account2281   * @example ethToSubstrate('0x9F0583DbB855d...')2282   * @returns substrate mirror of a provided ethereum address2283   */2284  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2285    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2286  }22872288  /**2289   * Get ethereum mirror of a substrate address2290   * @param subAddress substrate account2291   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2292   * @returns ethereum mirror of a provided substrate address2293   */2294  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2295    return CrossAccountId.translateSubToEth(subAddress);2296  }22972298  paraSiblingSovereignAccount(paraid: number) {2299    // We are getting a *sibling* parachain sovereign account,2300    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2301    const siblingPrefix = '0x7369626c';23022303    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2304    const suffix = '000000000000000000000000000000000000000000000000';23052306    return siblingPrefix + encodedParaId + suffix;2307  }2308}23092310class StakingGroup extends HelperGroup<UniqueHelper> {2311  /**2312   * Stake tokens for App Promotion2313   * @param signer keyring of signer2314   * @param amountToStake amount of tokens to stake2315   * @param label extra label for log2316   * @returns2317   */2318  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2319    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2320    const _stakeResult = await this.helper.executeExtrinsic(2321      signer, 'api.tx.appPromotion.stake',2322      [amountToStake], true,2323    );2324    // TODO extract info from stakeResult2325    return true;2326  }23272328  /**2329   * Unstake tokens for App Promotion2330   * @param signer keyring of signer2331   * @param amountToUnstake amount of tokens to unstake2332   * @param label extra label for log2333   * @returns block number where balances will be unlocked2334   */2335  async unstake(signer: TSigner, label?: string): Promise<number> {2336    if(typeof label === 'undefined') label = `${signer.address}`;2337    const _unstakeResult = await this.helper.executeExtrinsic(2338      signer, 'api.tx.appPromotion.unstake',2339      [], true,2340    );2341    // TODO extract block number fron events2342    return 1;2343  }23442345  /**2346   * Get total staked amount for address2347   * @param address substrate or ethereum address2348   * @returns total staked amount2349   */2350  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2351    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2352    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2353  }23542355  /**2356   * Get total staked per block2357   * @param address substrate or ethereum address2358   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2359   */2360  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2361    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2362    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2363      return { 2364        block: block.toBigInt(),2365        amount: amount.toBigInt(),2366      };2367    });2368  }23692370  /**2371   * Get total pending unstake amount for address2372   * @param address substrate or ethereum address2373   * @returns total pending unstake amount2374   */2375  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2376    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2377  }23782379  /**2380   * Get pending unstake amount per block for address2381   * @param address substrate or ethereum address2382   * @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 block2383   */2384  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2385    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2386    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2387      return {2388        block: block.toBigInt(),2389        amount: amount.toBigInt(),2390      };2391    });2392    return result;2393  }2394}23952396class SchedulerGroup extends HelperGroup<UniqueHelper> {2397  constructor(helper: UniqueHelper) {2398    super(helper);2399  }24002401  async cancelScheduled(signer: TSigner, scheduledId: string) {2402    return this.helper.executeExtrinsic(2403      signer,2404      'api.tx.scheduler.cancelNamed',2405      [scheduledId],2406      true,2407    );2408  }24092410  async changePriority(signer: TSigner, scheduledId: string, priority: number) {2411    return this.helper.executeExtrinsic(2412      signer,2413      'api.tx.scheduler.changeNamedPriority',2414      [scheduledId, priority],2415      true,2416    );2417  }24182419  scheduleAt<T extends UniqueHelper>(2420    scheduledId: string,2421    executionBlockNumber: number,2422    options: ISchedulerOptions = {},2423  ) {2424    return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2425  }24262427  scheduleAfter<T extends UniqueHelper>(2428    scheduledId: string,2429    blocksBeforeExecution: number,2430    options: ISchedulerOptions = {},2431  ) {2432    return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2433  }24342435  schedule<T extends UniqueHelper>(2436    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2437    scheduledId: string,2438    blocksNum: number,2439    options: ISchedulerOptions = {},2440  ) {2441    // eslint-disable-next-line @typescript-eslint/naming-convention2442    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2443    return this.helper.clone(ScheduledHelperType, {2444      scheduleFn,2445      scheduledId,2446      blocksNum,2447      options,2448    }) as T;2449  }2450}24512452class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2453  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2454    await this.helper.executeExtrinsic(2455      signer,2456      'api.tx.foreignAssets.registerForeignAsset',2457      [ownerAddress, location, metadata],2458      true,2459    );2460  }24612462  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2463    await this.helper.executeExtrinsic(2464      signer,2465      'api.tx.foreignAssets.updateForeignAsset',2466      [foreignAssetId, location, metadata],2467      true,2468    );2469  }2470}24712472class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2473  palletName: string;24742475  constructor(helper: T, palletName: string) {2476    super(helper);24772478    this.palletName = palletName;2479  }24802481  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2482    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2483  }2484}24852486class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2487  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2488    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2489  }24902491  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2492    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2493  }24942495  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2496    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2497  }2498}24992500class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2501  async accounts(address: string, currencyId: any) {2502    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2503    return BigInt(free);2504  }2505}25062507class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2508  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2509    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2510  }25112512  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2513    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2514  }25152516  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2517    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2518  }25192520  async account(assetId: string | number, address: string) {2521    const accountAsset = (2522      await this.helper.callRpc('api.query.assets.account', [assetId, address])2523    ).toJSON()! as any;25242525    if (accountAsset !== null) {2526      return BigInt(accountAsset['balance']);2527    } else {2528      return null;2529    }2530  }2531}25322533class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2534  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2535    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2536  }2537}25382539class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2540  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2541    const apiPrefix = 'api.tx.assetManager.';25422543    const registerTx = this.helper.constructApiCall(2544      apiPrefix + 'registerForeignAsset',2545      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2546    );25472548    const setUnitsTx = this.helper.constructApiCall(2549      apiPrefix + 'setAssetUnitsPerSecond',2550      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2551    );25522553    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2554    const encodedProposal = batchCall?.method.toHex() || '';2555    return encodedProposal;2556  }25572558  async assetTypeId(location: any) {2559    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2560  }2561}25622563class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2564  async notePreimage(signer: TSigner, encodedProposal: string) {2565    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2566  }25672568  externalProposeMajority(proposalHash: string) {2569    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2570  }25712572  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2573    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2574  }25752576  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2577    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2578  }2579}25802581class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2582  collective: string;25832584  constructor(helper: MoonbeamHelper, collective: string) {2585    super(helper);25862587    this.collective = collective;2588  }25892590  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2591    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2592  }25932594  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2595    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2596  }25972598  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2599    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2600  }26012602  async proposalCount() {2603    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2604  }2605}26062607export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2608export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26092610export class UniqueHelper extends ChainHelperBase {2611  balance: BalanceGroup<UniqueHelper>;2612  collection: CollectionGroup;2613  nft: NFTGroup;2614  rft: RFTGroup;2615  ft: FTGroup;2616  staking: StakingGroup;2617  scheduler: SchedulerGroup;2618  foreignAssets: ForeignAssetsGroup;2619  xcm: XcmGroup<UniqueHelper>;2620  xTokens: XTokensGroup<UniqueHelper>;2621  tokens: TokensGroup<UniqueHelper>;26222623  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2624    super(logger, options.helperBase ?? UniqueHelper);26252626    this.balance = new BalanceGroup(this);2627    this.collection = new CollectionGroup(this);2628    this.nft = new NFTGroup(this);2629    this.rft = new RFTGroup(this);2630    this.ft = new FTGroup(this);2631    this.staking = new StakingGroup(this);2632    this.scheduler = new SchedulerGroup(this);2633    this.foreignAssets = new ForeignAssetsGroup(this);2634    this.xcm = new XcmGroup(this, 'polkadotXcm');2635    this.xTokens = new XTokensGroup(this);2636    this.tokens = new TokensGroup(this);2637  }26382639  getSudo<T extends UniqueHelper>() {2640    // eslint-disable-next-line @typescript-eslint/naming-convention2641    const SudoHelperType = SudoHelper(this.helperBase);2642    return this.clone(SudoHelperType) as T;2643  }2644}26452646export class XcmChainHelper extends ChainHelperBase {2647  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2648    const wsProvider = new WsProvider(wsEndpoint);2649    this.api = new ApiPromise({2650      provider: wsProvider,2651    });2652    await this.api.isReadyOrError;2653    this.network = await UniqueHelper.detectNetwork(this.api);2654  }2655}26562657export class RelayHelper extends XcmChainHelper {2658  xcm: XcmGroup<RelayHelper>;26592660  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2661    super(logger, options.helperBase ?? RelayHelper);26622663    this.xcm = new XcmGroup(this, 'xcmPallet');2664  }2665}26662667export class WestmintHelper extends XcmChainHelper {2668  balance: SubstrateBalanceGroup<WestmintHelper>;2669  xcm: XcmGroup<WestmintHelper>;2670  assets: AssetsGroup<WestmintHelper>;2671  xTokens: XTokensGroup<WestmintHelper>;26722673  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2674    super(logger, options.helperBase ?? WestmintHelper);26752676    this.balance = new SubstrateBalanceGroup(this);2677    this.xcm = new XcmGroup(this, 'polkadotXcm');2678    this.assets = new AssetsGroup(this);2679    this.xTokens = new XTokensGroup(this);2680  }2681}26822683export class MoonbeamHelper extends XcmChainHelper {2684  balance: EthereumBalanceGroup<MoonbeamHelper>;2685  assetManager: MoonbeamAssetManagerGroup;2686  assets: AssetsGroup<MoonbeamHelper>;2687  xTokens: XTokensGroup<MoonbeamHelper>;2688  democracy: MoonbeamDemocracyGroup;2689  collective: {2690    council: MoonbeamCollectiveGroup,2691    techCommittee: MoonbeamCollectiveGroup,2692  };26932694  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2695    super(logger, options.helperBase ?? MoonbeamHelper);26962697    this.balance = new EthereumBalanceGroup(this);2698    this.assetManager = new MoonbeamAssetManagerGroup(this);2699    this.assets = new AssetsGroup(this);2700    this.xTokens = new XTokensGroup(this);2701    this.democracy = new MoonbeamDemocracyGroup(this);2702    this.collective = {2703      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2704      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2705    };2706  }2707}27082709export class AcalaHelper extends XcmChainHelper {2710  balance: SubstrateBalanceGroup<AcalaHelper>;2711  assetRegistry: AcalaAssetRegistryGroup;2712  xTokens: XTokensGroup<AcalaHelper>;2713  tokens: TokensGroup<AcalaHelper>;27142715  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2716    super(logger, options.helperBase ?? AcalaHelper);27172718    this.balance = new SubstrateBalanceGroup(this);2719    this.assetRegistry = new AcalaAssetRegistryGroup(this);2720    this.xTokens = new XTokensGroup(this);2721    this.tokens = new TokensGroup(this);2722  }27232724  getSudo<T extends AcalaHelper>() {2725    // eslint-disable-next-line @typescript-eslint/naming-convention2726    const SudoHelperType = SudoHelper(this.helperBase);2727    return this.clone(SudoHelperType) as T;2728  }2729}27302731// eslint-disable-next-line @typescript-eslint/naming-convention2732function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2733  return class extends Base {2734    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2735    scheduledId: string;2736    blocksNum: number;2737    options: ISchedulerOptions;27382739    constructor(...args: any[]) {2740      const logger = args[0] as ILogger;2741      const options = args[1] as {2742        scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2743        scheduledId: string,2744        blocksNum: number,2745        options: ISchedulerOptions2746      };27472748      super(logger);27492750      this.scheduleFn = options.scheduleFn;2751      this.scheduledId = options.scheduledId;2752      this.blocksNum = options.blocksNum;2753      this.options = options.options;2754    }27552756    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2757      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2758      const extrinsic = 'api.tx.scheduler.' +  this.scheduleFn;27592760      return super.executeExtrinsic(2761        sender,2762        extrinsic,2763        [2764          this.scheduledId,2765          this.blocksNum,2766          this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2767          this.options.priority ?? null,2768          {Value: scheduledTx},2769        ],2770        expectSuccess,2771      );2772    }2773  };2774}27752776// eslint-disable-next-line @typescript-eslint/naming-convention2777function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2778  return class extends Base {2779    constructor(...args: any[]) {2780      super(...args);2781    }27822783    executeExtrinsic (2784      sender: IKeyringPair,2785      extrinsic: string,2786      params: any[],2787      expectSuccess?: boolean,2788    ): Promise<ITransactionResult> {2789      const call = this.constructApiCall(extrinsic, params);27902791      return super.executeExtrinsic(2792        sender,2793        'api.tx.sudo.sudo',2794        [call],2795        expectSuccess,2796      );2797    }2798  };2799}28002801export class UniqueBaseCollection {2802  helper: UniqueHelper;2803  collectionId: number;28042805  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2806    this.collectionId = collectionId;2807    this.helper = uniqueHelper;2808  }28092810  async getData() {2811    return await this.helper.collection.getData(this.collectionId);2812  }28132814  async getLastTokenId() {2815    return await this.helper.collection.getLastTokenId(this.collectionId);2816  }28172818  async doesTokenExist(tokenId: number) {2819    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2820  }28212822  async getAdmins() {2823    return await this.helper.collection.getAdmins(this.collectionId);2824  }28252826  async getAllowList() {2827    return await this.helper.collection.getAllowList(this.collectionId);2828  }28292830  async getEffectiveLimits() {2831    return await this.helper.collection.getEffectiveLimits(this.collectionId);2832  }28332834  async getProperties(propertyKeys?: string[] | null) {2835    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2836  }28372838  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2839    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2840  }28412842  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2843    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2844  }28452846  async confirmSponsorship(signer: TSigner) {2847    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2848  }28492850  async removeSponsor(signer: TSigner) {2851    return await this.helper.collection.removeSponsor(signer, this.collectionId);2852  }28532854  async setLimits(signer: TSigner, limits: ICollectionLimits) {2855    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2856  }28572858  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2859    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2860  }28612862  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2863    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2864  }28652866  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2867    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2868  }28692870  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2871    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2872  }28732874  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2875    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2876  }28772878  async setProperties(signer: TSigner, properties: IProperty[]) {2879    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2880  }28812882  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2883    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2884  }28852886  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2887    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2888  }28892890  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2891    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2892  }28932894  async disableNesting(signer: TSigner) {2895    return await this.helper.collection.disableNesting(signer, this.collectionId);2896  }28972898  async burn(signer: TSigner) {2899    return await this.helper.collection.burn(signer, this.collectionId);2900  }29012902  scheduleAt<T extends UniqueHelper>(2903    scheduledId: string,2904    executionBlockNumber: number,2905    options: ISchedulerOptions = {},2906  ) {2907    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2908    return new UniqueBaseCollection(this.collectionId, scheduledHelper);2909  }29102911  scheduleAfter<T extends UniqueHelper>(2912    scheduledId: string,2913    blocksBeforeExecution: number,2914    options: ISchedulerOptions = {},2915  ) {2916    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2917    return new UniqueBaseCollection(this.collectionId, scheduledHelper);2918  }29192920  getSudo<T extends UniqueHelper>() {2921    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2922  }2923}292429252926export class UniqueNFTCollection extends UniqueBaseCollection {2927  getTokenObject(tokenId: number) {2928    return new UniqueNFToken(tokenId, this);2929  }29302931  async getTokensByAddress(addressObj: ICrossAccountId) {2932    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2933  }29342935  async getToken(tokenId: number, blockHashAt?: string) {2936    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2937  }29382939  async getTokenOwner(tokenId: number, blockHashAt?: string) {2940    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2941  }29422943  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2944    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2945  }29462947  async getTokenChildren(tokenId: number, blockHashAt?: string) {2948    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2949  }29502951  async getPropertyPermissions(propertyKeys: string[] | null = null) {2952    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2953  }29542955  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2956    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2957  }29582959  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2960    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2961  }29622963  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2964    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2965  }29662967  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2968    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2969  }29702971  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2972    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2973  }29742975  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2976    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2977  }29782979  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2980    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2981  }29822983  async burnToken(signer: TSigner, tokenId: number) {2984    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2985  }29862987  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2988    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2989  }29902991  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2992    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2993  }29942995  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2996    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2997  }29982999  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3000    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3001  }30023003  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3004    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3005  }30063007  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3008    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3009  }30103011  scheduleAt<T extends UniqueHelper>(3012    scheduledId: string,3013    executionBlockNumber: number,3014    options: ISchedulerOptions = {},3015  ) {3016    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3017    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3018  }30193020  scheduleAfter<T extends UniqueHelper>(3021    scheduledId: string,3022    blocksBeforeExecution: number,3023    options: ISchedulerOptions = {},3024  ) {3025    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3026    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3027  }30283029  getSudo<T extends UniqueHelper>() {3030    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3031  }3032}303330343035export class UniqueRFTCollection extends UniqueBaseCollection {3036  getTokenObject(tokenId: number) {3037    return new UniqueRFToken(tokenId, this);3038  }30393040  async getToken(tokenId: number, blockHashAt?: string) {3041    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3042  }30433044  async getTokensByAddress(addressObj: ICrossAccountId) {3045    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3046  }30473048  async getTop10TokenOwners(tokenId: number) {3049    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3050  }30513052  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3053    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3054  }30553056  async getTokenTotalPieces(tokenId: number) {3057    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3058  }30593060  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3061    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3062  }30633064  async getPropertyPermissions(propertyKeys: string[] | null = null) {3065    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3066  }30673068  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3069    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3070  }30713072  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3073    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3074  }30753076  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3077    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3078  }30793080  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3081    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3082  }30833084  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3085    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3086  }30873088  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3089    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3090  }30913092  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3093    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3094  }30953096  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3097    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3098  }30993100  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3101    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3102  }31033104  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3105    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3106  }31073108  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3109    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3110  }31113112  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3113    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3114  }31153116  scheduleAt<T extends UniqueHelper>(3117    scheduledId: string,3118    executionBlockNumber: number,3119    options: ISchedulerOptions = {},3120  ) {3121    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3122    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3123  }31243125  scheduleAfter<T extends UniqueHelper>(3126    scheduledId: string,3127    blocksBeforeExecution: number,3128    options: ISchedulerOptions = {},3129  ) {3130    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3131    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3132  }31333134  getSudo<T extends UniqueHelper>() {3135    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3136  }3137}313831393140export class UniqueFTCollection extends UniqueBaseCollection {3141  async getBalance(addressObj: ICrossAccountId) {3142    return await this.helper.ft.getBalance(this.collectionId, addressObj);3143  }31443145  async getTotalPieces() {3146    return await this.helper.ft.getTotalPieces(this.collectionId);3147  }31483149  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3150    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3151  }31523153  async getTop10Owners() {3154    return await this.helper.ft.getTop10Owners(this.collectionId);3155  }31563157  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3158    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3159  }31603161  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3162    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3163  }31643165  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3166    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3167  }31683169  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3170    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3171  }31723173  async burnTokens(signer: TSigner, amount=1n) {3174    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3175  }31763177  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3178    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3179  }31803181  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3182    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3183  }31843185  scheduleAt<T extends UniqueHelper>(3186    scheduledId: string,3187    executionBlockNumber: number,3188    options: ISchedulerOptions = {},3189  ) {3190    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3191    return new UniqueFTCollection(this.collectionId, scheduledHelper);3192  }31933194  scheduleAfter<T extends UniqueHelper>(3195    scheduledId: string,3196    blocksBeforeExecution: number,3197    options: ISchedulerOptions = {},3198  ) {3199    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3200    return new UniqueFTCollection(this.collectionId, scheduledHelper);3201  }32023203  getSudo<T extends UniqueHelper>() {3204    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3205  }3206}320732083209export class UniqueBaseToken {3210  collection: UniqueNFTCollection | UniqueRFTCollection;3211  collectionId: number;3212  tokenId: number;32133214  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3215    this.collection = collection;3216    this.collectionId = collection.collectionId;3217    this.tokenId = tokenId;3218  }32193220  async getNextSponsored(addressObj: ICrossAccountId) {3221    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3222  }32233224  async getProperties(propertyKeys?: string[] | null) {3225    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3226  }32273228  async setProperties(signer: TSigner, properties: IProperty[]) {3229    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3230  }32313232  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3233    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3234  }32353236  async doesExist() {3237    return await this.collection.doesTokenExist(this.tokenId);3238  }32393240  nestingAccount() {3241    return this.collection.helper.util.getTokenAccount(this);3242  }32433244  scheduleAt<T extends UniqueHelper>(3245    scheduledId: string,3246    executionBlockNumber: number,3247    options: ISchedulerOptions = {},3248  ) {3249    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3250    return new UniqueBaseToken(this.tokenId, scheduledCollection);3251  }32523253  scheduleAfter<T extends UniqueHelper>(3254    scheduledId: string,3255    blocksBeforeExecution: number,3256    options: ISchedulerOptions = {},3257  ) {3258    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3259    return new UniqueBaseToken(this.tokenId, scheduledCollection);3260  }32613262  getSudo<T extends UniqueHelper>() {3263    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3264  }3265}326632673268export class UniqueNFToken extends UniqueBaseToken {3269  collection: UniqueNFTCollection;32703271  constructor(tokenId: number, collection: UniqueNFTCollection) {3272    super(tokenId, collection);3273    this.collection = collection;3274  }32753276  async getData(blockHashAt?: string) {3277    return await this.collection.getToken(this.tokenId, blockHashAt);3278  }32793280  async getOwner(blockHashAt?: string) {3281    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3282  }32833284  async getTopmostOwner(blockHashAt?: string) {3285    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3286  }32873288  async getChildren(blockHashAt?: string) {3289    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3290  }32913292  async nest(signer: TSigner, toTokenObj: IToken) {3293    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3294  }32953296  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3297    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3298  }32993300  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3301    return await this.collection.transferToken(signer, this.tokenId, addressObj);3302  }33033304  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3305    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3306  }33073308  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3309    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3310  }33113312  async isApproved(toAddressObj: ICrossAccountId) {3313    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3314  }33153316  async burn(signer: TSigner) {3317    return await this.collection.burnToken(signer, this.tokenId);3318  }33193320  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3321    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3322  }33233324  scheduleAt<T extends UniqueHelper>(3325    scheduledId: string,3326    executionBlockNumber: number,3327    options: ISchedulerOptions = {},3328  ) {3329    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3330    return new UniqueNFToken(this.tokenId, scheduledCollection);3331  }33323333  scheduleAfter<T extends UniqueHelper>(3334    scheduledId: string,3335    blocksBeforeExecution: number,3336    options: ISchedulerOptions = {},3337  ) {3338    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3339    return new UniqueNFToken(this.tokenId, scheduledCollection);3340  }33413342  getSudo<T extends UniqueHelper>() {3343    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3344  }3345}33463347export class UniqueRFToken extends UniqueBaseToken {3348  collection: UniqueRFTCollection;33493350  constructor(tokenId: number, collection: UniqueRFTCollection) {3351    super(tokenId, collection);3352    this.collection = collection;3353  }33543355  async getData(blockHashAt?: string) {3356    return await this.collection.getToken(this.tokenId, blockHashAt);3357  }33583359  async getTop10Owners() {3360    return await this.collection.getTop10TokenOwners(this.tokenId);3361  }33623363  async getBalance(addressObj: ICrossAccountId) {3364    return await this.collection.getTokenBalance(this.tokenId, addressObj);3365  }33663367  async getTotalPieces() {3368    return await this.collection.getTokenTotalPieces(this.tokenId);3369  }33703371  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3372    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3373  }33743375  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3376    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3377  }33783379  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3380    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3381  }33823383  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3384    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3385  }33863387  async repartition(signer: TSigner, amount: bigint) {3388    return await this.collection.repartitionToken(signer, this.tokenId, amount);3389  }33903391  async burn(signer: TSigner, amount=1n) {3392    return await this.collection.burnToken(signer, this.tokenId, amount);3393  }33943395  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3396    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3397  }33983399  scheduleAt<T extends UniqueHelper>(3400    scheduledId: string,3401    executionBlockNumber: number,3402    options: ISchedulerOptions = {},3403  ) {3404    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3405    return new UniqueRFToken(this.tokenId, scheduledCollection);3406  }34073408  scheduleAfter<T extends UniqueHelper>(3409    scheduledId: string,3410    blocksBeforeExecution: number,3411    options: ISchedulerOptions = {},3412  ) {3413    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3414    return new UniqueRFToken(this.tokenId, scheduledCollection);3415  }34163417  getSudo<T extends UniqueHelper>() {3418    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3419  }3420}
modifiedtests/src/xcm/xcmOpal.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/xcmOpal.test.ts
+++ b/tests/src/xcm/xcmOpal.test.ts
@@ -14,33 +14,22 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-
-import {WsProvider} from '@polkadot/api';
-import {ApiOptions} from '@polkadot/api/types';
 import {IKeyringPair} from '@polkadot/types/types';
-import usingApi, {executeTransaction} from './../substrate/substrate-api';
-import {bigIntToDecimals, describeXCM, getGenericResult, paraSiblingSovereignAccount, normalizeAccountId} from './../deprecated-helpers/helpers';
-import waitNewBlocks from './../substrate/wait-new-blocks';
-import getBalance from './../substrate/get-balance';
-
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
+import config from '../config';
+import {itSub, expect, describeXCM, usingPlaygrounds, usingWestmintPlaygrounds, usingRelayPlaygrounds} from '../util';
 
 const STATEMINE_CHAIN = 1000;
 const UNIQUE_CHAIN = 2095;
 
-const RELAY_PORT = '9844';
-const UNIQUE_PORT = '9944';
-const STATEMINE_PORT = '9948';
+const relayUrl = config.relayUrl;
+const westmintUrl = config.westmintUrl;
+
 const STATEMINE_PALLET_INSTANCE = 50;
 const ASSET_ID = 100;
 const ASSET_METADATA_DECIMALS = 18;
 const ASSET_METADATA_NAME = 'USDT';
 const ASSET_METADATA_DESCRIPTION = 'USDT';
-const ASSET_METADATA_MINIMAL_BALANCE = 1;
+const ASSET_METADATA_MINIMAL_BALANCE = 1n;
 
 const WESTMINT_DECIMALS = 12;
 
@@ -69,58 +58,26 @@
 
 
   before(async () => {
-    console.log('hey babe its opal');
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob'); // funds donor
+    await usingPlaygrounds(async (_helper, privateKey) => {
+      alice = await privateKey('//Alice');
+      bob = await privateKey('//Bob'); // funds donor
     });
 
-    const statemineApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + STATEMINE_PORT),
-    };
-
-    const uniqueApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + UNIQUE_PORT),
-    };
-
-    const relayApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + RELAY_PORT),
-    };
-
-    await usingApi(async (api) => {
-
+    await usingWestmintPlaygrounds(westmintUrl, async (helper) => {
       // 350.00 (three hundred fifty) DOT
-      const fundingAmount = 3_500_000_000_000; 
-
-      const tx = api.tx.assets.create(ASSET_ID, alice.addressRaw, ASSET_METADATA_MINIMAL_BALANCE);
-      const events = await executeTransaction(api, alice, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
-
-      // set metadata
-      const tx2 = api.tx.assets.setMetadata(ASSET_ID, ASSET_METADATA_NAME, ASSET_METADATA_DESCRIPTION, ASSET_METADATA_DECIMALS);
-      const events2 = await executeTransaction(api, alice, tx2);
-      const result2 = getGenericResult(events2);
-      expect(result2.success).to.be.true;
+      const fundingAmount = 3_500_000_000_000n; 
 
-      // mint some amount of asset
-      const tx3 = api.tx.assets.mint(ASSET_ID, alice.addressRaw, ASSET_AMOUNT);
-      const events3 = await executeTransaction(api, alice, tx3);
-      const result3 = getGenericResult(events3);
-      expect(result3.success).to.be.true;
+      await helper.assets.create(alice, ASSET_ID, alice.address, ASSET_METADATA_MINIMAL_BALANCE);
+      await helper.assets.setMetadata(alice, ASSET_ID, ASSET_METADATA_NAME, ASSET_METADATA_DESCRIPTION, ASSET_METADATA_DECIMALS);
+      await helper.assets.mint(alice, ASSET_ID, alice.address, ASSET_AMOUNT);
 
       // funding parachain sovereing account (Parachain: 2095)
-      const parachainSovereingAccount = await paraSiblingSovereignAccount(UNIQUE_CHAIN);
-      const tx4 = api.tx.balances.transfer(parachainSovereingAccount, fundingAmount);
-      const events4 = await executeTransaction(api, bob, tx4);
-      const result4 = getGenericResult(events4);
-      expect(result4.success).to.be.true;
+      const parachainSovereingAccount = helper.address.paraSiblingSovereignAccount(UNIQUE_CHAIN);
+      await helper.balance.transferToSubstrate(bob, parachainSovereingAccount, fundingAmount);
+    });
 
-    }, statemineApiOptions);
 
-
-    await usingApi(async (api) => {
-
+    await usingPlaygrounds(async (helper) => {
       const location = {
         V1: {
           parents: 1,
@@ -145,20 +102,13 @@
         decimals: ASSET_METADATA_DECIMALS,
         minimalBalance: ASSET_METADATA_MINIMAL_BALANCE,
       };
-      //registerForeignAsset(owner, location, metadata)
-      const tx = api.tx.foreignAssets.registerForeignAsset(alice.addressRaw, location, metadata);
-      const sudoTx = api.tx.sudo.sudo(tx as any);
-      const events = await executeTransaction(api, alice, sudoTx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
-
-      [balanceOpalBefore] = await getBalance(api, [alice.address]);
-
-    }, uniqueApiOptions);
+      await helper.getSudo().foreignAssets.register(alice, alice.address, location, metadata);
+      balanceOpalBefore = await helper.balance.getSubstrate(alice.address);
+    });
 
 
     // Providing the relay currency to the unique sender account
-    await usingApi(async (api) => {
+    await usingRelayPlaygrounds(relayUrl, async (helper) => {
       const destination = {
         V1: {
           parents: 0,
@@ -197,31 +147,15 @@
       };
 
       const feeAssetItem = 0;
+      const weightLimit = 5_000_000_000;
 
-      const weightLimit = {
-        Limited: 5_000_000_000,
-      };
-
-      const tx = api.tx.xcmPallet.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
-      const events = await executeTransaction(api, alice, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
-    }, relayApiOptions);
+      await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, weightLimit);
+    });
   
   });
 
-  it('Should connect and send USDT from Westmint to Opal', async () => {
-    
-    const statemineApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + STATEMINE_PORT),
-    };
-
-    const uniqueApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + UNIQUE_PORT),
-    };
-
-    await usingApi(async (api) => {
-
+  itSub('Should connect and send USDT from Westmint to Opal', async ({helper}) => {
+    await usingWestmintPlaygrounds(westmintUrl, async (helper) => {
       const dest = {
         V1: {
           parents: 1,
@@ -268,146 +202,105 @@
       };
 
       const feeAssetItem = 0;
-
-      const weightLimit = {
-        Limited: 5000000000,
-      };
-
-      [balanceStmnBefore] = await getBalance(api, [alice.address]);
+      const weightLimit = 5000000000;
 
-      const tx = api.tx.polkadotXcm.limitedReserveTransferAssets(dest, beneficiary, assets, feeAssetItem, weightLimit);
-      const events = await executeTransaction(api, alice, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
+      balanceStmnBefore = await helper.balance.getSubstrate(alice.address);
+      await helper.xcm.limitedReserveTransferAssets(alice, dest, beneficiary, assets, feeAssetItem, weightLimit);
 
-      [balanceStmnAfter] = await getBalance(api, [alice.address]);
+      balanceStmnAfter = await helper.balance.getSubstrate(alice.address);
 
       // common good parachain take commission in it native token
       console.log(
         'Opal to Westmint transaction fees on Westmint: %s WND',
-        bigIntToDecimals(balanceStmnBefore - balanceStmnAfter, WESTMINT_DECIMALS),
+        helper.util.bigIntToDecimals(balanceStmnBefore - balanceStmnAfter, WESTMINT_DECIMALS),
       );
       expect(balanceStmnBefore > balanceStmnAfter).to.be.true;
 
-    }, statemineApiOptions);
+    });
 
 
     // ensure that asset has been delivered
-    await usingApi(async (api) => {
-      await waitNewBlocks(api, 3);
-      // expext collection id will be with id 1
-      const free = (await api.query.fungible.balance(1, normalizeAccountId(alice.address))).toBigInt();
+    await helper.wait.newBlocks(3);
 
-      [balanceOpalAfter] = await getBalance(api, [alice.address]);
+    // expext collection id will be with id 1
+    const free = await helper.ft.getBalance(1, {Substrate: alice.address});
 
-      // commission has not paid in USDT token
-      expect(free == TRANSFER_AMOUNT).to.be.true;
-      console.log(
-        'Opal to Westmint transaction fees on Opal: %s USDT',
-        bigIntToDecimals(TRANSFER_AMOUNT - free),
-      );
-      // ... and parachain native token
-      expect(balanceOpalAfter == balanceOpalBefore).to.be.true;
-      console.log(
-        'Opal to Westmint transaction fees on Opal: %s WND',
-        bigIntToDecimals(balanceOpalAfter - balanceOpalBefore, WESTMINT_DECIMALS),
-      );
+    balanceOpalAfter = await helper.balance.getSubstrate(alice.address);
 
-    }, uniqueApiOptions);
-    
+    // commission has not paid in USDT token
+    expect(free == TRANSFER_AMOUNT).to.be.true;
+    console.log(
+      'Opal to Westmint transaction fees on Opal: %s USDT',
+      helper.util.bigIntToDecimals(TRANSFER_AMOUNT - free),
+    );
+    // ... and parachain native token
+    expect(balanceOpalAfter == balanceOpalBefore).to.be.true;
+    console.log(
+      'Opal to Westmint transaction fees on Opal: %s WND',
+      helper.util.bigIntToDecimals(balanceOpalAfter - balanceOpalBefore, WESTMINT_DECIMALS),
+    );    
   });
-
-  it('Should connect and send USDT from Unique to Statemine back', async () => {
-
-    const uniqueApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + UNIQUE_PORT),
-    };
-
-    const statemineApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + STATEMINE_PORT),
-    };
-
-    await usingApi(async (api) => {
-      const destination = {
-        V1: {
-          parents: 1,
-          interior: {X2: [
-            {
-              Parachain: STATEMINE_CHAIN,
-            },
-            {
-              AccountId32: {
-                network: 'Any',
-                id: alice.addressRaw,
-              },
-            },
-          ]},
-        },
-      };
 
-      const currencies: [any, bigint][] = [
-        [
+  itSub('Should connect and send USDT from Unique to Statemine back', async ({helper}) => {
+    const destination = {
+      V1: {
+        parents: 1,
+        interior: {X2: [
           {
-            ForeignAssetId: 0,
+            Parachain: STATEMINE_CHAIN,
           },
-          //10_000_000_000_000_000n,
-          TRANSFER_AMOUNT,
-        ], 
-        [
           {
-            NativeAssetId: 'Parent',
+            AccountId32: {
+              network: 'Any',
+              id: alice.addressRaw,
+            },
           },
-          400_000_000_000_000n,
-        ],
-      ];
+        ]},
+      },
+    };
 
-      const feeItem = 1;
-      const destWeight = 500000000000;
+    const currencies: [any, bigint][] = [
+      [
+        {
+          ForeignAssetId: 0,
+        },
+        //10_000_000_000_000_000n,
+        TRANSFER_AMOUNT,
+      ], 
+      [
+        {
+          NativeAssetId: 'Parent',
+        },
+        400_000_000_000_000n,
+      ],
+    ];
 
-      const tx = api.tx.xTokens.transferMulticurrencies(currencies, feeItem, destination, destWeight);
-      const events = await executeTransaction(api, alice, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
-      
-      // the commission has been paid in parachain native token
-      [balanceOpalFinal] = await getBalance(api, [alice.address]);
-      expect(balanceOpalAfter > balanceOpalFinal).to.be.true;
-    }, uniqueApiOptions);
+    const feeItem = 1;
+    const destWeight = 500000000000;
 
-    await usingApi(async (api) => {
-      await waitNewBlocks(api, 3);
+    await helper.xTokens.transferMulticurrencies(alice, currencies, feeItem, destination, destWeight);
+    
+    // the commission has been paid in parachain native token
+    balanceOpalFinal = await helper.balance.getSubstrate(alice.address);
+    expect(balanceOpalAfter > balanceOpalFinal).to.be.true;
+
+    await usingWestmintPlaygrounds(westmintUrl, async (helper) => {
+      await helper.wait.newBlocks(3);
       
       // The USDT token never paid fees. Its amount not changed from begin value.
       // Also check that xcm transfer has been succeeded 
-      const free = ((await api.query.assets.account(100, alice.address)).toHuman()) as any;
-      expect(BigInt(free.balance.replace(/,/g, '')) == ASSET_AMOUNT).to.be.true;
-    }, statemineApiOptions);
+      expect((await helper.assets.account(ASSET_ID, alice.address))! == ASSET_AMOUNT).to.be.true;
+    });
   });
 
-  it('Should connect and send Relay token to Unique', async () => {
-
-    const uniqueApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + UNIQUE_PORT),
-    };
-
-    const uniqueApiOptions2: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + UNIQUE_PORT),
-    };
-
-    const relayApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + RELAY_PORT),
-    };
-
+  itSub('Should connect and send Relay token to Unique', async ({helper}) => {
     const TRANSFER_AMOUNT_RELAY = 50_000_000_000_000_000n;
 
-    await usingApi(async (api) => {
-      [balanceBobBefore] = await getBalance(api, [bob.address]);
-      balanceBobRelayTokenBefore = BigInt(((await api.query.tokens.accounts(bob.addressRaw, {NativeAssetId: 'Parent'})).toJSON() as any).free);
-
-    }, uniqueApiOptions);
+    balanceBobBefore = await helper.balance.getSubstrate(bob.address);
+    balanceBobRelayTokenBefore = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
 
     // Providing the relay currency to the unique sender account
-    await usingApi(async (api) => {
+    await usingRelayPlaygrounds(relayUrl, async (helper) => {
       const destination = {
         V1: {
           parents: 0,
@@ -446,82 +339,62 @@
       };
 
       const feeAssetItem = 0;
-
-      const weightLimit = {
-        Limited: 5_000_000_000,
-      };
+      const weightLimit = 5_000_000_000;
 
-      const tx = api.tx.xcmPallet.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
-      const events = await executeTransaction(api, bob, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
-    }, relayApiOptions);
+      await helper.xcm.limitedReserveTransferAssets(bob, destination, beneficiary, assets, feeAssetItem, weightLimit);
+    });
   
+    await helper.wait.newBlocks(3);
 
-    await usingApi(async (api) => {
-      await waitNewBlocks(api, 3);
+    balanceBobAfter = await helper.balance.getSubstrate(bob.address);  
+    balanceBobRelayTokenAfter = await helper.tokens.accounts(bob.address, {NativeAssetId: 'Parent'});
 
-      [balanceBobAfter] = await getBalance(api, [bob.address]);
-      balanceBobRelayTokenAfter = BigInt(((await api.query.tokens.accounts(bob.addressRaw, {NativeAssetId: 'Parent'})).toJSON() as any).free);
-      const wndFee = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore; 
-      console.log(
-        'Relay (Westend) to Opal transaction fees: %s OPL',
-        bigIntToDecimals(balanceBobAfter - balanceBobBefore),
-      );
-      console.log(
-        'Relay (Westend) to Opal transaction fees: %s WND',
-        bigIntToDecimals(wndFee, WESTMINT_DECIMALS),
-      );
-      expect(balanceBobBefore == balanceBobAfter).to.be.true;
-      expect(balanceBobRelayTokenBefore < balanceBobRelayTokenAfter).to.be.true;
-    }, uniqueApiOptions2);
-
+    const wndFee = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore; 
+    console.log(
+      'Relay (Westend) to Opal transaction fees: %s OPL',
+      helper.util.bigIntToDecimals(balanceBobAfter - balanceBobBefore),
+    );
+    console.log(
+      'Relay (Westend) to Opal transaction fees: %s WND',
+      helper.util.bigIntToDecimals(wndFee, WESTMINT_DECIMALS),
+    );
+    expect(balanceBobBefore == balanceBobAfter).to.be.true;
+    expect(balanceBobRelayTokenBefore < balanceBobRelayTokenAfter).to.be.true;
   });
 
-  it('Should connect and send Relay token back', async () => {
-    const uniqueApiOptions: ApiOptions = {
-      provider: new WsProvider('ws://127.0.0.1:' + UNIQUE_PORT),
+  itSub('Should connect and send Relay token back', async ({helper}) => {
+    const destination = {
+      V1: {
+        parents: 1,
+        interior: {X2: [
+          {
+            Parachain: STATEMINE_CHAIN,
+          },
+          {
+            AccountId32: {
+              network: 'Any',
+              id: bob.addressRaw,
+            },
+          },
+        ]},
+      },
     };
 
-    await usingApi(async (api) => {
-      const destination = {
-        V1: {
-          parents: 1,
-          interior: {X2: [
-            {
-              Parachain: STATEMINE_CHAIN,
-            },
-            {
-              AccountId32: {
-                network: 'Any',
-                id: bob.addressRaw,
-              },
-            },
-          ]},
+    const currencies: any = [
+      [
+        {
+          NativeAssetId: 'Parent',
         },
-      };
+        50_000_000_000_000_000n,
+      ],
+    ];
 
-      const currencies: any = [
-        [
-          {
-            NativeAssetId: 'Parent',
-          },
-          50_000_000_000_000_000n,
-        ],
-      ];
-
-      const feeItem = 0;
-      const destWeight = 500000000000;
-
-      const tx = api.tx.xTokens.transferMulticurrencies(currencies, feeItem, destination, destWeight);
-      const events = await executeTransaction(api, bob, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
+    const feeItem = 0;
+    const destWeight = 500000000000;
 
-      [balanceBobFinal] = await getBalance(api, [bob.address]);
-      console.log('Relay (Westend) to Opal transaction fees: %s OPL', balanceBobAfter - balanceBobFinal);
+    await helper.xTokens.transferMulticurrencies(bob, currencies, feeItem, destination, destWeight);
 
-    }, uniqueApiOptions);
+    balanceBobFinal = await helper.balance.getSubstrate(bob.address);
+    console.log('Relay (Westend) to Opal transaction fees: %s OPL', balanceBobAfter - balanceBobFinal);
   });
-
 });
modifiedtests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -14,53 +14,24 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-
-import {WsProvider, Keyring} from '@polkadot/api';
-import {ApiOptions} from '@polkadot/api/types';
 import {IKeyringPair} from '@polkadot/types/types';
-import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
-import {getGenericResult, generateKeyringPair, waitEvent, describeXCM, bigIntToDecimals} from '../deprecated-helpers/helpers';
-import {MultiLocation} from '@polkadot/types/interfaces';
 import {blake2AsHex} from '@polkadot/util-crypto';
-import waitNewBlocks from '../substrate/wait-new-blocks';
-import getBalance from '../substrate/get-balance';
+import config from '../config';
 import {XcmV2TraitsOutcome, XcmV2TraitsError} from '../interfaces';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
+import {itSub, expect, describeXCM, usingPlaygrounds, usingKaruraPlaygrounds, usingRelayPlaygrounds, usingMoonriverPlaygrounds} from '../util';
 
 const QUARTZ_CHAIN = 2095;
 const KARURA_CHAIN = 2000;
 const MOONRIVER_CHAIN = 2023;
 
-const RELAY_PORT = 9844;
-const KARURA_PORT = 9946;
-const MOONRIVER_PORT = 9947;
+const relayUrl = config.relayUrl;
+const karuraUrl = config.karuraUrl;
+const moonriverUrl = config.moonriverUrl;
 
 const KARURA_DECIMALS = 12;
 
 const TRANSFER_AMOUNT = 2000000000000000000000000n;
 
-function parachainApiOptions(port: number): ApiOptions {
-  return {
-    provider: new WsProvider('ws://127.0.0.1:' + port.toString()),
-  };
-}
-
-function karuraOptions(): ApiOptions {
-  return parachainApiOptions(KARURA_PORT);
-}
-
-function moonriverOptions(): ApiOptions {
-  return parachainApiOptions(MOONRIVER_PORT);
-}
-
-function relayOptions(): ApiOptions {
-  return parachainApiOptions(RELAY_PORT);
-}
-
 describeXCM('[XCM] Integration test: Exchanging tokens with Karura', () => {
   let alice: IKeyringPair;
   let randomAccount: IKeyringPair;
@@ -76,219 +47,162 @@
   let balanceQuartzForeignTokenFinal: bigint;
 
   before(async () => {
-    console.log('hey babe');
-    await usingApi(async (api, privateKeyWrapper) => {
-      const keyringSr25519 = new Keyring({type: 'sr25519'});
-
-      alice = privateKeyWrapper('//Alice');
-      randomAccount = generateKeyringPair(keyringSr25519);
+    await usingPlaygrounds(async (helper, privateKey) => {
+      alice = await privateKey('//Alice');
+      [randomAccount] = await helper.arrange.createAccounts([0n], alice);
     });
 
-    // Karura side
-    await usingApi(
-      async (api) => {
-        const destination = {
-          V0: {
-            X2: [
-              'Parent',
-              {
-                Parachain: QUARTZ_CHAIN,
-              },
-            ],
-          },
-        };
-
-        const metadata = {
-          name: 'QTZ',
-          symbol: 'QTZ',
-          decimals: 18,
-          minimalBalance: 1,
-        };
-
-        const tx = api.tx.assetRegistry.registerForeignAsset(destination, metadata);
-        const sudoTx = api.tx.sudo.sudo(tx as any);
-        const events = await submitTransactionAsync(alice, sudoTx);
-        const result = getGenericResult(events);
-        expect(result.success).to.be.true;
-
-        const tx1 = api.tx.balances.transfer(randomAccount.address, 10000000000000n);
-        const events1 = await submitTransactionAsync(alice, tx1);
-        const result1 = getGenericResult(events1);
-        expect(result1.success).to.be.true;
-
-        [balanceKaruraTokenInit] = await getBalance(api, [randomAccount.address]);
-        {
-          const {free} = (await api.query.tokens.accounts(randomAccount.addressRaw, {ForeignAsset: 0})).toJSON() as any;
-          balanceQuartzForeignTokenInit = BigInt(free);
-        }
-      },
-      karuraOptions(),
-    );
-
-    // Quartz side
-    await usingApi(async (api) => {
-      const tx0 = api.tx.balances.transfer(randomAccount.address, 10n * TRANSFER_AMOUNT);
-      const events0 = await submitTransactionAsync(alice, tx0);
-      const result0 = getGenericResult(events0);
-      expect(result0.success).to.be.true;
-
-      [balanceQuartzTokenInit] = await getBalance(api, [randomAccount.address]);
-    });
-  });
-
-  it('Should connect and send QTZ to Karura', async () => {
-
-    // Quartz side
-    await usingApi(async (api) => {
-
+    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
       const destination = {
         V0: {
           X2: [
             'Parent',
             {
-              Parachain: KARURA_CHAIN,
+              Parachain: QUARTZ_CHAIN,
             },
           ],
         },
       };
 
-      const beneficiary = {
-        V0: {
-          X1: {
-            AccountId32: {
-              network: 'Any',
-              id: randomAccount.addressRaw,
-            },
-          },
-        },
+      const metadata = {
+        name: 'QTZ',
+        symbol: 'QTZ',
+        decimals: 18,
+        minimalBalance: 1n,
       };
 
-      const assets = {
-        V1: [
+      await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);
+      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);
+      balanceKaruraTokenInit = await helper.balance.getSubstrate(randomAccount.address);
+      balanceQuartzForeignTokenInit = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});
+    });
+
+    await usingPlaygrounds(async (helper) => {
+      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10n * TRANSFER_AMOUNT);
+      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccount.address);
+    });
+  });
+
+  itSub('Should connect and send QTZ to Karura', async ({helper}) => {
+    const destination = {
+      V0: {
+        X2: [
+          'Parent',
           {
-            id: {
-              Concrete: {
-                parents: 0,
-                interior: 'Here',
-              },
-            },
-            fun: {
-              Fungible: TRANSFER_AMOUNT,
-            },
+            Parachain: KARURA_CHAIN,
           },
         ],
-      };
-
-      const feeAssetItem = 0;
+      },
+    };
 
-      const weightLimit = {
-        Limited: 5000000000,
-      };
+    const beneficiary = {
+      V0: {
+        X1: {
+          AccountId32: {
+            network: 'Any',
+            id: randomAccount.addressRaw,
+          },
+        },
+      },
+    };
 
-      const tx = api.tx.polkadotXcm.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
-      const events = await submitTransactionAsync(randomAccount, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
+    const assets = {
+      V1: [
+        {
+          id: {
+            Concrete: {
+              parents: 0,
+              interior: 'Here',
+            },
+          },
+          fun: {
+            Fungible: TRANSFER_AMOUNT,
+          },
+        },
+      ],
+    };
 
-      [balanceQuartzTokenMiddle] = await getBalance(api, [randomAccount.address]);
+    const feeAssetItem = 0;
+    const weightLimit = 5000000000;
 
-      const qtzFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;
-      console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', bigIntToDecimals(qtzFees));
-      expect(qtzFees > 0n).to.be.true;
-    });
+    await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, weightLimit);
+    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);
 
-    // Karura side
-    await usingApi(
-      async (api) => {
-        await waitNewBlocks(api, 3);
-        const {free} = (await api.query.tokens.accounts(randomAccount.addressRaw, {ForeignAsset: 0})).toJSON() as any;
-        balanceQuartzForeignTokenMiddle = BigInt(free);
+    const qtzFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;
+    console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));
+    expect(qtzFees > 0n).to.be.true;
 
-        [balanceKaruraTokenMiddle] = await getBalance(api, [randomAccount.address]);
+    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
+      await helper.wait.newBlocks(3);
+      balanceQuartzForeignTokenMiddle = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});
+      balanceKaruraTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);
 
-        const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;
-        const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;
+      const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;
+      const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;
 
-        console.log(
-          '[Quartz -> Karura] transaction fees on Karura: %s KAR',
-          bigIntToDecimals(karFees, KARURA_DECIMALS),
-        );
-        console.log('[Quartz -> Karura] income %s QTZ', bigIntToDecimals(qtzIncomeTransfer));
-        expect(karFees == 0n).to.be.true;
-        expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
-      },
-      karuraOptions(),
-    );
+      console.log(
+        '[Quartz -> Karura] transaction fees on Karura: %s KAR',
+        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),
+      );
+      console.log('[Quartz -> Karura] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));
+      expect(karFees == 0n).to.be.true;
+      expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
+    });
   });
 
-  it('Should connect to Karura and send QTZ back', async () => {
-
-    // Karura side
-    await usingApi(
-      async (api) => {
-        const destination = {
-          V1: {
-            parents: 1,
-            interior: {
-              X2: [
-                {Parachain: QUARTZ_CHAIN},
-                {
-                  AccountId32: {
-                    network: 'Any',
-                    id: randomAccount.addressRaw,
-                  },
+  itSub('Should connect to Karura and send QTZ back', async ({helper}) => {
+    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
+      const destination = {
+        V1: {
+          parents: 1,
+          interior: {
+            X2: [
+              {Parachain: QUARTZ_CHAIN},
+              {
+                AccountId32: {
+                  network: 'Any',
+                  id: randomAccount.addressRaw,
                 },
-              ],
-            },
+              },
+            ],
           },
-        };
-
-        const id = {
-          ForeignAsset: 0,
-        };
+        },
+      };
 
-        const destWeight = 50000000;
+      const id = {
+        ForeignAsset: 0,
+      };
 
-        const tx = api.tx.xTokens.transfer(id as any, TRANSFER_AMOUNT, destination, destWeight);
-        const events = await submitTransactionAsync(randomAccount, tx);
-        const result = getGenericResult(events);
-        expect(result.success).to.be.true;
+      const destWeight = 50000000;
 
-        [balanceKaruraTokenFinal] = await getBalance(api, [randomAccount.address]);
-        {
-          const {free} = (await api.query.tokens.accounts(randomAccount.addressRaw, id)).toJSON() as any;
-          balanceQuartzForeignTokenFinal = BigInt(free);
-        }
+      await helper.xTokens.transfer(randomAccount, id, TRANSFER_AMOUNT, destination, destWeight);
+      balanceKaruraTokenFinal = await helper.balance.getSubstrate(randomAccount.address);
+      balanceQuartzForeignTokenFinal = await helper.tokens.accounts(randomAccount.address, id);
 
-        const karFees = balanceKaruraTokenMiddle - balanceKaruraTokenFinal;
-        const qtzOutcomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenFinal;
+      const karFees = balanceKaruraTokenMiddle - balanceKaruraTokenFinal;
+      const qtzOutcomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenFinal;
 
-        console.log(
-          '[Karura -> Quartz] transaction fees on Karura: %s KAR',
-          bigIntToDecimals(karFees, KARURA_DECIMALS),
-        );
-        console.log('[Karura -> Quartz] outcome %s QTZ', bigIntToDecimals(qtzOutcomeTransfer));
+      console.log(
+        '[Karura -> Quartz] transaction fees on Karura: %s KAR',
+        helper.util.bigIntToDecimals(karFees, KARURA_DECIMALS),
+      );
+      console.log('[Karura -> Quartz] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));
 
-        expect(karFees > 0).to.be.true;
-        expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
-      },
-      karuraOptions(),
-    );
+      expect(karFees > 0).to.be.true;
+      expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
+    });
 
-    // Quartz side
-    await usingApi(async (api) => {
-      await waitNewBlocks(api, 3);
+    await helper.wait.newBlocks(3);
 
-      [balanceQuartzTokenFinal] = await getBalance(api, [randomAccount.address]);
-      const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;
-      expect(actuallyDelivered > 0).to.be.true;
+    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccount.address);
+    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;
+    expect(actuallyDelivered > 0).to.be.true;
 
-      console.log('[Karura -> Quartz] actually delivered %s QTZ', bigIntToDecimals(actuallyDelivered));
+    console.log('[Karura -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));
 
-      const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;
-      console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', bigIntToDecimals(qtzFees));
-      expect(qtzFees == 0n).to.be.true;
-    });
+    const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;
+    console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));
+    expect(qtzFees == 0n).to.be.true;
   });
 });
 
@@ -297,13 +211,13 @@
   let alice: IKeyringPair;
 
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
+    await usingPlaygrounds(async (_helper, privateKey) => {
+      alice = await privateKey('//Alice');
     });
   });
 
-  it('Quartz rejects tokens from the Relay', async () => {
-    await usingApi(async (api) => {
+  itSub('Quartz rejects tokens from the Relay', async ({helper}) => {
+    await usingRelayPlaygrounds(relayUrl, async (helper) => {
       const destination = {
         V1: {
           parents: 0,
@@ -342,49 +256,37 @@
       };
 
       const feeAssetItem = 0;
+      const weightLimit = 5_000_000_000;
 
-      const weightLimit = {
-        Limited: 5_000_000_000,
-      };
+      await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, weightLimit);
+    });
 
-      const tx = api.tx.xcmPallet.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
-      const events = await submitTransactionAsync(alice, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
-    }, relayOptions());
+    const maxWaitBlocks = 3;
 
-    await usingApi(async api => {
-      const maxWaitBlocks = 3;
-      const dmpQueueExecutedDownward = await waitEvent(
-        api,
-        maxWaitBlocks,
-        'dmpQueue',
-        'ExecutedDownward',
-      );
+    const dmpQueueExecutedDownward = await helper.wait.event(maxWaitBlocks, 'dmpQueue', 'ExecutedDownward');
 
-      expect(
-        dmpQueueExecutedDownward != null,
-        '[Relay] dmpQueue.ExecutedDownward event is expected',
-      ).to.be.true;
+    expect(
+      dmpQueueExecutedDownward != null,
+      '[Relay] dmpQueue.ExecutedDownward event is expected',
+    ).to.be.true;
 
-      const event = dmpQueueExecutedDownward!.event;
-      const outcome = event.data[1] as XcmV2TraitsOutcome;
+    const event = dmpQueueExecutedDownward!.event;
+    const outcome = event.data[1] as XcmV2TraitsOutcome;
 
-      expect(
-        outcome.isIncomplete,
-        '[Relay] The outcome of the XCM should be `Incomplete`',
-      ).to.be.true;
+    expect(
+      outcome.isIncomplete,
+      '[Relay] The outcome of the XCM should be `Incomplete`',
+    ).to.be.true;
 
-      const incomplete = outcome.asIncomplete;
-      expect(
-        incomplete[1].toString() == 'AssetNotFound',
-        '[Relay] The XCM error should be `AssetNotFound`',
-      ).to.be.true;
-    });
+    const incomplete = outcome.asIncomplete;
+    expect(
+      incomplete[1].toString() == 'AssetNotFound',
+      '[Relay] The XCM error should be `AssetNotFound`',
+    ).to.be.true;
   });
 
-  it('Quartz rejects KAR tokens from Karura', async () => {
-    await usingApi(async (api) => {
+  itSub('Quartz rejects KAR tokens from Karura', async ({helper}) => {
+    await usingKaruraPlaygrounds(karuraUrl, async (helper) => {
       const destination = {
         V1: {
           parents: 1,
@@ -408,35 +310,31 @@
 
       const destWeight = 50000000;
 
-      const tx = api.tx.xTokens.transfer(id as any, 100_000_000_000, destination, destWeight);
-      const events = await submitTransactionAsync(alice, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
-    }, karuraOptions());
+      await helper.xTokens.transfer(alice, id, 100_000_000_000n, destination, destWeight);
+    });
 
-    await usingApi(async api => {
-      const maxWaitBlocks = 3;
-      const xcmpQueueFailEvent = await waitEvent(api, maxWaitBlocks, 'xcmpQueue', 'Fail');
+    const maxWaitBlocks = 3;
+
+    const xcmpQueueFailEvent = await helper.wait.event(maxWaitBlocks, 'xcmpQueue', 'Fail');
 
-      expect(
-        xcmpQueueFailEvent != null,
-        '[Karura] xcmpQueue.FailEvent event is expected',
-      ).to.be.true;
+    expect(
+      xcmpQueueFailEvent != null,
+      '[Karura] xcmpQueue.FailEvent event is expected',
+    ).to.be.true;
 
-      const event = xcmpQueueFailEvent!.event;
-      const outcome = event.data[1] as XcmV2TraitsError;
+    const event = xcmpQueueFailEvent!.event;
+    const outcome = event.data[1] as XcmV2TraitsError;
 
-      expect(
-        outcome.isUntrustedReserveLocation,
-        '[Karura] The XCM error should be `UntrustedReserveLocation`',
-      ).to.be.true;
-    });
+    expect(
+      outcome.isUntrustedReserveLocation,
+      '[Karura] The XCM error should be `UntrustedReserveLocation`',
+    ).to.be.true;
   });
 });
 
 describeXCM('[XCM] Integration test: Exchanging QTZ with Moonriver', () => {
   // Quartz constants
-  let quartzAlice: IKeyringPair;
+  let quartzDonor: IKeyringPair;
   let quartzAssetLocation;
 
   let randomAccountQuartz: IKeyringPair;
@@ -444,15 +342,6 @@
 
   // Moonriver constants
   let assetId: string;
-
-  const moonriverKeyring = new Keyring({type: 'ethereum'});
-  const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';
-  const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';
-  const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';
-
-  const alithAccount = moonriverKeyring.addFromUri(alithPrivateKey, undefined, 'ethereum');
-  const baltatharAccount = moonriverKeyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');
-  const dorothyAccount = moonriverKeyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');
 
   const councilVotingThreshold = 2;
   const technicalCommitteeThreshold = 2;
@@ -464,7 +353,7 @@
     symbol: 'xcQTZ',
     decimals: 18,
     isFrozen: false,
-    minimalBalance: 1,
+    minimalBalance: 1n,
   };
 
   let balanceQuartzTokenInit: bigint;
@@ -478,322 +367,229 @@
   let balanceMovrTokenFinal: bigint;
 
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      const keyringEth = new Keyring({type: 'ethereum'});
-      const keyringSr25519 = new Keyring({type: 'sr25519'});
-
-      quartzAlice = privateKeyWrapper('//Alice');
-      randomAccountQuartz = generateKeyringPair(keyringSr25519);
-      randomAccountMoonriver = generateKeyringPair(keyringEth);
+    await usingPlaygrounds(async (helper, privateKey) => {
+      quartzDonor = await privateKey('//Alice');
+      [randomAccountQuartz] = await helper.arrange.createAccounts([0n], quartzDonor);
 
       balanceForeignQtzTokenInit = 0n;
     });
 
-    await usingApi(
-      async (api) => {
+    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {
+      const alithAccount = helper.account.alithAccount();
+      const baltatharAccount = helper.account.baltatharAccount();
+      const dorothyAccount = helper.account.dorothyAccount();
 
-        // >>> Sponsoring Dorothy >>>
-        console.log('Sponsoring Dorothy.......');
-        const tx0 = api.tx.balances.transfer(dorothyAccount.address, 11_000_000_000_000_000_000n);
-        const events0 = await submitTransactionAsync(alithAccount, tx0);
-        const result0 = getGenericResult(events0);
-        expect(result0.success).to.be.true;
-        console.log('Sponsoring Dorothy.......DONE');
-        // <<< Sponsoring Dorothy <<<
+      randomAccountMoonriver = helper.account.create();
 
-        const sourceLocation: MultiLocation = api.createType(
-          'MultiLocation',
-          {
-            parents: 1,
-            interior: {X1: {Parachain: QUARTZ_CHAIN}},
-          },
-        );
+      // >>> Sponsoring Dorothy >>>
+      console.log('Sponsoring Dorothy.......');
+      await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);
+      console.log('Sponsoring Dorothy.......DONE');
+      // <<< Sponsoring Dorothy <<<
 
-        quartzAssetLocation = {XCM: sourceLocation};
-        const existentialDeposit = 1;
-        const isSufficient = true;
-        const unitsPerSecond = '1';
-        const numAssetsWeightHint = 0;
+      quartzAssetLocation = {
+        XCM: {
+          parents: 1,
+          interior: {X1: {Parachain: QUARTZ_CHAIN}},
+        },
+      };
+      const existentialDeposit = 1n;
+      const isSufficient = true;
+      const unitsPerSecond = 1n;
+      const numAssetsWeightHint = 0;
 
-        const registerTx = api.tx.assetManager.registerForeignAsset(
-          quartzAssetLocation,
-          quartzAssetMetadata,
-          existentialDeposit,
-          isSufficient,
-        );
-        console.log('Encoded proposal for registerAsset is %s', registerTx.method.toHex() || '');
-
-        const setUnitsTx = api.tx.assetManager.setAssetUnitsPerSecond(
-          quartzAssetLocation,
-          unitsPerSecond,
-          numAssetsWeightHint,
-        );
-        console.log('Encoded proposal for setAssetUnitsPerSecond is %s', setUnitsTx.method.toHex() || '');
-
-        const batchCall = api.tx.utility.batchAll([registerTx, setUnitsTx]);
-        console.log('Encoded proposal for batchCall is %s', batchCall.method.toHex() || '');
-
-        // >>> Note motion preimage >>>
-        console.log('Note motion preimage.......');
-        const encodedProposal = batchCall?.method.toHex() || '';
-        const proposalHash = blake2AsHex(encodedProposal);
-        console.log('Encoded proposal for batch utility after schedule is %s', encodedProposal);
-        console.log('Encoded proposal hash for batch utility after schedule is %s', proposalHash);
-        console.log('Encoded length %d', encodedProposal.length);
+      const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({
+        location: quartzAssetLocation,
+        metadata: quartzAssetMetadata,
+        existentialDeposit,
+        isSufficient,
+        unitsPerSecond,
+        numAssetsWeightHint,
+      });
+      const proposalHash = blake2AsHex(encodedProposal);
 
-        const tx1 = api.tx.democracy.notePreimage(encodedProposal);
-        const events1 = await submitTransactionAsync(baltatharAccount, tx1);
-        const result1 = getGenericResult(events1);
-        expect(result1.success).to.be.true;
-        console.log('Note motion preimage.......DONE');
-        // <<< Note motion preimage <<<
+      console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);
+      console.log('Encoded length %d', encodedProposal.length);
+      console.log('Encoded proposal hash for batch utility after schedule is %s', proposalHash);
 
-        // >>> Propose external motion through council >>>
-        console.log('Propose external motion through council.......');
-        const externalMotion = api.tx.democracy.externalProposeMajority(proposalHash);
-        const tx2 = api.tx.councilCollective.propose(
-          councilVotingThreshold,
-          externalMotion,
-          externalMotion.encodedLength,
-        );
-        const events2 = await submitTransactionAsync(baltatharAccount, tx2);
-        const result2 = getGenericResult(events2);
-        expect(result2.success).to.be.true;
+      // >>> Note motion preimage >>>
+      console.log('Note motion preimage.......');
+      await helper.democracy.notePreimage(baltatharAccount, encodedProposal);
+      console.log('Note motion preimage.......DONE');
+      // <<< Note motion preimage <<<
 
-        const encodedMotion = externalMotion?.method.toHex() || '';
-        const motionHash = blake2AsHex(encodedMotion);
-        console.log('Motion hash is %s', motionHash);
+      // >>> Propose external motion through council >>>
+      console.log('Propose external motion through council.......');
+      const externalMotion = helper.democracy.externalProposeMajority(proposalHash);
+      const encodedMotion = externalMotion?.method.toHex() || '';
+      const motionHash = blake2AsHex(encodedMotion);
+      console.log('Motion hash is %s', motionHash);
 
-        const tx3 = api.tx.councilCollective.vote(motionHash, 0, true);
-        {
-          const events3 = await submitTransactionAsync(dorothyAccount, tx3);
-          const result3 = getGenericResult(events3);
-          expect(result3.success).to.be.true;
-        }
-        {
-          const events3 = await submitTransactionAsync(baltatharAccount, tx3);
-          const result3 = getGenericResult(events3);
-          expect(result3.success).to.be.true;
-        }
+      await helper.collective.council.propose(baltatharAccount, councilVotingThreshold, externalMotion, externalMotion.encodedLength);
 
-        const tx4 = api.tx.councilCollective.close(motionHash, 0, 1_000_000_000, externalMotion.encodedLength);
-        const events4 = await submitTransactionAsync(dorothyAccount, tx4);
-        const result4 = getGenericResult(events4);
-        expect(result4.success).to.be.true;
-        console.log('Propose external motion through council.......DONE');
-        // <<< Propose external motion through council <<<
+      const councilProposalIdx = await helper.collective.council.proposalCount() - 1;
+      await helper.collective.council.vote(dorothyAccount, motionHash, councilProposalIdx, true);
+      await helper.collective.council.vote(baltatharAccount, motionHash, councilProposalIdx, true);
 
-        // >>> Fast track proposal through technical committee >>>
-        console.log('Fast track proposal through technical committee.......');
-        const fastTrack = api.tx.democracy.fastTrack(proposalHash, votingPeriod, delayPeriod);
-        const tx5 = api.tx.techCommitteeCollective.propose(
-          technicalCommitteeThreshold,
-          fastTrack,
-          fastTrack.encodedLength,
-        );
-        const events5 = await submitTransactionAsync(alithAccount, tx5);
-        const result5 = getGenericResult(events5);
-        expect(result5.success).to.be.true;
+      await helper.collective.council.close(dorothyAccount, motionHash, councilProposalIdx, 1_000_000_000, externalMotion.encodedLength);
+      console.log('Propose external motion through council.......DONE');
+      // <<< Propose external motion through council <<<
 
-        const encodedFastTrack = fastTrack?.method.toHex() || '';
-        const fastTrackHash = blake2AsHex(encodedFastTrack);
-        console.log('FastTrack hash is %s', fastTrackHash);
+      // >>> Fast track proposal through technical committee >>>
+      console.log('Fast track proposal through technical committee.......');
+      const fastTrack = helper.democracy.fastTrack(proposalHash, votingPeriod, delayPeriod);
+      const encodedFastTrack = fastTrack?.method.toHex() || '';
+      const fastTrackHash = blake2AsHex(encodedFastTrack);
+      console.log('FastTrack hash is %s', fastTrackHash);
 
-        const proposalIdx = Number(await api.query.techCommitteeCollective.proposalCount()) - 1;
-        const tx6 = api.tx.techCommitteeCollective.vote(fastTrackHash, proposalIdx, true);
-        {
-          const events6 = await submitTransactionAsync(baltatharAccount, tx6);
-          const result6 = getGenericResult(events6);
-          expect(result6.success).to.be.true;
-        }
-        {
-          const events6 = await submitTransactionAsync(alithAccount, tx6);
-          const result6 = getGenericResult(events6);
-          expect(result6.success).to.be.true;
-        }
+      await helper.collective.techCommittee.propose(alithAccount, technicalCommitteeThreshold, fastTrack, fastTrack.encodedLength);
 
-        const tx7 = api.tx.techCommitteeCollective
-          .close(fastTrackHash, proposalIdx, 1_000_000_000, fastTrack.encodedLength);
-        const events7 = await submitTransactionAsync(baltatharAccount, tx7);
-        const result7 = getGenericResult(events7);
-        expect(result7.success).to.be.true;
-        console.log('Fast track proposal through technical committee.......DONE');
-        // <<< Fast track proposal through technical committee <<<
+      const techProposalIdx = await helper.collective.techCommittee.proposalCount() - 1;
+      await helper.collective.techCommittee.vote(baltatharAccount, fastTrackHash, techProposalIdx, true);
+      await helper.collective.techCommittee.vote(alithAccount, fastTrackHash, techProposalIdx, true);
 
-        // >>> Referendum voting >>>
-        console.log('Referendum voting.......');
-        const tx8 = api.tx.democracy.vote(
-          0,
-          {Standard: {balance: 10_000_000_000_000_000_000n, vote: {aye: true, conviction: 1}}},
-        );
-        const events8 = await submitTransactionAsync(dorothyAccount, tx8);
-        const result8 = getGenericResult(events8);
-        expect(result8.success).to.be.true;
-        console.log('Referendum voting.......DONE');
-        // <<< Referendum voting <<<
+      await helper.collective.techCommittee.close(baltatharAccount, fastTrackHash, techProposalIdx, 1_000_000_000, fastTrack.encodedLength);
+      console.log('Fast track proposal through technical committee.......DONE');
+      // <<< Fast track proposal through technical committee <<<
 
-        // >>> Acquire Quartz AssetId Info on Moonriver >>>
-        console.log('Acquire Quartz AssetId Info on Moonriver.......');
+      // >>> Referendum voting >>>
+      console.log('Referendum voting.......');
+      await helper.democracy.referendumVote(dorothyAccount, 0, {
+        balance: 10_000_000_000_000_000_000n,
+        vote: {aye: true, conviction: 1},
+      });
+      console.log('Referendum voting.......DONE');
+      // <<< Referendum voting <<<
 
-        // Wait for the democracy execute
-        await waitNewBlocks(api, 5);
+      // >>> Acquire Quartz AssetId Info on Moonriver >>>
+      console.log('Acquire Quartz AssetId Info on Moonriver.......');
 
-        assetId = (await api.query.assetManager.assetTypeId({
-          XCM: sourceLocation,
-        })).toString();
+      // Wait for the democracy execute
+      await helper.wait.newBlocks(5);
 
-        console.log('QTZ asset ID is %s', assetId);
-        console.log('Acquire Quartz AssetId Info on Moonriver.......DONE');
-        // >>> Acquire Quartz AssetId Info on Moonriver >>>
+      assetId = (await helper.assetManager.assetTypeId(quartzAssetLocation)).toString();
 
-        // >>> Sponsoring random Account >>>
-        console.log('Sponsoring random Account.......');
-        const tx10 = api.tx.balances.transfer(randomAccountMoonriver.address, 11_000_000_000_000_000_000n);
-        const events10 = await submitTransactionAsync(baltatharAccount, tx10);
-        const result10 = getGenericResult(events10);
-        expect(result10.success).to.be.true;
-        console.log('Sponsoring random Account.......DONE');
-        // <<< Sponsoring random Account <<<
+      console.log('QTZ asset ID is %s', assetId);
+      console.log('Acquire Quartz AssetId Info on Moonriver.......DONE');
+      // >>> Acquire Quartz AssetId Info on Moonriver >>>
 
-        [balanceMovrTokenInit] = await getBalance(api, [randomAccountMoonriver.address]);
-      },
-      moonriverOptions(),
-    );
+      // >>> Sponsoring random Account >>>
+      console.log('Sponsoring random Account.......');
+      await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonriver.address, 11_000_000_000_000_000_000n);
+      console.log('Sponsoring random Account.......DONE');
+      // <<< Sponsoring random Account <<<
 
-    await usingApi(async (api) => {
-      const tx0 = api.tx.balances.transfer(randomAccountQuartz.address, 10n * TRANSFER_AMOUNT);
-      const events0 = await submitTransactionAsync(quartzAlice, tx0);
-      const result0 = getGenericResult(events0);
-      expect(result0.success).to.be.true;
+      balanceMovrTokenInit = await helper.balance.getEthereum(randomAccountMoonriver.address);
+    });
 
-      [balanceQuartzTokenInit] = await getBalance(api, [randomAccountQuartz.address]);
+    await usingPlaygrounds(async (helper) => {
+      await helper.balance.transferToSubstrate(quartzDonor, randomAccountQuartz.address, 10n * TRANSFER_AMOUNT);
+      balanceQuartzTokenInit = await helper.balance.getSubstrate(randomAccountQuartz.address);
     });
   });
 
-  it('Should connect and send QTZ to Moonriver', async () => {
-    await usingApi(async (api) => {
-      const currencyId = {
-        NativeAssetId: 'Here',
-      };
-      const dest = {
-        V1: {
-          parents: 1,
-          interior: {
-            X2: [
-              {Parachain: MOONRIVER_CHAIN},
-              {AccountKey20: {network: 'Any', key: randomAccountMoonriver.address}},
-            ],
-          },
+  itSub('Should connect and send QTZ to Moonriver', async ({helper}) => {
+    const currencyId = {
+      NativeAssetId: 'Here',
+    };
+    const dest = {
+      V1: {
+        parents: 1,
+        interior: {
+          X2: [
+            {Parachain: MOONRIVER_CHAIN},
+            {AccountKey20: {network: 'Any', key: randomAccountMoonriver.address}},
+          ],
         },
-      };
-      const amount = TRANSFER_AMOUNT;
-      const destWeight = 850000000;
+      },
+    };
+    const amount = TRANSFER_AMOUNT;
+    const destWeight = 850000000;
 
-      const tx = api.tx.xTokens.transfer(currencyId, amount, dest, destWeight);
-      const events = await submitTransactionAsync(randomAccountQuartz, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
+    await helper.xTokens.transfer(randomAccountQuartz, currencyId, amount, dest, destWeight);
 
-      [balanceQuartzTokenMiddle] = await getBalance(api, [randomAccountQuartz.address]);
-      expect(balanceQuartzTokenMiddle < balanceQuartzTokenInit).to.be.true;
+    balanceQuartzTokenMiddle = await helper.balance.getSubstrate(randomAccountQuartz.address);
+    expect(balanceQuartzTokenMiddle < balanceQuartzTokenInit).to.be.true;
 
-      const transactionFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;
-      console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', bigIntToDecimals(transactionFees));
-      expect(transactionFees > 0).to.be.true;
-    });
+    const transactionFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;
+    console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(transactionFees));
+    expect(transactionFees > 0).to.be.true;
 
-    await usingApi(
-      async (api) => {
-        await waitNewBlocks(api, 3);
+    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {
+      await helper.wait.newBlocks(3);
 
-        [balanceMovrTokenMiddle] = await getBalance(api, [randomAccountMoonriver.address]);
+      balanceMovrTokenMiddle = await helper.balance.getEthereum(randomAccountMoonriver.address);
 
-        const movrFees = balanceMovrTokenInit - balanceMovrTokenMiddle;
-        console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR',bigIntToDecimals(movrFees));
-        expect(movrFees == 0n).to.be.true;
+      const movrFees = balanceMovrTokenInit - balanceMovrTokenMiddle;
+      console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR',helper.util.bigIntToDecimals(movrFees));
+      expect(movrFees == 0n).to.be.true;
 
-        const qtzRandomAccountAsset = (
-          await api.query.assets.account(assetId, randomAccountMoonriver.address)
-        ).toJSON()! as any;
-
-        balanceForeignQtzTokenMiddle = BigInt(qtzRandomAccountAsset['balance']);
-        const qtzIncomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenInit;
-        console.log('[Quartz -> Moonriver] income %s QTZ', bigIntToDecimals(qtzIncomeTransfer));
-        expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
-      },
-      moonriverOptions(),
-    );
+      balanceForeignQtzTokenMiddle = (await helper.assets.account(assetId, randomAccountMoonriver.address))!; // BigInt(qtzRandomAccountAsset['balance']);
+      const qtzIncomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenInit;
+      console.log('[Quartz -> Moonriver] income %s QTZ', helper.util.bigIntToDecimals(qtzIncomeTransfer));
+      expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
+    });
   });
 
-  it('Should connect to Moonriver and send QTZ back', async () => {
-    await usingApi(
-      async (api) => {
-        const asset = {
-          V1: {
-            id: {
-              Concrete: {
-                parents: 1,
-                interior: {
-                  X1: {Parachain: QUARTZ_CHAIN},
-                },
+  itSub('Should connect to Moonriver and send QTZ back', async ({helper}) => {
+    await usingMoonriverPlaygrounds(moonriverUrl, async (helper) => {
+      const asset = {
+        V1: {
+          id: {
+            Concrete: {
+              parents: 1,
+              interior: {
+                X1: {Parachain: QUARTZ_CHAIN},
               },
-            },
-            fun: {
-              Fungible: TRANSFER_AMOUNT,
             },
           },
-        };
-        const destination = {
-          V1: {
-            parents: 1,
-            interior: {
-              X2: [
-                {Parachain: QUARTZ_CHAIN},
-                {AccountId32: {network: 'Any', id: randomAccountQuartz.addressRaw}},
-              ],
-            },
+          fun: {
+            Fungible: TRANSFER_AMOUNT,
           },
-        };
-        const destWeight = 50000000;
+        },
+      };
+      const destination = {
+        V1: {
+          parents: 1,
+          interior: {
+            X2: [
+              {Parachain: QUARTZ_CHAIN},
+              {AccountId32: {network: 'Any', id: randomAccountQuartz.addressRaw}},
+            ],
+          },
+        },
+      };
+      const destWeight = 50000000;
 
-        const tx = api.tx.xTokens.transferMultiasset(asset, destination, destWeight);
-        const events = await submitTransactionAsync(randomAccountMoonriver, tx);
-        const result = getGenericResult(events);
-        expect(result.success).to.be.true;
+      await helper.xTokens.transferMultiasset(randomAccountMoonriver, asset, destination, destWeight);
 
-        [balanceMovrTokenFinal] = await getBalance(api, [randomAccountMoonriver.address]);
+      balanceMovrTokenFinal = await helper.balance.getEthereum(randomAccountMoonriver.address);
 
-        const movrFees = balanceMovrTokenMiddle - balanceMovrTokenFinal;
-        console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', bigIntToDecimals(movrFees));
-        expect(movrFees > 0).to.be.true;
+      const movrFees = balanceMovrTokenMiddle - balanceMovrTokenFinal;
+      console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', helper.util.bigIntToDecimals(movrFees));
+      expect(movrFees > 0).to.be.true;
 
-        const qtzRandomAccountAsset = (
-          await api.query.assets.account(assetId, randomAccountMoonriver.address)
-        ).toJSON()! as any;
+      const qtzRandomAccountAsset = await helper.assets.account(assetId, randomAccountMoonriver.address);
 
-        expect(qtzRandomAccountAsset).to.be.null;
+      expect(qtzRandomAccountAsset).to.be.null;
 
-        balanceForeignQtzTokenFinal = 0n;
+      balanceForeignQtzTokenFinal = 0n;
 
-        const qtzOutcomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenFinal;
-        console.log('[Quartz -> Moonriver] outcome %s QTZ', bigIntToDecimals(qtzOutcomeTransfer));
-        expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
-      },
-      moonriverOptions(),
-    );
+      const qtzOutcomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenFinal;
+      console.log('[Quartz -> Moonriver] outcome %s QTZ', helper.util.bigIntToDecimals(qtzOutcomeTransfer));
+      expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
+    });
 
-    await usingApi(async (api) => {
-      await waitNewBlocks(api, 3);
+    await helper.wait.newBlocks(3);
 
-      [balanceQuartzTokenFinal] = await getBalance(api, [randomAccountQuartz.address]);
-      const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;
-      expect(actuallyDelivered > 0).to.be.true;
+    balanceQuartzTokenFinal = await helper.balance.getSubstrate(randomAccountQuartz.address);
+    const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;
+    expect(actuallyDelivered > 0).to.be.true;
 
-      console.log('[Moonriver -> Quartz] actually delivered %s QTZ', bigIntToDecimals(actuallyDelivered));
+    console.log('[Moonriver -> Quartz] actually delivered %s QTZ', helper.util.bigIntToDecimals(actuallyDelivered));
 
-      const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;
-      console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', bigIntToDecimals(qtzFees));
-      expect(qtzFees == 0n).to.be.true;
-    });
+    const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;
+    console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', helper.util.bigIntToDecimals(qtzFees));
+    expect(qtzFees == 0n).to.be.true;
   });
 });
modifiedtests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth
--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -14,53 +14,24 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-
-import {WsProvider, Keyring} from '@polkadot/api';
-import {ApiOptions} from '@polkadot/api/types';
 import {IKeyringPair} from '@polkadot/types/types';
-import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
-import {getGenericResult, generateKeyringPair, waitEvent, describeXCM, bigIntToDecimals} from '../deprecated-helpers/helpers';
-import {MultiLocation} from '@polkadot/types/interfaces';
 import {blake2AsHex} from '@polkadot/util-crypto';
-import waitNewBlocks from '../substrate/wait-new-blocks';
-import getBalance from '../substrate/get-balance';
+import config from '../config';
 import {XcmV2TraitsError, XcmV2TraitsOutcome} from '../interfaces';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
+import {itSub, expect, describeXCM, usingPlaygrounds, usingAcalaPlaygrounds, usingRelayPlaygrounds, usingMoonbeamPlaygrounds} from '../util';
 
 const UNIQUE_CHAIN = 2037;
 const ACALA_CHAIN = 2000;
 const MOONBEAM_CHAIN = 2004;
 
-const RELAY_PORT = 9844;
-const ACALA_PORT = 9946;
-const MOONBEAM_PORT = 9947;
+const relayUrl = config.relayUrl;
+const acalaUrl = config.acalaUrl;
+const moonbeamUrl = config.moonbeamUrl;
 
 const ACALA_DECIMALS = 12;
 
 const TRANSFER_AMOUNT = 2000000000000000000000000n;
 
-function parachainApiOptions(port: number): ApiOptions {
-  return {
-    provider: new WsProvider('ws://127.0.0.1:' + port.toString()),
-  };
-}
-
-function acalaOptions(): ApiOptions {
-  return parachainApiOptions(ACALA_PORT);
-}
-
-function moonbeamOptions(): ApiOptions {
-  return parachainApiOptions(MOONBEAM_PORT);
-}
-
-function relayOptions(): ApiOptions {
-  return parachainApiOptions(RELAY_PORT);
-}
-
 describeXCM('[XCM] Integration test: Exchanging tokens with Acala', () => {
   let alice: IKeyringPair;
   let randomAccount: IKeyringPair;
@@ -76,218 +47,166 @@
   let balanceUniqueForeignTokenFinal: bigint;
 
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      const keyringSr25519 = new Keyring({type: 'sr25519'});
-
-      alice = privateKeyWrapper('//Alice');
-      randomAccount = generateKeyringPair(keyringSr25519);
+    await usingPlaygrounds(async (helper, privateKey) => {
+      alice = await privateKey('//Alice');
+      [randomAccount] = await helper.arrange.createAccounts([0n], alice);
     });
 
-    // Acala side
-    await usingApi(
-      async (api) => {
-        const destination = {
-          V0: {
-            X2: [
-              'Parent',
-              {
-                Parachain: UNIQUE_CHAIN,
-              },
-            ],
-          },
-        };
-
-        const metadata = {
-          name: 'UNQ',
-          symbol: 'UNQ',
-          decimals: 18,
-          minimalBalance: 1,
-        };
-
-        const tx = api.tx.assetRegistry.registerForeignAsset(destination, metadata);
-        const sudoTx = api.tx.sudo.sudo(tx as any);
-        const events = await submitTransactionAsync(alice, sudoTx);
-        const result = getGenericResult(events);
-        expect(result.success).to.be.true;
-
-        const tx1 = api.tx.balances.transfer(randomAccount.address, 10000000000000n);
-        const events1 = await submitTransactionAsync(alice, tx1);
-        const result1 = getGenericResult(events1);
-        expect(result1.success).to.be.true;
-
-        [balanceAcalaTokenInit] = await getBalance(api, [randomAccount.address]);
-        {
-          const {free} = (await api.query.tokens.accounts(randomAccount.addressRaw, {ForeignAsset: 0})).toJSON() as any;
-          balanceUniqueForeignTokenInit = BigInt(free);
-        }
-      },
-      acalaOptions(),
-    );
-
-    // Unique side
-    await usingApi(async (api) => {
-      const tx0 = api.tx.balances.transfer(randomAccount.address, 10n * TRANSFER_AMOUNT);
-      const events0 = await submitTransactionAsync(alice, tx0);
-      const result0 = getGenericResult(events0);
-      expect(result0.success).to.be.true;
-
-      [balanceUniqueTokenInit] = await getBalance(api, [randomAccount.address]);
-    });
-  });
-
-  it('Should connect and send UNQ to Acala', async () => {
-
-    // Unique side
-    await usingApi(async (api) => {
-
+    await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
       const destination = {
         V0: {
           X2: [
             'Parent',
             {
-              Parachain: ACALA_CHAIN,
+              Parachain: UNIQUE_CHAIN,
             },
           ],
         },
       };
 
-      const beneficiary = {
-        V0: {
-          X1: {
-            AccountId32: {
-              network: 'Any',
-              id: randomAccount.addressRaw,
-            },
-          },
-        },
+      const metadata = {
+        name: 'UNQ',
+        symbol: 'UNQ',
+        decimals: 18,
+        minimalBalance: 1n,
       };
 
-      const assets = {
-        V1: [
+      await helper.getSudo().assetRegistry.registerForeignAsset(alice, destination, metadata);
+      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10000000000000n);
+      balanceAcalaTokenInit = await helper.balance.getSubstrate(randomAccount.address);
+      balanceUniqueForeignTokenInit = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});
+    });
+
+    await usingPlaygrounds(async (helper) => {
+      await helper.balance.transferToSubstrate(alice, randomAccount.address, 10n * TRANSFER_AMOUNT);
+      balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccount.address);
+    });
+  });
+
+  itSub('Should connect and send UNQ to Acala', async ({helper}) => {
+
+    const destination = {
+      V0: {
+        X2: [
+          'Parent',
           {
-            id: {
-              Concrete: {
-                parents: 0,
-                interior: 'Here',
-              },
-            },
-            fun: {
-              Fungible: TRANSFER_AMOUNT,
-            },
+            Parachain: ACALA_CHAIN,
           },
         ],
-      };
+      },
+    };
 
-      const feeAssetItem = 0;
+    const beneficiary = {
+      V0: {
+        X1: {
+          AccountId32: {
+            network: 'Any',
+            id: randomAccount.addressRaw,
+          },
+        },
+      },
+    };
 
-      const weightLimit = {
-        Limited: 5000000000,
-      };
+    const assets = {
+      V1: [
+        {
+          id: {
+            Concrete: {
+              parents: 0,
+              interior: 'Here',
+            },
+          },
+          fun: {
+            Fungible: TRANSFER_AMOUNT,
+          },
+        },
+      ],
+    };
+
+    const feeAssetItem = 0;
+    const weightLimit = 5000000000;
 
-      const tx = api.tx.polkadotXcm.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
-      const events = await submitTransactionAsync(randomAccount, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
+    await helper.xcm.limitedReserveTransferAssets(randomAccount, destination, beneficiary, assets, feeAssetItem, weightLimit);
 
-      [balanceUniqueTokenMiddle] = await getBalance(api, [randomAccount.address]);
+    balanceUniqueTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);
 
-      const unqFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;
-      console.log('[Unique -> Acala] transaction fees on Unique: %s UNQ', bigIntToDecimals(unqFees));
-      expect(unqFees > 0n).to.be.true;
-    });
+    const unqFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;
+    console.log('[Unique -> Acala] transaction fees on Unique: %s UNQ', helper.util.bigIntToDecimals(unqFees));
+    expect(unqFees > 0n).to.be.true;
 
-    // Acala side
-    await usingApi(
-      async (api) => {
-        await waitNewBlocks(api, 3);
-        const {free} = (await api.query.tokens.accounts(randomAccount.addressRaw, {ForeignAsset: 0})).toJSON() as any;
-        balanceUniqueForeignTokenMiddle = BigInt(free);
+    await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
+      await helper.wait.newBlocks(3);
 
-        [balanceAcalaTokenMiddle] = await getBalance(api, [randomAccount.address]);
+      balanceUniqueForeignTokenMiddle = await helper.tokens.accounts(randomAccount.address, {ForeignAsset: 0});
+      balanceAcalaTokenMiddle = await helper.balance.getSubstrate(randomAccount.address);
 
-        const acaFees = balanceAcalaTokenInit - balanceAcalaTokenMiddle;
-        const unqIncomeTransfer = balanceUniqueForeignTokenMiddle - balanceUniqueForeignTokenInit;
+      const acaFees = balanceAcalaTokenInit - balanceAcalaTokenMiddle;
+      const unqIncomeTransfer = balanceUniqueForeignTokenMiddle - balanceUniqueForeignTokenInit;
 
-        console.log(
-          '[Unique -> Acala] transaction fees on Acala: %s ACA',
-          bigIntToDecimals(acaFees, ACALA_DECIMALS),
-        );
-        console.log('[Unique -> Acala] income %s UNQ', bigIntToDecimals(unqIncomeTransfer));
-        expect(acaFees == 0n).to.be.true;
-        expect(unqIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
-      },
-      acalaOptions(),
-    );
+      console.log(
+        '[Unique -> Acala] transaction fees on Acala: %s ACA',
+        helper.util.bigIntToDecimals(acaFees, ACALA_DECIMALS),
+      );
+      console.log('[Unique -> Acala] income %s UNQ', helper.util.bigIntToDecimals(unqIncomeTransfer));
+      expect(acaFees == 0n).to.be.true;
+      expect(unqIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
+    });
   });
 
-  it('Should connect to Acala and send UNQ back', async () => {
-
-    // Acala side
-    await usingApi(
-      async (api) => {
-        const destination = {
-          V1: {
-            parents: 1,
-            interior: {
-              X2: [
-                {Parachain: UNIQUE_CHAIN},
-                {
-                  AccountId32: {
-                    network: 'Any',
-                    id: randomAccount.addressRaw,
-                  },
+  itSub('Should connect to Acala and send UNQ back', async ({helper}) => {
+    await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
+      const destination = {
+        V1: {
+          parents: 1,
+          interior: {
+            X2: [
+              {Parachain: UNIQUE_CHAIN},
+              {
+                AccountId32: {
+                  network: 'Any',
+                  id: randomAccount.addressRaw,
                 },
-              ],
-            },
+              },
+            ],
           },
-        };
+        },
+      };
 
-        const id = {
-          ForeignAsset: 0,
-        };
+      const id = {
+        ForeignAsset: 0,
+      };
 
-        const destWeight = 50000000;
+      const destWeight = 50000000;
 
-        const tx = api.tx.xTokens.transfer(id as any, TRANSFER_AMOUNT, destination, destWeight);
-        const events = await submitTransactionAsync(randomAccount, tx);
-        const result = getGenericResult(events);
-        expect(result.success).to.be.true;
+      await helper.xTokens.transfer(randomAccount, id, TRANSFER_AMOUNT, destination, destWeight);
 
-        [balanceAcalaTokenFinal] = await getBalance(api, [randomAccount.address]);
-        {
-          const {free} = (await api.query.tokens.accounts(randomAccount.addressRaw, id)).toJSON() as any;
-          balanceUniqueForeignTokenFinal = BigInt(free);
-        }
+      balanceAcalaTokenFinal = await helper.balance.getSubstrate(randomAccount.address);
+      balanceUniqueForeignTokenFinal = await helper.tokens.accounts(randomAccount.address, id);
 
-        const acaFees = balanceAcalaTokenMiddle - balanceAcalaTokenFinal;
-        const unqOutcomeTransfer = balanceUniqueForeignTokenMiddle - balanceUniqueForeignTokenFinal;
+      const acaFees = balanceAcalaTokenMiddle - balanceAcalaTokenFinal;
+      const unqOutcomeTransfer = balanceUniqueForeignTokenMiddle - balanceUniqueForeignTokenFinal;
 
-        console.log(
-          '[Acala -> Unique] transaction fees on Acala: %s ACA',
-          bigIntToDecimals(acaFees, ACALA_DECIMALS),
-        );
-        console.log('[Acala -> Unique] outcome %s UNQ', bigIntToDecimals(unqOutcomeTransfer));
+      console.log(
+        '[Acala -> Unique] transaction fees on Acala: %s ACA',
+        helper.util.bigIntToDecimals(acaFees, ACALA_DECIMALS),
+      );
+      console.log('[Acala -> Unique] outcome %s UNQ', helper.util.bigIntToDecimals(unqOutcomeTransfer));
 
-        expect(acaFees > 0).to.be.true;
-        expect(unqOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
-      },
-      acalaOptions(),
-    );
+      expect(acaFees > 0).to.be.true;
+      expect(unqOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
+    });
 
-    // Unique side
-    await usingApi(async (api) => {
-      await waitNewBlocks(api, 3);
+    await helper.wait.newBlocks(3);
 
-      [balanceUniqueTokenFinal] = await getBalance(api, [randomAccount.address]);
-      const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenMiddle;
-      expect(actuallyDelivered > 0).to.be.true;
+    balanceUniqueTokenFinal = await helper.balance.getSubstrate(randomAccount.address);
+    const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenMiddle;
+    expect(actuallyDelivered > 0).to.be.true;
 
-      console.log('[Acala -> Unique] actually delivered %s UNQ', bigIntToDecimals(actuallyDelivered));
+    console.log('[Acala -> Unique] actually delivered %s UNQ', helper.util.bigIntToDecimals(actuallyDelivered));
 
-      const unqFees = TRANSFER_AMOUNT - actuallyDelivered;
-      console.log('[Acala -> Unique] transaction fees on Unique: %s UNQ', bigIntToDecimals(unqFees));
-      expect(unqFees == 0n).to.be.true;
-    });
+    const unqFees = TRANSFER_AMOUNT - actuallyDelivered;
+    console.log('[Acala -> Unique] transaction fees on Unique: %s UNQ', helper.util.bigIntToDecimals(unqFees));
+    expect(unqFees == 0n).to.be.true;
   });
 });
 
@@ -296,13 +215,13 @@
   let alice: IKeyringPair;
 
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
+    await usingPlaygrounds(async (_helper, privateKey) => {
+      alice = await privateKey('//Alice');
     });
   });
 
-  it('Unique rejects tokens from the Relay', async () => {
-    await usingApi(async (api) => {
+  itSub('Unique rejects tokens from the Relay', async ({helper}) => {
+    await usingRelayPlaygrounds(relayUrl, async (helper) => {
       const destination = {
         V1: {
           parents: 0,
@@ -341,49 +260,37 @@
       };
 
       const feeAssetItem = 0;
+      const weightLimit = 5_000_000_000;
 
-      const weightLimit = {
-        Limited: 5_000_000_000,
-      };
+      await helper.xcm.limitedReserveTransferAssets(alice, destination, beneficiary, assets, feeAssetItem, weightLimit);
+    });
 
-      const tx = api.tx.xcmPallet.limitedReserveTransferAssets(destination, beneficiary, assets, feeAssetItem, weightLimit);
-      const events = await submitTransactionAsync(alice, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
-    }, relayOptions());
+    const maxWaitBlocks = 3;
 
-    await usingApi(async api => {
-      const maxWaitBlocks = 3;
-      const dmpQueueExecutedDownward = await waitEvent(
-        api,
-        maxWaitBlocks,
-        'dmpQueue',
-        'ExecutedDownward',
-      );
+    const dmpQueueExecutedDownward = await helper.wait.event(maxWaitBlocks, 'dmpQueue', 'ExecutedDownward');
 
-      expect(
-        dmpQueueExecutedDownward != null,
-        '[Relay] dmpQueue.ExecutedDownward event is expected',
-      ).to.be.true;
+    expect(
+      dmpQueueExecutedDownward != null,
+      '[Relay] dmpQueue.ExecutedDownward event is expected',
+    ).to.be.true;
 
-      const event = dmpQueueExecutedDownward!.event;
-      const outcome = event.data[1] as XcmV2TraitsOutcome;
+    const event = dmpQueueExecutedDownward!.event;
+    const outcome = event.data[1] as XcmV2TraitsOutcome;
 
-      expect(
-        outcome.isIncomplete,
-        '[Relay] The outcome of the XCM should be `Incomplete`',
-      ).to.be.true;
+    expect(
+      outcome.isIncomplete,
+      '[Relay] The outcome of the XCM should be `Incomplete`',
+    ).to.be.true;
 
-      const incomplete = outcome.asIncomplete;
-      expect(
-        incomplete[1].toString() == 'AssetNotFound',
-        '[Relay] The XCM error should be `AssetNotFound`',
-      ).to.be.true;
-    });
+    const incomplete = outcome.asIncomplete;
+    expect(
+      incomplete[1].toString() == 'AssetNotFound',
+      '[Relay] The XCM error should be `AssetNotFound`',
+    ).to.be.true;
   });
 
-  it('Unique rejects ACA tokens from Acala', async () => {
-    await usingApi(async (api) => {
+  itSub('Unique rejects ACA tokens from Acala', async ({helper}) => {
+    await usingAcalaPlaygrounds(acalaUrl, async (helper) => {
       const destination = {
         V1: {
           parents: 1,
@@ -407,36 +314,31 @@
 
       const destWeight = 50000000;
 
-      const tx = api.tx.xTokens.transfer(id as any, 100_000_000_000, destination, destWeight);
-      const events = await submitTransactionAsync(alice, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
-    }, acalaOptions());
+      await helper.xTokens.transfer(alice, id, 100_000_000_000n, destination, destWeight);
+    });
 
-    await usingApi(async api => {
-      const maxWaitBlocks = 3;
-      const xcmpQueueFailEvent = await waitEvent(api, maxWaitBlocks, 'xcmpQueue', 'Fail');
+    const maxWaitBlocks = 3;
 
-      expect(
-        xcmpQueueFailEvent != null,
-        '[Acala] xcmpQueue.FailEvent event is expected',
-      ).to.be.true;
+    const xcmpQueueFailEvent = await helper.wait.event(maxWaitBlocks, 'xcmpQueue', 'Fail');
+
+    expect(
+      xcmpQueueFailEvent != null,
+      '[Acala] xcmpQueue.FailEvent event is expected',
+    ).to.be.true;
 
-      const event = xcmpQueueFailEvent!.event;
-      const outcome = event.data[1] as XcmV2TraitsError;
+    const event = xcmpQueueFailEvent!.event;
+    const outcome = event.data[1] as XcmV2TraitsError;
 
-      expect(
-        outcome.isUntrustedReserveLocation,
-        '[Acala] The XCM error should be `UntrustedReserveLocation`',
-      ).to.be.true;
-    });
+    expect(
+      outcome.isUntrustedReserveLocation,
+      '[Acala] The XCM error should be `UntrustedReserveLocation`',
+    ).to.be.true;
   });
 });
 
 describeXCM('[XCM] Integration test: Exchanging UNQ with Moonbeam', () => {
-
   // Unique constants
-  let uniqueAlice: IKeyringPair;
+  let uniqueDonor: IKeyringPair;
   let uniqueAssetLocation;
 
   let randomAccountUnique: IKeyringPair;
@@ -445,15 +347,6 @@
   // Moonbeam constants
   let assetId: string;
 
-  const moonbeamKeyring = new Keyring({type: 'ethereum'});
-  const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';
-  const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';
-  const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';
-
-  const alithAccount = moonbeamKeyring.addFromUri(alithPrivateKey, undefined, 'ethereum');
-  const baltatharAccount = moonbeamKeyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');
-  const dorothyAccount = moonbeamKeyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');
-
   const councilVotingThreshold = 2;
   const technicalCommitteeThreshold = 2;
   const votingPeriod = 3;
@@ -464,7 +357,7 @@
     symbol: 'xcUNQ',
     decimals: 18,
     isFrozen: false,
-    minimalBalance: 1,
+    minimalBalance: 1n,
   };
 
   let balanceUniqueTokenInit: bigint;
@@ -478,322 +371,230 @@
   let balanceGlmrTokenFinal: bigint;
 
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      const keyringEth = new Keyring({type: 'ethereum'});
-      const keyringSr25519 = new Keyring({type: 'sr25519'});
+    await usingPlaygrounds(async (helper, privateKey) => {
+      uniqueDonor = await privateKey('//Alice');
+      [randomAccountUnique] = await helper.arrange.createAccounts([0n], uniqueDonor);
 
-      uniqueAlice = privateKeyWrapper('//Alice');
-      randomAccountUnique = generateKeyringPair(keyringSr25519);
-      randomAccountMoonbeam = generateKeyringPair(keyringEth);
-
       balanceForeignUnqTokenInit = 0n;
     });
 
-    await usingApi(
-      async (api) => {
+    await usingMoonbeamPlaygrounds(moonbeamUrl, async (helper) => {
+      const alithAccount = helper.account.alithAccount();
+      const baltatharAccount = helper.account.baltatharAccount();
+      const dorothyAccount = helper.account.dorothyAccount();
 
-        // >>> Sponsoring Dorothy >>>
-        console.log('Sponsoring Dorothy.......');
-        const tx0 = api.tx.balances.transfer(dorothyAccount.address, 11_000_000_000_000_000_000n);
-        const events0 = await submitTransactionAsync(alithAccount, tx0);
-        const result0 = getGenericResult(events0);
-        expect(result0.success).to.be.true;
-        console.log('Sponsoring Dorothy.......DONE');
-        // <<< Sponsoring Dorothy <<<
+      randomAccountMoonbeam = helper.account.create();
 
-        const sourceLocation: MultiLocation = api.createType(
-          'MultiLocation',
-          {
-            parents: 1,
-            interior: {X1: {Parachain: UNIQUE_CHAIN}},
-          },
-        );
+      // >>> Sponsoring Dorothy >>>
+      console.log('Sponsoring Dorothy.......');
+      await helper.balance.transferToEthereum(alithAccount, dorothyAccount.address, 11_000_000_000_000_000_000n);
+      console.log('Sponsoring Dorothy.......DONE');
+      // <<< Sponsoring Dorothy <<<
 
-        uniqueAssetLocation = {XCM: sourceLocation};
-        const existentialDeposit = 1;
-        const isSufficient = true;
-        const unitsPerSecond = '1';
-        const numAssetsWeightHint = 0;
+      uniqueAssetLocation = {
+        XCM: {
+          parents: 1,
+          interior: {X1: {Parachain: UNIQUE_CHAIN}},
+        },
+      };
+      const existentialDeposit = 1n;
+      const isSufficient = true;
+      const unitsPerSecond = 1n;
+      const numAssetsWeightHint = 0;
 
-        const registerTx = api.tx.assetManager.registerForeignAsset(
-          uniqueAssetLocation,
-          uniqueAssetMetadata,
-          existentialDeposit,
-          isSufficient,
-        );
-        console.log('Encoded proposal for registerAsset is %s', registerTx.method.toHex() || '');
-
-        const setUnitsTx = api.tx.assetManager.setAssetUnitsPerSecond(
-          uniqueAssetLocation,
-          unitsPerSecond,
-          numAssetsWeightHint,
-        );
-        console.log('Encoded proposal for setAssetUnitsPerSecond is %s', setUnitsTx.method.toHex() || '');
-
-        const batchCall = api.tx.utility.batchAll([registerTx, setUnitsTx]);
-        console.log('Encoded proposal for batchCall is %s', batchCall.method.toHex() || '');
-
-        // >>> Note motion preimage >>>
-        console.log('Note motion preimage.......');
-        const encodedProposal = batchCall?.method.toHex() || '';
-        const proposalHash = blake2AsHex(encodedProposal);
-        console.log('Encoded proposal for batch utility after schedule is %s', encodedProposal);
-        console.log('Encoded proposal hash for batch utility after schedule is %s', proposalHash);
-        console.log('Encoded length %d', encodedProposal.length);
+      const encodedProposal = helper.assetManager.makeRegisterForeignAssetProposal({
+        location: uniqueAssetLocation,
+        metadata: uniqueAssetMetadata,
+        existentialDeposit,
+        isSufficient,
+        unitsPerSecond,
+        numAssetsWeightHint,
+      });
+      const proposalHash = blake2AsHex(encodedProposal);
 
-        const tx1 = api.tx.democracy.notePreimage(encodedProposal);
-        const events1 = await submitTransactionAsync(baltatharAccount, tx1);
-        const result1 = getGenericResult(events1);
-        expect(result1.success).to.be.true;
-        console.log('Note motion preimage.......DONE');
-        // <<< Note motion preimage <<<
+      console.log('Encoded proposal for registerForeignAsset & setAssetUnitsPerSecond is %s', encodedProposal);
+      console.log('Encoded length %d', encodedProposal.length);
+      console.log('Encoded proposal hash for batch utility after schedule is %s', proposalHash);
 
-        // >>> Propose external motion through council >>>
-        console.log('Propose external motion through council.......');
-        const externalMotion = api.tx.democracy.externalProposeMajority(proposalHash);
-        const tx2 = api.tx.councilCollective.propose(
-          councilVotingThreshold,
-          externalMotion,
-          externalMotion.encodedLength,
-        );
-        const events2 = await submitTransactionAsync(baltatharAccount, tx2);
-        const result2 = getGenericResult(events2);
-        expect(result2.success).to.be.true;
+      // >>> Note motion preimage >>>
+      console.log('Note motion preimage.......');
+      await helper.democracy.notePreimage(baltatharAccount, encodedProposal);
+      console.log('Note motion preimage.......DONE');
+      // <<< Note motion preimage <<<
 
-        const encodedMotion = externalMotion?.method.toHex() || '';
-        const motionHash = blake2AsHex(encodedMotion);
-        console.log('Motion hash is %s', motionHash);
+      // >>> Propose external motion through council >>>
+      console.log('Propose external motion through council.......');
+      const externalMotion = helper.democracy.externalProposeMajority(proposalHash);
+      const encodedMotion = externalMotion?.method.toHex() || '';
+      const motionHash = blake2AsHex(encodedMotion);
+      console.log('Motion hash is %s', motionHash);
 
-        const tx3 = api.tx.councilCollective.vote(motionHash, 0, true);
-        {
-          const events3 = await submitTransactionAsync(dorothyAccount, tx3);
-          const result3 = getGenericResult(events3);
-          expect(result3.success).to.be.true;
-        }
-        {
-          const events3 = await submitTransactionAsync(baltatharAccount, tx3);
-          const result3 = getGenericResult(events3);
-          expect(result3.success).to.be.true;
-        }
+      await helper.collective.council.propose(baltatharAccount, councilVotingThreshold, externalMotion, externalMotion.encodedLength);
 
-        const tx4 = api.tx.councilCollective.close(motionHash, 0, 1_000_000_000, externalMotion.encodedLength);
-        const events4 = await submitTransactionAsync(dorothyAccount, tx4);
-        const result4 = getGenericResult(events4);
-        expect(result4.success).to.be.true;
-        console.log('Propose external motion through council.......DONE');
-        // <<< Propose external motion through council <<<
+      const councilProposalIdx = await helper.collective.council.proposalCount() - 1;
+      await helper.collective.council.vote(dorothyAccount, motionHash, councilProposalIdx, true);
+      await helper.collective.council.vote(baltatharAccount, motionHash, councilProposalIdx, true);
 
-        // >>> Fast track proposal through technical committee >>>
-        console.log('Fast track proposal through technical committee.......');
-        const fastTrack = api.tx.democracy.fastTrack(proposalHash, votingPeriod, delayPeriod);
-        const tx5 = api.tx.techCommitteeCollective.propose(
-          technicalCommitteeThreshold,
-          fastTrack,
-          fastTrack.encodedLength,
-        );
-        const events5 = await submitTransactionAsync(alithAccount, tx5);
-        const result5 = getGenericResult(events5);
-        expect(result5.success).to.be.true;
+      await helper.collective.council.close(dorothyAccount, motionHash, councilProposalIdx, 1_000_000_000, externalMotion.encodedLength);
+      console.log('Propose external motion through council.......DONE');
+      // <<< Propose external motion through council <<<
 
-        const encodedFastTrack = fastTrack?.method.toHex() || '';
-        const fastTrackHash = blake2AsHex(encodedFastTrack);
-        console.log('FastTrack hash is %s', fastTrackHash);
+      // >>> Fast track proposal through technical committee >>>
+      console.log('Fast track proposal through technical committee.......');
+      const fastTrack = helper.democracy.fastTrack(proposalHash, votingPeriod, delayPeriod);
+      const encodedFastTrack = fastTrack?.method.toHex() || '';
+      const fastTrackHash = blake2AsHex(encodedFastTrack);
+      console.log('FastTrack hash is %s', fastTrackHash);
 
-        const proposalIdx = Number(await api.query.techCommitteeCollective.proposalCount()) - 1;
-        const tx6 = api.tx.techCommitteeCollective.vote(fastTrackHash, proposalIdx, true);
-        {
-          const events6 = await submitTransactionAsync(baltatharAccount, tx6);
-          const result6 = getGenericResult(events6);
-          expect(result6.success).to.be.true;
-        }
-        {
-          const events6 = await submitTransactionAsync(alithAccount, tx6);
-          const result6 = getGenericResult(events6);
-          expect(result6.success).to.be.true;
-        }
+      await helper.collective.techCommittee.propose(alithAccount, technicalCommitteeThreshold, fastTrack, fastTrack.encodedLength);
 
-        const tx7 = api.tx.techCommitteeCollective
-          .close(fastTrackHash, proposalIdx, 1_000_000_000, fastTrack.encodedLength);
-        const events7 = await submitTransactionAsync(baltatharAccount, tx7);
-        const result7 = getGenericResult(events7);
-        expect(result7.success).to.be.true;
-        console.log('Fast track proposal through technical committee.......DONE');
-        // <<< Fast track proposal through technical committee <<<
+      const techProposalIdx = await helper.collective.techCommittee.proposalCount() - 1;
+      await helper.collective.techCommittee.vote(baltatharAccount, fastTrackHash, techProposalIdx, true);
+      await helper.collective.techCommittee.vote(alithAccount, fastTrackHash, techProposalIdx, true);
 
-        // >>> Referendum voting >>>
-        console.log('Referendum voting.......');
-        const tx8 = api.tx.democracy.vote(
-          0,
-          {Standard: {balance: 10_000_000_000_000_000_000n, vote: {aye: true, conviction: 1}}},
-        );
-        const events8 = await submitTransactionAsync(dorothyAccount, tx8);
-        const result8 = getGenericResult(events8);
-        expect(result8.success).to.be.true;
-        console.log('Referendum voting.......DONE');
-        // <<< Referendum voting <<<
+      await helper.collective.techCommittee.close(baltatharAccount, fastTrackHash, techProposalIdx, 1_000_000_000, fastTrack.encodedLength);
+      console.log('Fast track proposal through technical committee.......DONE');
+      // <<< Fast track proposal through technical committee <<<
 
-        // >>> Acquire Unique AssetId Info on Moonbeam >>>
-        console.log('Acquire Unique AssetId Info on Moonbeam.......');
+      // >>> Referendum voting >>>
+      console.log('Referendum voting.......');
+      await helper.democracy.referendumVote(dorothyAccount, 0, {
+        balance: 10_000_000_000_000_000_000n,
+        vote: {aye: true, conviction: 1},
+      });
+      console.log('Referendum voting.......DONE');
+      // <<< Referendum voting <<<
 
-        // Wait for the democracy execute
-        await waitNewBlocks(api, 5);
+      // >>> Acquire Unique AssetId Info on Moonbeam >>>
+      console.log('Acquire Unique AssetId Info on Moonbeam.......');
 
-        assetId = (await api.query.assetManager.assetTypeId({
-          XCM: sourceLocation,
-        })).toString();
+      // Wait for the democracy execute
+      await helper.wait.newBlocks(5);
 
-        console.log('UNQ asset ID is %s', assetId);
-        console.log('Acquire Unique AssetId Info on Moonbeam.......DONE');
-        // >>> Acquire Unique AssetId Info on Moonbeam >>>
+      assetId = (await helper.assetManager.assetTypeId(uniqueAssetLocation)).toString();
 
-        // >>> Sponsoring random Account >>>
-        console.log('Sponsoring random Account.......');
-        const tx10 = api.tx.balances.transfer(randomAccountMoonbeam.address, 11_000_000_000_000_000_000n);
-        const events10 = await submitTransactionAsync(baltatharAccount, tx10);
-        const result10 = getGenericResult(events10);
-        expect(result10.success).to.be.true;
-        console.log('Sponsoring random Account.......DONE');
-        // <<< Sponsoring random Account <<<
+      console.log('UNQ asset ID is %s', assetId);
+      console.log('Acquire Unique AssetId Info on Moonbeam.......DONE');
+      // >>> Acquire Unique AssetId Info on Moonbeam >>>
 
-        [balanceGlmrTokenInit] = await getBalance(api, [randomAccountMoonbeam.address]);
-      },
-      moonbeamOptions(),
-    );
+      // >>> Sponsoring random Account >>>
+      console.log('Sponsoring random Account.......');
+      await helper.balance.transferToEthereum(baltatharAccount, randomAccountMoonbeam.address, 11_000_000_000_000_000_000n);
+      console.log('Sponsoring random Account.......DONE');
+      // <<< Sponsoring random Account <<<
 
-    await usingApi(async (api) => {
-      const tx0 = api.tx.balances.transfer(randomAccountUnique.address, 10n * TRANSFER_AMOUNT);
-      const events0 = await submitTransactionAsync(uniqueAlice, tx0);
-      const result0 = getGenericResult(events0);
-      expect(result0.success).to.be.true;
+      balanceGlmrTokenInit = await helper.balance.getEthereum(randomAccountMoonbeam.address);
+    });
 
-      [balanceUniqueTokenInit] = await getBalance(api, [randomAccountUnique.address]);
+    await usingPlaygrounds(async (helper) => {
+      await helper.balance.transferToSubstrate(uniqueDonor, randomAccountUnique.address, 10n * TRANSFER_AMOUNT);
+      balanceUniqueTokenInit = await helper.balance.getSubstrate(randomAccountUnique.address);
     });
   });
 
-  it('Should connect and send UNQ to Moonbeam', async () => {
-    await usingApi(async (api) => {
-      const currencyId = {
-        NativeAssetId: 'Here',
-      };
-      const dest = {
-        V1: {
-          parents: 1,
-          interior: {
-            X2: [
-              {Parachain: MOONBEAM_CHAIN},
-              {AccountKey20: {network: 'Any', key: randomAccountMoonbeam.address}},
-            ],
-          },
+  itSub('Should connect and send UNQ to Moonbeam', async ({helper}) => {
+    const currencyId = {
+      NativeAssetId: 'Here',
+    };
+    const dest = {
+      V1: {
+        parents: 1,
+        interior: {
+          X2: [
+            {Parachain: MOONBEAM_CHAIN},
+            {AccountKey20: {network: 'Any', key: randomAccountMoonbeam.address}},
+          ],
         },
-      };
-      const amount = TRANSFER_AMOUNT;
-      const destWeight = 850000000;
+      },
+    };
+    const amount = TRANSFER_AMOUNT;
+    const destWeight = 850000000;
 
-      const tx = api.tx.xTokens.transfer(currencyId, amount, dest, destWeight);
-      const events = await submitTransactionAsync(randomAccountUnique, tx);
-      const result = getGenericResult(events);
-      expect(result.success).to.be.true;
+    await helper.xTokens.transfer(randomAccountUnique, currencyId, amount, dest, destWeight);
 
-      [balanceUniqueTokenMiddle] = await getBalance(api, [randomAccountUnique.address]);
-      expect(balanceUniqueTokenMiddle < balanceUniqueTokenInit).to.be.true;
+    balanceUniqueTokenMiddle = await helper.balance.getSubstrate(randomAccountUnique.address);
+    expect(balanceUniqueTokenMiddle < balanceUniqueTokenInit).to.be.true;
 
-      const transactionFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;
-      console.log('[Unique -> Moonbeam] transaction fees on Unique: %s UNQ', bigIntToDecimals(transactionFees));
-      expect(transactionFees > 0).to.be.true;
-    });
+    const transactionFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;
+    console.log('[Unique -> Moonbeam] transaction fees on Unique: %s UNQ', helper.util.bigIntToDecimals(transactionFees));
+    expect(transactionFees > 0).to.be.true;
 
-    await usingApi(
-      async (api) => {
-        await waitNewBlocks(api, 3);
+    await usingMoonbeamPlaygrounds(moonbeamUrl, async (helper) => {
+      await helper.wait.newBlocks(3);
 
-        [balanceGlmrTokenMiddle] = await getBalance(api, [randomAccountMoonbeam.address]);
+      balanceGlmrTokenMiddle = await helper.balance.getEthereum(randomAccountMoonbeam.address);
 
-        const glmrFees = balanceGlmrTokenInit - balanceGlmrTokenMiddle;
-        console.log('[Unique -> Moonbeam] transaction fees on Moonbeam: %s GLMR', bigIntToDecimals(glmrFees));
-        expect(glmrFees == 0n).to.be.true;
+      const glmrFees = balanceGlmrTokenInit - balanceGlmrTokenMiddle;
+      console.log('[Unique -> Moonbeam] transaction fees on Moonbeam: %s GLMR', helper.util.bigIntToDecimals(glmrFees));
+      expect(glmrFees == 0n).to.be.true;
 
-        const unqRandomAccountAsset = (
-          await api.query.assets.account(assetId, randomAccountMoonbeam.address)
-        ).toJSON()! as any;
+      balanceForeignUnqTokenMiddle = (await helper.assets.account(assetId, randomAccountMoonbeam.address))!;
 
-        balanceForeignUnqTokenMiddle = BigInt(unqRandomAccountAsset['balance']);
-        const unqIncomeTransfer = balanceForeignUnqTokenMiddle - balanceForeignUnqTokenInit;
-        console.log('[Unique -> Moonbeam] income %s UNQ', bigIntToDecimals(unqIncomeTransfer));
-        expect(unqIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
-      },
-      moonbeamOptions(),
-    );
+      const unqIncomeTransfer = balanceForeignUnqTokenMiddle - balanceForeignUnqTokenInit;
+      console.log('[Unique -> Moonbeam] income %s UNQ', helper.util.bigIntToDecimals(unqIncomeTransfer));
+      expect(unqIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
+    });
   });
 
-  it('Should connect to Moonbeam and send UNQ back', async () => {
-    await usingApi(
-      async (api) => {
-        const asset = {
-          V1: {
-            id: {
-              Concrete: {
-                parents: 1,
-                interior: {
-                  X1: {Parachain: UNIQUE_CHAIN},
-                },
+  itSub('Should connect to Moonbeam and send UNQ back', async ({helper}) => {
+    await usingMoonbeamPlaygrounds(moonbeamUrl, async (helper) => {
+      const asset = {
+        V1: {
+          id: {
+            Concrete: {
+              parents: 1,
+              interior: {
+                X1: {Parachain: UNIQUE_CHAIN},
               },
             },
-            fun: {
-              Fungible: TRANSFER_AMOUNT,
-            },
           },
-        };
-        const destination = {
-          V1: {
-            parents: 1,
-            interior: {
-              X2: [
-                {Parachain: UNIQUE_CHAIN},
-                {AccountId32: {network: 'Any', id: randomAccountUnique.addressRaw}},
-              ],
-            },
+          fun: {
+            Fungible: TRANSFER_AMOUNT,
           },
-        };
-        const destWeight = 50000000;
-
-        const tx = api.tx.xTokens.transferMultiasset(asset, destination, destWeight);
-        const events = await submitTransactionAsync(randomAccountMoonbeam, tx);
-        const result = getGenericResult(events);
-        expect(result.success).to.be.true;
+        },
+      };
+      const destination = {
+        V1: {
+          parents: 1,
+          interior: {
+            X2: [
+              {Parachain: UNIQUE_CHAIN},
+              {AccountId32: {network: 'Any', id: randomAccountUnique.addressRaw}},
+            ],
+          },
+        },
+      };
+      const destWeight = 50000000;
 
-        [balanceGlmrTokenFinal] = await getBalance(api, [randomAccountMoonbeam.address]);
+      await helper.xTokens.transferMultiasset(randomAccountMoonbeam, asset, destination, destWeight);
 
-        const glmrFees = balanceGlmrTokenMiddle - balanceGlmrTokenFinal;
-        console.log('[Moonbeam -> Unique] transaction fees on Moonbeam: %s GLMR', bigIntToDecimals(glmrFees));
-        expect(glmrFees > 0).to.be.true;
+      balanceGlmrTokenFinal = await helper.balance.getEthereum(randomAccountMoonbeam.address);
 
-        const unqRandomAccountAsset = (
-          await api.query.assets.account(assetId, randomAccountMoonbeam.address)
-        ).toJSON()! as any;
+      const glmrFees = balanceGlmrTokenMiddle - balanceGlmrTokenFinal;
+      console.log('[Moonbeam -> Unique] transaction fees on Moonbeam: %s GLMR', helper.util.bigIntToDecimals(glmrFees));
+      expect(glmrFees > 0).to.be.true;
 
-        expect(unqRandomAccountAsset).to.be.null;
+      const unqRandomAccountAsset = await helper.assets.account(assetId, randomAccountMoonbeam.address);
 
-        balanceForeignUnqTokenFinal = 0n;
+      expect(unqRandomAccountAsset).to.be.null;
+      
+      balanceForeignUnqTokenFinal = 0n;
 
-        const unqOutcomeTransfer = balanceForeignUnqTokenMiddle - balanceForeignUnqTokenFinal;
-        console.log('[Unique -> Moonbeam] outcome %s UNQ', bigIntToDecimals(unqOutcomeTransfer));
-        expect(unqOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
-      },
-      moonbeamOptions(),
-    );
+      const unqOutcomeTransfer = balanceForeignUnqTokenMiddle - balanceForeignUnqTokenFinal;
+      console.log('[Unique -> Moonbeam] outcome %s UNQ', helper.util.bigIntToDecimals(unqOutcomeTransfer));
+      expect(unqOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
+    });
 
-    await usingApi(async (api) => {
-      await waitNewBlocks(api, 3);
+    await helper.wait.newBlocks(3);
 
-      [balanceUniqueTokenFinal] = await getBalance(api, [randomAccountUnique.address]);
-      const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenMiddle;
-      expect(actuallyDelivered > 0).to.be.true;
+    balanceUniqueTokenFinal = await helper.balance.getSubstrate(randomAccountUnique.address);
+    const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenMiddle;
+    expect(actuallyDelivered > 0).to.be.true;
 
-      console.log('[Moonbeam -> Unique] actually delivered %s UNQ', bigIntToDecimals(actuallyDelivered));
+    console.log('[Moonbeam -> Unique] actually delivered %s UNQ', helper.util.bigIntToDecimals(actuallyDelivered));
 
-      const unqFees = TRANSFER_AMOUNT - actuallyDelivered;
-      console.log('[Moonbeam -> Unique] transaction fees on Unique: %s UNQ', bigIntToDecimals(unqFees));
-      expect(unqFees == 0n).to.be.true;
-    });
+    const unqFees = TRANSFER_AMOUNT - actuallyDelivered;
+    console.log('[Moonbeam -> Unique] transaction fees on Unique: %s UNQ', helper.util.bigIntToDecimals(unqFees));
+    expect(unqFees == 0n).to.be.true;
   });
 });