difftreelog
Merge branch 'develop' into tests/feed-alices
in: master
47 files changed
.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"
.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}
+
+
.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}
+
+
.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}
+
+
.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"
.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"
.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"
.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
+}
+
.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
+}
+
.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"
]
.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
.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()
tests/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;
tests/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];
-}
tests/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
tests/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
tests/src/deprecated-helpers/helpers.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event, BlockNumber} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import {AnyNumber} from '@polkadot/types-codec/types';25import BN from 'bn.js';26import chai from 'chai';27import chaiAsPromised from 'chai-as-promised';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';32import {Context} from 'mocha';3334chai.use(chaiAsPromised);35const expect = chai.expect;3637export type CrossAccountId = {38 Substrate: string,39} | {40 Ethereum: string,41};424344export enum Pallets {45 Inflation = 'inflation',46 RmrkCore = 'rmrkcore',47 RmrkEquip = 'rmrkequip',48 ReFungible = 'refungible',49 Fungible = 'fungible',50 NFT = 'nonfungible',51 Scheduler = 'scheduler',52 AppPromotion = 'apppromotion',53}5455export async function isUnique(): Promise<boolean> {56 return usingApi(async api => {57 const chain = await api.rpc.system.chain();5859 return chain.eq('UNIQUE');60 });61}6263export async function isQuartz(): Promise<boolean> {64 return usingApi(async api => {65 const chain = await api.rpc.system.chain();6667 return chain.eq('QUARTZ');68 });69}7071let modulesNames: any;72export function getModuleNames(api: ApiPromise): string[] {73 if (typeof modulesNames === 'undefined')74 modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());75 return modulesNames;76}7778export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {79 return await usingApi(async api => {80 const pallets = getModuleNames(api);8182 return requiredPallets.filter(p => !pallets.includes(p));83 });84}8586export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {87 return (await missingRequiredPallets(requiredPallets)).length == 0;88}8990export async function requirePallets(mocha: Context, requiredPallets: string[]) {91 const missingPallets = await missingRequiredPallets(requiredPallets);9293 if (missingPallets.length > 0) {94 const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;95 const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;96 const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9798 console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);99100 mocha.skip();101 }102}103104export function bigIntToSub(api: ApiPromise, number: bigint) {105 return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();106}107108export function bigIntToDecimals(number: bigint, decimals = 18): string {109 const numberStr = number.toString();110 const dotPos = numberStr.length - decimals;111112 if (dotPos <= 0) {113 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;114 } else {115 const intPart = numberStr.substring(0, dotPos);116 const fractPart = numberStr.substring(dotPos);117 return intPart + '.' + fractPart;118 }119}120121export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {122 if (typeof input === 'string') {123 if (input.length >= 47) {124 return {Substrate: input};125 } else if (input.length === 42 && input.startsWith('0x')) {126 return {Ethereum: input.toLowerCase()};127 } else if (input.length === 40 && !input.startsWith('0x')) {128 return {Ethereum: '0x' + input.toLowerCase()};129 } else {130 throw new Error(`Unknown address format: "${input}"`);131 }132 }133 if ('address' in input) {134 return {Substrate: input.address};135 }136 if ('Ethereum' in input) {137 return {138 Ethereum: input.Ethereum.toLowerCase(),139 };140 } else if ('ethereum' in input) {141 return {142 Ethereum: (input as any).ethereum.toLowerCase(),143 };144 } else if ('Substrate' in input) {145 return input;146 } else if ('substrate' in input) {147 return {148 Substrate: (input as any).substrate,149 };150 }151152 // AccountId153 return {Substrate: input.toString()};154}155export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {156 input = normalizeAccountId(input);157 if ('Substrate' in input) {158 return input.Substrate;159 } else {160 return evmToAddress(input.Ethereum);161 }162}163164export const U128_MAX = (1n << 128n) - 1n;165166const MICROUNIQUE = 1_000_000_000_000n;167const MILLIUNIQUE = 1_000n * MICROUNIQUE;168const CENTIUNIQUE = 10n * MILLIUNIQUE;169export const UNIQUE = 100n * CENTIUNIQUE;170171interface GenericResult<T> {172 success: boolean;173 data: T | null;174}175176interface CreateCollectionResult {177 success: boolean;178 collectionId: number;179}180181interface CreateItemResult {182 success: boolean;183 collectionId: number;184 itemId: number;185 recipient?: CrossAccountId;186 amount?: number;187}188189interface DestroyItemResult {190 success: boolean;191 collectionId: number;192 itemId: number;193 owner: CrossAccountId;194 amount: number;195}196197interface TransferResult {198 collectionId: number;199 itemId: number;200 sender?: CrossAccountId;201 recipient?: CrossAccountId;202 value: bigint;203}204205interface IReFungibleOwner {206 fraction: BN;207 owner: number[];208}209210interface IGetMessage {211 checkMsgUnqMethod: string;212 checkMsgTrsMethod: string;213 checkMsgSysMethod: string;214}215216export interface IFungibleTokenDataType {217 value: number;218}219220export interface IChainLimits {221 collectionNumbersLimit: number;222 accountTokenOwnershipLimit: number;223 collectionsAdminsLimit: number;224 customDataLimit: number;225 nftSponsorTransferTimeout: number;226 fungibleSponsorTransferTimeout: number;227 refungibleSponsorTransferTimeout: number;228 //offchainSchemaLimit: number;229 //constOnChainSchemaLimit: number;230}231232export interface IReFungibleTokenDataType {233 owner: IReFungibleOwner[];234}235236export function uniqueEventMessage(events: EventRecord[]): IGetMessage {237 let checkMsgUnqMethod = '';238 let checkMsgTrsMethod = '';239 let checkMsgSysMethod = '';240 events.forEach(({event: {method, section}}) => {241 if (section === 'common') {242 checkMsgUnqMethod = method;243 } else if (section === 'treasury') {244 checkMsgTrsMethod = method;245 } else if (section === 'system') {246 checkMsgSysMethod = method;247 } else { return null; }248 });249 const result: IGetMessage = {250 checkMsgUnqMethod,251 checkMsgTrsMethod,252 checkMsgSysMethod,253 };254 return result;255}256257export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {258 const event = events.find(r => check(r.event));259 if (!event) return;260 return event.event as T;261}262263export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;264export function getGenericResult<T>(265 events: EventRecord[],266 expectSection: string,267 expectMethod: string,268 extractAction: (data: GenericEventData) => T269): GenericResult<T>;270271export function getGenericResult<T>(272 events: EventRecord[],273 expectSection?: string,274 expectMethod?: string,275 extractAction?: (data: GenericEventData) => T,276): GenericResult<T> {277 let success = false;278 let successData = null;279280 events.forEach(({event: {data, method, section}}) => {281 // console.log(` ${phase}: ${section}.${method}:: ${data}`);282 if (method === 'ExtrinsicSuccess') {283 success = true;284 } else if ((expectSection == section) && (expectMethod == method)) {285 successData = extractAction!(data as any);286 }287 });288289 const result: GenericResult<T> = {290 success,291 data: successData,292 };293 return result;294}295296export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {297 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));298 const result: CreateCollectionResult = {299 success: genericResult.success,300 collectionId: genericResult.data ?? 0,301 };302 return result;303}304305export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {306 const results: CreateItemResult[] = [];307308 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {309 const collectionId = parseInt(data[0].toString(), 10);310 const itemId = parseInt(data[1].toString(), 10);311 const recipient = normalizeAccountId(data[2].toJSON() as any);312 const amount = parseInt(data[3].toString(), 10);313314 const itemRes: CreateItemResult = {315 success: true,316 collectionId,317 itemId,318 recipient,319 amount,320 };321322 results.push(itemRes);323 return results;324 });325326 if (!genericResult.success) return [];327 return results;328}329330export function getCreateItemResult(events: EventRecord[]): CreateItemResult {331 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));332333 if (genericResult.data == null)334 return {335 success: genericResult.success,336 collectionId: 0,337 itemId: 0,338 amount: 0,339 };340 else341 return {342 success: genericResult.success,343 collectionId: genericResult.data[0] as number,344 itemId: genericResult.data[1] as number,345 recipient: normalizeAccountId(genericResult.data![2] as any),346 amount: genericResult.data[3] as number,347 };348}349350export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {351 const results: DestroyItemResult[] = [];352353 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {354 const collectionId = parseInt(data[0].toString(), 10);355 const itemId = parseInt(data[1].toString(), 10);356 const owner = normalizeAccountId(data[2].toJSON() as any);357 const amount = parseInt(data[3].toString(), 10);358359 const itemRes: DestroyItemResult = {360 success: true,361 collectionId,362 itemId,363 owner,364 amount,365 };366367 results.push(itemRes);368 return results;369 });370371 if (!genericResult.success) return [];372 return results;373}374375export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {376 for (const {event} of events) {377 if (api.events.common.Transfer.is(event)) {378 const [collection, token, sender, recipient, value] = event.data;379 return {380 collectionId: collection.toNumber(),381 itemId: token.toNumber(),382 sender: normalizeAccountId(sender.toJSON() as any),383 recipient: normalizeAccountId(recipient.toJSON() as any),384 value: value.toBigInt(),385 };386 }387 }388 throw new Error('no transfer event');389}390391interface Nft {392 type: 'NFT';393}394395interface Fungible {396 type: 'Fungible';397 decimalPoints: number;398}399400interface ReFungible {401 type: 'ReFungible';402}403404export type CollectionMode = Nft | Fungible | ReFungible;405406export type Property = {407 key: any,408 value: any,409};410411type Permission = {412 mutable: boolean;413 collectionAdmin: boolean;414 tokenOwner: boolean;415}416417type PropertyPermission = {418 key: any;419 permission: Permission;420}421422export type CreateCollectionParams = {423 mode: CollectionMode,424 name: string,425 description: string,426 tokenPrefix: string,427 properties?: Array<Property>,428 propPerm?: Array<PropertyPermission>429};430431const defaultCreateCollectionParams: CreateCollectionParams = {432 description: 'description',433 mode: {type: 'NFT'},434 name: 'name',435 tokenPrefix: 'prefix',436};437438export async function439createCollection(440 api: ApiPromise,441 sender: IKeyringPair,442 params: Partial<CreateCollectionParams> = {},443): Promise<CreateCollectionResult> {444 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};445446 let modeprm = {};447 if (mode.type === 'NFT') {448 modeprm = {nft: null};449 } else if (mode.type === 'Fungible') {450 modeprm = {fungible: mode.decimalPoints};451 } else if (mode.type === 'ReFungible') {452 modeprm = {refungible: null};453 }454455 const tx = api.tx.unique.createCollectionEx({456 name: strToUTF16(name),457 description: strToUTF16(description),458 tokenPrefix: strToUTF16(tokenPrefix),459 mode: modeprm as any,460 });461 const events = await executeTransaction(api, sender, tx);462 return getCreateCollectionResult(events);463}464465export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {466 const {name, description, tokenPrefix} = {...defaultCreateCollectionParams, ...params};467468 let collectionId = 0;469 await usingApi(async (api, privateKeyWrapper) => {470 // Get number of collections before the transaction471 const collectionCountBefore = await getCreatedCollectionCount(api);472473 // Run the CreateCollection transaction474 const alicePrivateKey = privateKeyWrapper('//Alice');475476 const result = await createCollection(api, alicePrivateKey, params);477478 // Get number of collections after the transaction479 const collectionCountAfter = await getCreatedCollectionCount(api);480481 // Get the collection482 const collection = await queryCollectionExpectSuccess(api, result.collectionId);483484 // What to expect485 // tslint:disable-next-line:no-unused-expression486 expect(result.success).to.be.true;487 expect(result.collectionId).to.be.equal(collectionCountAfter);488 // tslint:disable-next-line:no-unused-expression489 expect(collection).to.be.not.null;490 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');491 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));492 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);493 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);494 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);495496 collectionId = result.collectionId;497 });498499 return collectionId;500}501502export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {503 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};504505 let collectionId = 0;506 await usingApi(async (api, privateKeyWrapper) => {507 // Get number of collections before the transaction508 const collectionCountBefore = await getCreatedCollectionCount(api);509510 // Run the CreateCollection transaction511 const alicePrivateKey = privateKeyWrapper('//Alice');512513 let modeprm = {};514 if (mode.type === 'NFT') {515 modeprm = {nft: null};516 } else if (mode.type === 'Fungible') {517 modeprm = {fungible: mode.decimalPoints};518 } else if (mode.type === 'ReFungible') {519 modeprm = {refungible: null};520 }521522 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});523 const events = await submitTransactionAsync(alicePrivateKey, tx);524 const result = getCreateCollectionResult(events);525526 // Get number of collections after the transaction527 const collectionCountAfter = await getCreatedCollectionCount(api);528529 // Get the collection530 const collection = await queryCollectionExpectSuccess(api, result.collectionId);531532 // What to expect533 // tslint:disable-next-line:no-unused-expression534 expect(result.success).to.be.true;535 expect(result.collectionId).to.be.equal(collectionCountAfter);536 // tslint:disable-next-line:no-unused-expression537 expect(collection).to.be.not.null;538 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');539 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));540 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);541 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);542 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);543544545 collectionId = result.collectionId;546 });547548 return collectionId;549}550551export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {552 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};553554 await usingApi(async (api, privateKeyWrapper) => {555 // Get number of collections before the transaction556 const collectionCountBefore = await getCreatedCollectionCount(api);557558 // Run the CreateCollection transaction559 const alicePrivateKey = privateKeyWrapper('//Alice');560561 let modeprm = {};562 if (mode.type === 'NFT') {563 modeprm = {nft: null};564 } else if (mode.type === 'Fungible') {565 modeprm = {fungible: mode.decimalPoints};566 } else if (mode.type === 'ReFungible') {567 modeprm = {refungible: null};568 }569570 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});571 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;572573574 // Get number of collections after the transaction575 const collectionCountAfter = await getCreatedCollectionCount(api);576577 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');578 });579}580581export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {582 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};583584 let modeprm = {};585 if (mode.type === 'NFT') {586 modeprm = {nft: null};587 } else if (mode.type === 'Fungible') {588 modeprm = {fungible: mode.decimalPoints};589 } else if (mode.type === 'ReFungible') {590 modeprm = {refungible: null};591 }592593 await usingApi(async (api, privateKeyWrapper) => {594 // Get number of collections before the transaction595 const collectionCountBefore = await getCreatedCollectionCount(api);596597 // Run the CreateCollection transaction598 const alicePrivateKey = privateKeyWrapper('//Alice');599 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});600 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;601602 // Get number of collections after the transaction603 const collectionCountAfter = await getCreatedCollectionCount(api);604605 // What to expect606 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');607 });608}609610export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {611 let bal = 0n;612 let unused;613 do {614 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;615 unused = privateKeyWrapper(`//${randomSeed}`);616 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();617 } while (bal !== 0n);618 return unused;619}620621export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {622 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();623}624625export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {626 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));627}628629export async function findNotExistingCollection(api: ApiPromise): Promise<number> {630 const totalNumber = await getCreatedCollectionCount(api);631 const newCollection: number = totalNumber + 1;632 return newCollection;633}634635function getDestroyResult(events: EventRecord[]): boolean {636 let success = false;637 events.forEach(({event: {method}}) => {638 if (method == 'ExtrinsicSuccess') {639 success = true;640 }641 });642 return success;643}644645export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {646 await usingApi(async (api, privateKeyWrapper) => {647 // Run the DestroyCollection transaction648 const alicePrivateKey = privateKeyWrapper(senderSeed);649 const tx = api.tx.unique.destroyCollection(collectionId);650 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;651 });652}653654export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {655 await usingApi(async (api, privateKeyWrapper) => {656 // Run the DestroyCollection transaction657 const alicePrivateKey = privateKeyWrapper(senderSeed);658 const tx = api.tx.unique.destroyCollection(collectionId);659 const events = await submitTransactionAsync(alicePrivateKey, tx);660 const result = getDestroyResult(events);661 expect(result).to.be.true;662663 // What to expect664 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;665 });666}667668export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {669 await usingApi(async (api) => {670 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);671 const events = await submitTransactionAsync(sender, tx);672 const result = getGenericResult(events);673674 expect(result.success).to.be.true;675 });676}677678export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {679 await usingApi(async(api) => {680 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);681 const events = await submitTransactionAsync(sender, tx);682 const result = getGenericResult(events);683684 expect(result.success).to.be.true;685 });686};687688export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {689 await usingApi(async (api) => {690 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);691 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;692 const result = getGenericResult(events);693694 expect(result.success).to.be.false;695 });696}697698export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {699 await usingApi(async (api, privateKeyWrapper) => {700701 // Run the transaction702 const senderPrivateKey = privateKeyWrapper(sender);703 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);704 const events = await submitTransactionAsync(senderPrivateKey, tx);705 const result = getGenericResult(events);706707 // Get the collection708 const collection = await queryCollectionExpectSuccess(api, collectionId);709710 // What to expect711 expect(result.success).to.be.true;712 expect(collection.sponsorship.toJSON()).to.deep.equal({713 unconfirmed: sponsor,714 });715 });716}717718export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {719 await usingApi(async (api, privateKeyWrapper) => {720721 // Run the transaction722 const alicePrivateKey = privateKeyWrapper(sender);723 const tx = api.tx.unique.removeCollectionSponsor(collectionId);724 const events = await submitTransactionAsync(alicePrivateKey, tx);725 const result = getGenericResult(events);726727 // Get the collection728 const collection = await queryCollectionExpectSuccess(api, collectionId);729730 // What to expect731 expect(result.success).to.be.true;732 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});733 });734}735736export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {737 await usingApi(async (api, privateKeyWrapper) => {738739 // Run the transaction740 const alicePrivateKey = privateKeyWrapper(senderSeed);741 const tx = api.tx.unique.removeCollectionSponsor(collectionId);742 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;743 });744}745746export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {747 await usingApi(async (api, privateKeyWrapper) => {748749 // Run the transaction750 const alicePrivateKey = privateKeyWrapper(senderSeed);751 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);752 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;753 });754}755756export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {757 await usingApi(async (api, privateKeyWrapper) => {758759 // Run the transaction760 const sender = privateKeyWrapper(senderSeed);761 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);762 });763}764765export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {766 await usingApi(async (api) => {767768 // Run the transaction769 const tx = api.tx.unique.confirmSponsorship(collectionId);770 const events = await submitTransactionAsync(sender, tx);771 const result = getGenericResult(events);772773 // Get the collection774 const collection = await queryCollectionExpectSuccess(api, collectionId);775776 // What to expect777 expect(result.success).to.be.true;778 expect(collection.sponsorship.toJSON()).to.be.deep.equal({779 confirmed: sender.address,780 });781 });782}783784785export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {786 await usingApi(async (api, privateKeyWrapper) => {787788 // Run the transaction789 const sender = privateKeyWrapper(senderSeed);790 const tx = api.tx.unique.confirmSponsorship(collectionId);791 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;792 });793}794795export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {796 await usingApi(async (api) => {797 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);798 const events = await submitTransactionAsync(sender, tx);799 const result = getGenericResult(events);800801 expect(result.success).to.be.true;802 });803}804805export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {806 await usingApi(async (api) => {807 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);808 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;809 const result = getGenericResult(events);810811 expect(result.success).to.be.false;812 });813}814815export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {816817 await usingApi(async (api) => {818819 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);820 const events = await submitTransactionAsync(sender, tx);821 const result = getGenericResult(events);822823 expect(result.success).to.be.true;824 });825}826827export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {828829 await usingApi(async (api) => {830831 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);832 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;833 const result = getGenericResult(events);834835 expect(result.success).to.be.false;836 });837}838839export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {840 await usingApi(async (api) => {841 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);842 const events = await submitTransactionAsync(sender, tx);843 const result = getGenericResult(events);844845 expect(result.success).to.be.true;846 });847}848849export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {850 await usingApi(async (api) => {851 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);852 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;853 const result = getGenericResult(events);854855 expect(result.success).to.be.false;856 });857}858859export async function getNextSponsored(860 api: ApiPromise,861 collectionId: number,862 account: string | CrossAccountId,863 tokenId: number,864): Promise<number> {865 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));866}867868export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {869 await usingApi(async (api) => {870 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);871 const events = await submitTransactionAsync(sender, tx);872 const result = getGenericResult(events);873874 expect(result.success).to.be.true;875 });876}877878export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {879 let allowlisted = false;880 await usingApi(async (api) => {881 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;882 });883 return allowlisted;884}885886export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {887 await usingApi(async (api) => {888 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());889 const events = await submitTransactionAsync(sender, tx);890 const result = getGenericResult(events);891892 expect(result.success).to.be.true;893 });894}895896export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {897 await usingApi(async (api) => {898 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());899 const events = await submitTransactionAsync(sender, tx);900 const result = getGenericResult(events);901902 expect(result.success).to.be.true;903 });904}905906export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {907 await usingApi(async (api) => {908 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());909 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;910 const result = getGenericResult(events);911912 expect(result.success).to.be.false;913 });914}915916export interface CreateFungibleData {917 readonly Value: bigint;918}919920export interface CreateReFungibleData { }921export interface CreateNftData { }922923export type CreateItemData = {924 NFT: CreateNftData;925} | {926 Fungible: CreateFungibleData;927} | {928 ReFungible: CreateReFungibleData;929};930931export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {932 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);933 const events = await submitTransactionAsync(sender, tx);934 return getGenericResult(events).success;935}936937export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {938 await usingApi(async (api) => {939 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);940 // if burning token by admin - use adminButnItemExpectSuccess941 expect(balanceBefore >= BigInt(value)).to.be.true;942943 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;944945 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);946 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);947 });948}949950export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {951 await usingApi(async (api) => {952 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);953954 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;955 const result = getCreateCollectionResult(events);956 // tslint:disable-next-line:no-unused-expression957 expect(result.success).to.be.false;958 });959}960961export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {962 await usingApi(async (api) => {963 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);964 const events = await submitTransactionAsync(sender, tx);965 return getGenericResult(events).success;966 });967}968969export async function970approve(971 api: ApiPromise,972 collectionId: number,973 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,974) {975 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);976 const events = await submitTransactionAsync(owner, approveUniqueTx);977 return getGenericResult(events).success;978}979980export async function981approveExpectSuccess(982 collectionId: number,983 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,984) {985 await usingApi(async (api: ApiPromise) => {986 const result = await approve(api, collectionId, tokenId, owner, approved, amount);987 expect(result).to.be.true;988989 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));990 });991}992993export async function adminApproveFromExpectSuccess(994 collectionId: number,995 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,996) {997 await usingApi(async (api: ApiPromise) => {998 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);999 const events = await submitTransactionAsync(admin, approveUniqueTx);1000 const result = getGenericResult(events);1001 expect(result.success).to.be.true;10021003 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));1004 });1005}10061007export async function1008transferFrom(1009 api: ApiPromise,1010 collectionId: number,1011 tokenId: number,1012 accountApproved: IKeyringPair,1013 accountFrom: IKeyringPair | CrossAccountId,1014 accountTo: IKeyringPair | CrossAccountId,1015 value: number | bigint,1016) {1017 const from = normalizeAccountId(accountFrom);1018 const to = normalizeAccountId(accountTo);1019 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1020 const events = await submitTransactionAsync(accountApproved, transferFromTx);1021 return getGenericResult(events).success;1022}10231024export async function1025transferFromExpectSuccess(1026 collectionId: number,1027 tokenId: number,1028 accountApproved: IKeyringPair,1029 accountFrom: IKeyringPair | CrossAccountId,1030 accountTo: IKeyringPair | CrossAccountId,1031 value: number | bigint = 1,1032 type = 'NFT',1033) {1034 await usingApi(async (api: ApiPromise) => {1035 const from = normalizeAccountId(accountFrom);1036 const to = normalizeAccountId(accountTo);1037 let balanceBefore = 0n;1038 if (type === 'Fungible' || type === 'ReFungible') {1039 balanceBefore = await getBalance(api, collectionId, to, tokenId);1040 }1041 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1042 if (type === 'NFT') {1043 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1044 }1045 if (type === 'Fungible') {1046 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1047 if (JSON.stringify(to) !== JSON.stringify(from)) {1048 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1049 } else {1050 expect(balanceAfter).to.be.equal(balanceBefore);1051 }1052 }1053 if (type === 'ReFungible') {1054 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1055 }1056 });1057}10581059export async function1060transferFromExpectFail(1061 collectionId: number,1062 tokenId: number,1063 accountApproved: IKeyringPair,1064 accountFrom: IKeyringPair,1065 accountTo: IKeyringPair,1066 value: number | bigint = 1,1067) {1068 await usingApi(async (api: ApiPromise) => {1069 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1070 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1071 const result = getCreateCollectionResult(events);1072 // tslint:disable-next-line:no-unused-expression1073 expect(result.success).to.be.false;1074 });1075}10761077/* eslint no-async-promise-executor: "off" */1078export async function getBlockNumber(api: ApiPromise): Promise<number> {1079 return new Promise<number>(async (resolve) => {1080 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1081 unsubscribe();1082 resolve(head.number.toNumber());1083 });1084 });1085}10861087export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1088 await usingApi(async (api) => {1089 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1090 const events = await submitTransactionAsync(sender, changeAdminTx);1091 const result = getCreateCollectionResult(events);1092 expect(result.success).to.be.true;1093 });1094}10951096export async function adminApproveFromExpectFail(1097 collectionId: number,1098 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1099) {1100 await usingApi(async (api: ApiPromise) => {1101 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1102 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1103 const result = getGenericResult(events);1104 expect(result.success).to.be.false;1105 });1106}11071108export async function1109getFreeBalance(account: IKeyringPair): Promise<bigint> {1110 let balance = 0n;1111 await usingApi(async (api) => {1112 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1113 });11141115 return balance;1116}11171118export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1119 return usingApi(async api => {1120 // We are getting a *sibling* parachain sovereign account,1121 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c1122 const siblingPrefix = '0x7369626c';11231124 const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1125 const suffix = '000000000000000000000000000000000000000000000000';11261127 return siblingPrefix + encodedParaId + suffix;1128 });1129}11301131export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1132 const tx = api.tx.balances.transfer(target, amount);1133 const events = await submitTransactionAsync(source, tx);1134 const result = getGenericResult(events);1135 expect(result.success).to.be.true;1136}11371138export async function1139scheduleExpectSuccess(1140 operationTx: any,1141 sender: IKeyringPair,1142 blockSchedule: number,1143 scheduledId: string,1144 period = 1,1145 repetitions = 1,1146) {1147 await usingApi(async (api: ApiPromise) => {1148 const blockNumber: number | undefined = await getBlockNumber(api);1149 const expectedBlockNumber = blockNumber + blockSchedule;11501151 expect(blockNumber).to.be.greaterThan(0);1152 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1153 scheduledId,1154 expectedBlockNumber,1155 repetitions > 1 ? [period, repetitions] : null,1156 0,1157 {Value: operationTx as any},1158 );11591160 const events = await submitTransactionAsync(sender, scheduleTx);1161 expect(getGenericResult(events).success).to.be.true;1162 });1163}11641165export async function1166scheduleExpectFailure(1167 operationTx: any,1168 sender: IKeyringPair,1169 blockSchedule: number,1170 scheduledId: string,1171 period = 1,1172 repetitions = 1,1173) {1174 await usingApi(async (api: ApiPromise) => {1175 const blockNumber: number | undefined = await getBlockNumber(api);1176 const expectedBlockNumber = blockNumber + blockSchedule;11771178 expect(blockNumber).to.be.greaterThan(0);1179 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1180 scheduledId,1181 expectedBlockNumber,1182 repetitions <= 1 ? null : [period, repetitions],1183 0,1184 {Value: operationTx as any},1185 );11861187 //const events =1188 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1189 //expect(getGenericResult(events).success).to.be.false;1190 });1191}11921193export async function1194scheduleTransferAndWaitExpectSuccess(1195 collectionId: number,1196 tokenId: number,1197 sender: IKeyringPair,1198 recipient: IKeyringPair,1199 value: number | bigint = 1,1200 blockSchedule: number,1201 scheduledId: string,1202) {1203 await usingApi(async (api: ApiPromise) => {1204 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);12051206 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();12071208 // sleep for n + 1 blocks1209 await waitNewBlocks(blockSchedule + 1);12101211 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();12121213 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1214 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1215 });1216}12171218export async function1219scheduleTransferExpectSuccess(1220 collectionId: number,1221 tokenId: number,1222 sender: IKeyringPair,1223 recipient: IKeyringPair,1224 value: number | bigint = 1,1225 blockSchedule: number,1226 scheduledId: string,1227) {1228 await usingApi(async (api: ApiPromise) => {1229 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12301231 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12321233 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1234 });1235}12361237export async function1238scheduleTransferFundsPeriodicExpectSuccess(1239 amount: bigint,1240 sender: IKeyringPair,1241 recipient: IKeyringPair,1242 blockSchedule: number,1243 scheduledId: string,1244 period: number,1245 repetitions: number,1246) {1247 await usingApi(async (api: ApiPromise) => {1248 const transferTx = api.tx.balances.transfer(recipient.address, amount);12491250 const balanceBefore = await getFreeBalance(recipient);12511252 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12531254 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1255 });1256}12571258export async function1259transfer(1260 api: ApiPromise,1261 collectionId: number,1262 tokenId: number,1263 sender: IKeyringPair,1264 recipient: IKeyringPair | CrossAccountId,1265 value: number | bigint,1266) : Promise<boolean> {1267 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1268 const events = await executeTransaction(api, sender, transferTx);1269 return getGenericResult(events).success;1270}12711272export async function1273transferExpectSuccess(1274 collectionId: number,1275 tokenId: number,1276 sender: IKeyringPair,1277 recipient: IKeyringPair | CrossAccountId,1278 value: number | bigint = 1,1279 type = 'NFT',1280) {1281 await usingApi(async (api: ApiPromise) => {1282 const from = normalizeAccountId(sender);1283 const to = normalizeAccountId(recipient);12841285 let balanceBefore = 0n;1286 if (type === 'Fungible' || type === 'ReFungible') {1287 balanceBefore = await getBalance(api, collectionId, to, tokenId);1288 }12891290 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1291 const events = await executeTransaction(api, sender, transferTx);1292 const result = getTransferResult(api, events);12931294 expect(result.collectionId).to.be.equal(collectionId);1295 expect(result.itemId).to.be.equal(tokenId);1296 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1297 expect(result.recipient).to.be.deep.equal(to);1298 expect(result.value).to.be.equal(BigInt(value));12991300 if (type === 'NFT') {1301 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1302 }1303 if (type === 'Fungible' || type === 'ReFungible') {1304 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1305 if (JSON.stringify(to) !== JSON.stringify(from)) {1306 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1307 } else {1308 expect(balanceAfter).to.be.equal(balanceBefore);1309 }1310 }1311 });1312}13131314export async function1315transferExpectFailure(1316 collectionId: number,1317 tokenId: number,1318 sender: IKeyringPair,1319 recipient: IKeyringPair | CrossAccountId,1320 value: number | bigint = 1,1321) {1322 await usingApi(async (api: ApiPromise) => {1323 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1324 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1325 const result = getGenericResult(events);1326 // if (events && Array.isArray(events)) {1327 // const result = getCreateCollectionResult(events);1328 // tslint:disable-next-line:no-unused-expression1329 expect(result.success).to.be.false;1330 //}1331 });1332}13331334export async function1335approveExpectFail(1336 collectionId: number,1337 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1338) {1339 await usingApi(async (api: ApiPromise) => {1340 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1341 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1342 const result = getCreateCollectionResult(events);1343 // tslint:disable-next-line:no-unused-expression1344 expect(result.success).to.be.false;1345 });1346}13471348export async function getBalance(1349 api: ApiPromise,1350 collectionId: number,1351 owner: string | CrossAccountId | IKeyringPair,1352 token: number,1353): Promise<bigint> {1354 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1355}1356export async function getTokenOwner(1357 api: ApiPromise,1358 collectionId: number,1359 token: number,1360): Promise<CrossAccountId> {1361 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1362 if (owner == null) throw new Error('owner == null');1363 return normalizeAccountId(owner);1364}1365export async function getTopmostTokenOwner(1366 api: ApiPromise,1367 collectionId: number,1368 token: number,1369): Promise<CrossAccountId> {1370 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1371 if (owner == null) throw new Error('owner == null');1372 return normalizeAccountId(owner);1373}1374export async function getTokenChildren(1375 api: ApiPromise,1376 collectionId: number,1377 tokenId: number,1378): Promise<UpDataStructsTokenChild[]> {1379 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1380}1381export async function isTokenExists(1382 api: ApiPromise,1383 collectionId: number,1384 token: number,1385): Promise<boolean> {1386 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1387}1388export async function getLastTokenId(1389 api: ApiPromise,1390 collectionId: number,1391): Promise<number> {1392 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1393}1394export async function getAdminList(1395 api: ApiPromise,1396 collectionId: number,1397): Promise<string[]> {1398 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1399}1400export async function getTokenProperties(1401 api: ApiPromise,1402 collectionId: number,1403 tokenId: number,1404 propertyKeys: string[],1405): Promise<UpDataStructsProperty[]> {1406 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1407}14081409export async function createFungibleItemExpectSuccess(1410 sender: IKeyringPair,1411 collectionId: number,1412 data: CreateFungibleData,1413 owner: CrossAccountId | string = sender.address,1414) {1415 return await usingApi(async (api) => {1416 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});14171418 const events = await submitTransactionAsync(sender, tx);1419 const result = getCreateItemResult(events);14201421 expect(result.success).to.be.true;1422 return result.itemId;1423 });1424}14251426export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1427 await usingApi(async (api) => {1428 const to = normalizeAccountId(owner);1429 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14301431 const events = await submitTransactionAsync(sender, tx);1432 expect(getGenericResult(events).success).to.be.true;1433 });1434}14351436export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1437 await usingApi(async (api) => {1438 const to = normalizeAccountId(owner);1439 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14401441 const events = await submitTransactionAsync(sender, tx);1442 const result = getCreateItemsResult(events);14431444 for (const res of result) {1445 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1446 }1447 });1448}14491450export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1451 await usingApi(async (api) => {1452 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14531454 const events = await submitTransactionAsync(sender, tx);1455 const result = getCreateItemsResult(events);14561457 for (const res of result) {1458 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1459 }1460 });1461}14621463export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1464 let newItemId = 0;1465 await usingApi(async (api) => {1466 const to = normalizeAccountId(owner);1467 const itemCountBefore = await getLastTokenId(api, collectionId);1468 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14691470 let tx;1471 if (createMode === 'Fungible') {1472 const createData = {fungible: {value: 10}};1473 tx = api.tx.unique.createItem(collectionId, to, createData as any);1474 } else if (createMode === 'ReFungible') {1475 const createData = {refungible: {pieces: 100}};1476 tx = api.tx.unique.createItem(collectionId, to, createData as any);1477 } else {1478 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1479 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1480 }14811482 const events = await submitTransactionAsync(sender, tx);1483 const result = getCreateItemResult(events);14841485 const itemCountAfter = await getLastTokenId(api, collectionId);1486 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14871488 if (createMode === 'NFT') {1489 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1490 }14911492 // What to expect1493 // tslint:disable-next-line:no-unused-expression1494 expect(result.success).to.be.true;1495 if (createMode === 'Fungible') {1496 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1497 } else {1498 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1499 }1500 expect(collectionId).to.be.equal(result.collectionId);1501 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1502 expect(to).to.be.deep.equal(result.recipient);1503 newItemId = result.itemId;1504 });1505 return newItemId;1506}15071508export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1509 await usingApi(async (api) => {15101511 let tx;1512 if (createMode === 'NFT') {1513 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1514 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1515 } else {1516 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1517 }151815191520 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1521 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1522 const result = getCreateItemResult(events);15231524 expect(result.success).to.be.false;1525 });1526}15271528export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1529 let newItemId = 0;1530 await usingApi(async (api) => {1531 const to = normalizeAccountId(owner);1532 const itemCountBefore = await getLastTokenId(api, collectionId);1533 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15341535 let tx;1536 if (createMode === 'Fungible') {1537 const createData = {fungible: {value: 10}};1538 tx = api.tx.unique.createItem(collectionId, to, createData as any);1539 } else if (createMode === 'ReFungible') {1540 const createData = {refungible: {pieces: 100}};1541 tx = api.tx.unique.createItem(collectionId, to, createData as any);1542 } else {1543 const createData = {nft: {}};1544 tx = api.tx.unique.createItem(collectionId, to, createData as any);1545 }15461547 const events = await executeTransaction(api, sender, tx);1548 const result = getCreateItemResult(events);15491550 const itemCountAfter = await getLastTokenId(api, collectionId);1551 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15521553 // What to expect1554 // tslint:disable-next-line:no-unused-expression1555 expect(result.success).to.be.true;1556 if (createMode === 'Fungible') {1557 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1558 } else {1559 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1560 }1561 expect(collectionId).to.be.equal(result.collectionId);1562 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1563 expect(to).to.be.deep.equal(result.recipient);1564 newItemId = result.itemId;1565 });1566 return newItemId;1567}15681569export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1570 const createData = {refungible: {pieces: amount}};1571 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15721573 const events = await submitTransactionAsync(sender, tx);1574 return getCreateItemResult(events);1575}15761577export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1578 await usingApi(async (api) => {1579 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15801581 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1582 const result = getCreateItemResult(events);15831584 expect(result.success).to.be.false;1585 });1586}15871588export async function setPublicAccessModeExpectSuccess(1589 sender: IKeyringPair, collectionId: number,1590 accessMode: 'Normal' | 'AllowList',1591) {1592 await usingApi(async (api) => {15931594 // Run the transaction1595 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1596 const events = await submitTransactionAsync(sender, tx);1597 const result = getGenericResult(events);15981599 // Get the collection1600 const collection = await queryCollectionExpectSuccess(api, collectionId);16011602 // What to expect1603 // tslint:disable-next-line:no-unused-expression1604 expect(result.success).to.be.true;1605 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1606 });1607}16081609export async function setPublicAccessModeExpectFail(1610 sender: IKeyringPair, collectionId: number,1611 accessMode: 'Normal' | 'AllowList',1612) {1613 await usingApi(async (api) => {16141615 // Run the transaction1616 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1617 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1618 const result = getGenericResult(events);16191620 // What to expect1621 // tslint:disable-next-line:no-unused-expression1622 expect(result.success).to.be.false;1623 });1624}16251626export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1627 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1628}16291630export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1631 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1632}16331634export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1635 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1636}16371638export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1639 await usingApi(async (api) => {16401641 // Run the transaction1642 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1643 const events = await submitTransactionAsync(sender, tx);1644 const result = getGenericResult(events);1645 expect(result.success).to.be.true;16461647 // Get the collection1648 const collection = await queryCollectionExpectSuccess(api, collectionId);16491650 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1651 });1652}16531654export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1655 await setMintPermissionExpectSuccess(sender, collectionId, true);1656}16571658export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1659 await usingApi(async (api) => {1660 // Run the transaction1661 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1662 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1663 const result = getCreateCollectionResult(events);1664 // tslint:disable-next-line:no-unused-expression1665 expect(result.success).to.be.false;1666 });1667}16681669export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1670 await usingApi(async (api) => {1671 // Run the transaction1672 const tx = api.tx.unique.setChainLimits(limits);1673 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1674 const result = getCreateCollectionResult(events);1675 // tslint:disable-next-line:no-unused-expression1676 expect(result.success).to.be.false;1677 });1678}16791680export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {1681 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1682}16831684export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1685 await usingApi(async (api) => {1686 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16871688 // Run the transaction1689 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1690 const events = await submitTransactionAsync(sender, tx);1691 const result = getGenericResult(events);1692 expect(result.success).to.be.true;16931694 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1695 });1696}16971698export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1699 await usingApi(async (api) => {17001701 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;17021703 // Run the transaction1704 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1705 const events = await submitTransactionAsync(sender, tx);1706 const result = getGenericResult(events);1707 expect(result.success).to.be.true;17081709 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1710 });1711}17121713export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1714 await usingApi(async (api) => {17151716 // Run the transaction1717 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1718 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1719 const result = getGenericResult(events);17201721 // What to expect1722 // tslint:disable-next-line:no-unused-expression1723 expect(result.success).to.be.false;1724 });1725}17261727export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1728 await usingApi(async (api) => {1729 // Run the transaction1730 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1731 const events = await submitTransactionAsync(sender, tx);1732 const result = getGenericResult(events);17331734 // What to expect1735 // tslint:disable-next-line:no-unused-expression1736 expect(result.success).to.be.true;1737 });1738}17391740export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1741 await usingApi(async (api) => {1742 // Run the transaction1743 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1744 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1745 const result = getGenericResult(events);17461747 // What to expect1748 // tslint:disable-next-line:no-unused-expression1749 expect(result.success).to.be.false;1750 });1751}17521753export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1754 : Promise<UpDataStructsRpcCollection | null> => {1755 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1756};17571758export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1759 // set global object - collectionsCount1760 return (await api.rpc.unique.collectionStats()).created.toNumber();1761};17621763export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1764 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1765}17661767export async function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {1768 (process.env.RUN_XCM_TESTS && !opts.skip1769 ? describe1770 : describe.skip)(title, fn);1771}17721773describeXCM.skip = (name: string, fn: (this: Mocha.Suite) => void) => describeXCM(name, fn, {skip: true});17741775export async function waitNewBlocks(blocksCount = 1): Promise<void> {1776 await usingApi(async (api) => {1777 const promise = new Promise<void>(async (resolve) => {1778 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1779 if (blocksCount > 0) {1780 blocksCount--;1781 } else {1782 unsubscribe();1783 resolve();1784 }1785 });1786 });1787 return promise;1788 });1789}17901791export async function waitEvent(1792 api: ApiPromise,1793 maxBlocksToWait: number,1794 eventSection: string,1795 eventMethod: string,1796): Promise<EventRecord | null> {17971798 const promise = new Promise<EventRecord | null>(async (resolve) => {1799 const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {1800 const blockNumber = header.number.toHuman();1801 const blockHash = header.hash;1802 const eventIdStr = `${eventSection}.${eventMethod}`;1803 const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;18041805 console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);18061807 const apiAt = await api.at(blockHash);1808 const eventRecords = await apiAt.query.system.events();18091810 const neededEvent = eventRecords.find(r => {1811 return r.event.section == eventSection && r.event.method == eventMethod;1812 });18131814 if (neededEvent) {1815 unsubscribe();1816 resolve(neededEvent);1817 } else if (maxBlocksToWait > 0) {1818 maxBlocksToWait--;1819 } else {1820 console.log(`Event \`${eventIdStr}\` is NOT found`);18211822 unsubscribe();1823 resolve(null);1824 }1825 });1826 });1827 return promise;1828}18291830export async function repartitionRFT(1831 api: ApiPromise,1832 collectionId: number,1833 sender: IKeyringPair,1834 tokenId: number,1835 amount: bigint,1836): Promise<boolean> {1837 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1838 const events = await submitTransactionAsync(sender, tx);1839 const result = getGenericResult(events);18401841 return result.success;1842}18431844export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1845 let i: any = it;1846 if (opts.only) i = i.only;1847 else if (opts.skip) i = i.skip;1848 i(name, async () => {1849 await usingApi(async (api, privateKeyWrapper) => {1850 await cb({api, privateKeyWrapper});1851 });1852 });1853}18541855itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1856itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18571858let accountSeed = 10000;1859export function generateKeyringPair(keyring: Keyring) {1860 const privateKey = `0xDEADBEEF${(Date.now()+(accountSeed++)).toString(16).padStart(64-8,'0')}`;1861 return keyring.addFromUri(privateKey);1862}18631864export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {1865 const blockHash = await api.rpc.chain.getBlockHash(blockNumber);1866 const subEvents = (await api.query.system.events.at(blockHash))1867 .filter(x => x.event.section === section)1868 .map((x) => x.toHuman());1869 const events = methods.map((m) => {1870 return {1871 event: {1872 method: m,1873 section,1874 },1875 };1876 });1877 if (!dryRun) {1878 expect(subEvents).to.be.like(events);1879 }1880 return subEvents;1881}tests/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;
-}
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -361,6 +361,7 @@
}
clearApi() {
+ super.clearApi();
this.web3 = null;
}
tests/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(); });
});
tests/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(); });
});
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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/);
});
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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(); });
});
tests/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');
tests/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});
tests/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'
tests/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 {
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -9,7 +9,7 @@
import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';
import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
-import {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';
+import {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';
export class CrossAccountId implements ICrossAccountId {
Substrate?: TSubstrateAccount;
@@ -252,6 +252,19 @@
isSuccess = isSuccess && amount === transfer.amount;
return isSuccess;
}
+
+ static bigIntToDecimals(number: bigint, decimals = 18) {
+ 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;
+ }
+ }
}
class UniqueEventHelper {
@@ -308,19 +321,25 @@
}
}
-class ChainHelperBase {
+export class ChainHelperBase {
+ helperBase: any;
+
transactionStatus = UniqueUtil.transactionStatus;
chainLogType = UniqueUtil.chainLogType;
util: typeof UniqueUtil;
eventHelper: typeof UniqueEventHelper;
logger: ILogger;
api: ApiPromise | null;
- forcedNetwork: TUniqueNetworks | null;
- network: TUniqueNetworks | null;
+ forcedNetwork: TNetworks | null;
+ network: TNetworks | null;
chainLog: IUniqueHelperLog[];
children: ChainHelperBase[];
+ address: AddressGroup;
+ chain: ChainGroup;
- constructor(logger?: ILogger) {
+ constructor(logger?: ILogger, helperBase?: any) {
+ this.helperBase = helperBase;
+
this.util = UniqueUtil;
this.eventHelper = UniqueEventHelper;
if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();
@@ -330,8 +349,23 @@
this.network = null;
this.chainLog = [];
this.children = [];
+ this.address = new AddressGroup(this);
+ this.chain = new ChainGroup(this);
}
+ clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {
+ Object.setPrototypeOf(helperCls.prototype, this);
+ const newHelper = new helperCls(this.logger, options);
+
+ newHelper.api = this.api;
+ newHelper.network = this.network;
+ newHelper.forceNetwork = this.forceNetwork;
+
+ this.children.push(newHelper);
+
+ return newHelper;
+ }
+
getApi(): ApiPromise {
if(this.api === null) throw Error('API not initialized');
return this.api;
@@ -341,7 +375,7 @@
this.chainLog = [];
}
- forceNetwork(value: TUniqueNetworks): void {
+ forceNetwork(value: TNetworks): void {
this.forcedNetwork = value;
}
@@ -367,13 +401,17 @@
this.network = null;
}
- static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {
+ static async detectNetwork(api: ApiPromise): Promise<TNetworks> {
const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;
+ const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];
+
+ if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;
+
if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;
return 'opal';
}
- static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {
+ static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {
const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});
await api.isReady;
@@ -384,9 +422,9 @@
return network;
}
- static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{
+ static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{
api: ApiPromise;
- network: TUniqueNetworks;
+ network: TNetworks;
}> {
if(typeof network === 'undefined' || network === null) network = 'opal';
const supportedRPC = {
@@ -399,6 +437,13 @@
unique: {
unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,
},
+ rococo: {},
+ westend: {},
+ moonbeam: {},
+ moonriver: {},
+ acala: {},
+ karura: {},
+ westmint: {},
};
if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);
const rpc = supportedRPC[network];
@@ -590,16 +635,16 @@
}
-class HelperGroup {
- helper: UniqueHelper;
+class HelperGroup<T extends ChainHelperBase> {
+ helper: T;
- constructor(uniqueHelper: UniqueHelper) {
+ constructor(uniqueHelper: T) {
this.helper = uniqueHelper;
}
}
-class CollectionGroup extends HelperGroup {
+class CollectionGroup extends HelperGroup<UniqueHelper> {
/**
* Get number of blocks when sponsored transaction is available.
*
@@ -2000,7 +2045,7 @@
}
-class ChainGroup extends HelperGroup {
+class ChainGroup extends HelperGroup<ChainHelperBase> {
/**
* Get system properties of a chain
* @example getChainProperties();
@@ -2054,10 +2099,106 @@
}
}
+class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ /**
+ * Get substrate address balance
+ * @param address substrate address
+ * @example getSubstrate("5GrwvaEF5zXb26Fz...")
+ * @returns amount of tokens on address
+ */
+ async getSubstrate(address: TSubstrateAccount): Promise<bigint> {
+ return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();
+ }
+
+ /**
+ * Transfer tokens to substrate address
+ * @param signer keyring of signer
+ * @param address substrate address of a recipient
+ * @param amount amount of tokens to be transfered
+ * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);
+ * @returns ```true``` if extrinsic success, otherwise ```false```
+ */
+ async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {
+ 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}`*/);
+
+ let transfer = {from: null, to: null, amount: 0n} as any;
+ result.result.events.forEach(({event: {data, method, section}}) => {
+ if ((section === 'balances') && (method === 'Transfer')) {
+ transfer = {
+ from: this.helper.address.normalizeSubstrate(data[0]),
+ to: this.helper.address.normalizeSubstrate(data[1]),
+ amount: BigInt(data[2]),
+ };
+ }
+ });
+ const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from
+ && this.helper.address.normalizeSubstrate(address) === transfer.to
+ && BigInt(amount) === transfer.amount;
+ return isSuccess;
+ }
+
+ /**
+ * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved
+ * @param address substrate address
+ * @returns
+ */
+ async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {
+ const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;
+ return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};
+ }
+}
+
+class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ /**
+ * Get ethereum address balance
+ * @param address ethereum address
+ * @example getEthereum("0x9F0583DbB855d...")
+ * @returns amount of tokens on address
+ */
+ async getEthereum(address: TEthereumAccount): Promise<bigint> {
+ return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();
+ }
-class BalanceGroup extends HelperGroup {
+ /**
+ * Transfer tokens to address
+ * @param signer keyring of signer
+ * @param address Ethereum address of a recipient
+ * @param amount amount of tokens to be transfered
+ * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);
+ * @returns ```true``` if extrinsic success, otherwise ```false```
+ */
+ async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {
+ const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);
+
+ let transfer = {from: null, to: null, amount: 0n} as any;
+ result.result.events.forEach(({event: {data, method, section}}) => {
+ if ((section === 'balances') && (method === 'Transfer')) {
+ transfer = {
+ from: data[0].toString(),
+ to: data[1].toString(),
+ amount: BigInt(data[2]),
+ };
+ }
+ });
+ const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from
+ && address === transfer.to
+ && BigInt(amount) === transfer.amount;
+ return isSuccess;
+ }
+}
+
+class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ subBalanceGroup: SubstrateBalanceGroup<T>;
+ ethBalanceGroup: EthereumBalanceGroup<T>;
+
+ constructor(helper: T) {
+ super(helper);
+ this.subBalanceGroup = new SubstrateBalanceGroup(helper);
+ this.ethBalanceGroup = new EthereumBalanceGroup(helper);
+ }
+
getCollectionCreationPrice(): bigint {
- return 2n * this.helper.balance.getOneTokenNominal();
+ return 2n * this.getOneTokenNominal();
}
/**
* Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).
@@ -2076,7 +2217,7 @@
* @returns amount of tokens on address
*/
async getSubstrate(address: TSubstrateAccount): Promise<bigint> {
- return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();
+ return this.subBalanceGroup.getSubstrate(address);
}
/**
@@ -2085,8 +2226,7 @@
* @returns
*/
async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {
- const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;
- return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};
+ return this.subBalanceGroup.getSubstrateFull(address);
}
/**
@@ -2096,7 +2236,7 @@
* @returns amount of tokens on address
*/
async getEthereum(address: TEthereumAccount): Promise<bigint> {
- return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();
+ return this.ethBalanceGroup.getEthereum(address);
}
/**
@@ -2108,27 +2248,11 @@
* @returns ```true``` if extrinsic success, otherwise ```false```
*/
async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {
- 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}`*/);
-
- let transfer = {from: null, to: null, amount: 0n} as any;
- result.result.events.forEach(({event: {data, method, section}}) => {
- if ((section === 'balances') && (method === 'Transfer')) {
- transfer = {
- from: this.helper.address.normalizeSubstrate(data[0]),
- to: this.helper.address.normalizeSubstrate(data[1]),
- amount: BigInt(data[2]),
- };
- }
- });
- const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from
- && this.helper.address.normalizeSubstrate(address) === transfer.to
- && BigInt(amount) === transfer.amount;
- return isSuccess;
+ return this.subBalanceGroup.transferToSubstrate(signer, address, amount);
}
}
-
-class AddressGroup extends HelperGroup {
+class AddressGroup extends HelperGroup<ChainHelperBase> {
/**
* Normalizes the address to the specified ss58 format, by default ```42```.
* @param address substrate address
@@ -2170,9 +2294,20 @@
substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {
return CrossAccountId.translateSubToEth(subAddress);
}
+
+ paraSiblingSovereignAccount(paraid: number) {
+ // We are getting a *sibling* parachain sovereign account,
+ // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c
+ const siblingPrefix = '0x7369626c';
+
+ const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);
+ const suffix = '000000000000000000000000000000000000000000000000';
+
+ return siblingPrefix + encodedParaId + suffix;
+ }
}
-class StakingGroup extends HelperGroup {
+class StakingGroup extends HelperGroup<UniqueHelper> {
/**
* Stake tokens for App Promotion
* @param signer keyring of signer
@@ -2258,7 +2393,7 @@
}
}
-class SchedulerGroup extends HelperGroup {
+class SchedulerGroup extends HelperGroup<UniqueHelper> {
constructor(helper: UniqueHelper) {
super(helper);
}
@@ -2314,53 +2449,281 @@
}
}
+class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {
+ async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {
+ await this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.foreignAssets.registerForeignAsset',
+ [ownerAddress, location, metadata],
+ true,
+ );
+ }
+
+ async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {
+ await this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.foreignAssets.updateForeignAsset',
+ [foreignAssetId, location, metadata],
+ true,
+ );
+ }
+}
+
+class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ palletName: string;
+
+ constructor(helper: T, palletName: string) {
+ super(helper);
+
+ this.palletName = palletName;
+ }
+
+ async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);
+ }
+}
+
+class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);
+ }
+
+ async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);
+ }
+
+ async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);
+ }
+}
+
+class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ async accounts(address: string, currencyId: any) {
+ const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;
+ return BigInt(free);
+ }
+}
+
+class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {
+ async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);
+ }
+
+ async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);
+ }
+
+ async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);
+ }
+
+ async account(assetId: string | number, address: string) {
+ const accountAsset = (
+ await this.helper.callRpc('api.query.assets.account', [assetId, address])
+ ).toJSON()! as any;
+
+ if (accountAsset !== null) {
+ return BigInt(accountAsset['balance']);
+ } else {
+ return null;
+ }
+ }
+}
+
+class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {
+ async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);
+ }
+}
+
+class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {
+ makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {
+ const apiPrefix = 'api.tx.assetManager.';
+
+ const registerTx = this.helper.constructApiCall(
+ apiPrefix + 'registerForeignAsset',
+ [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],
+ );
+
+ const setUnitsTx = this.helper.constructApiCall(
+ apiPrefix + 'setAssetUnitsPerSecond',
+ [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],
+ );
+
+ const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);
+ const encodedProposal = batchCall?.method.toHex() || '';
+ return encodedProposal;
+ }
+
+ async assetTypeId(location: any) {
+ return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);
+ }
+}
+
+class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {
+ async notePreimage(signer: TSigner, encodedProposal: string) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);
+ }
+
+ externalProposeMajority(proposalHash: string) {
+ return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);
+ }
+
+ fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {
+ return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);
+ }
+
+ async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {
+ await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);
+ }
+}
+
+class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {
+ collective: string;
+
+ constructor(helper: MoonbeamHelper, collective: string) {
+ super(helper);
+
+ this.collective = collective;
+ }
+
+ async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);
+ }
+
+ async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);
+ }
+
+ async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {
+ await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);
+ }
+
+ async proposalCount() {
+ return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));
+ }
+}
+
+export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;
export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;
export class UniqueHelper extends ChainHelperBase {
- helperBase: any;
-
- chain: ChainGroup;
- balance: BalanceGroup;
- address: AddressGroup;
+ balance: BalanceGroup<UniqueHelper>;
collection: CollectionGroup;
nft: NFTGroup;
rft: RFTGroup;
ft: FTGroup;
staking: StakingGroup;
scheduler: SchedulerGroup;
+ foreignAssets: ForeignAssetsGroup;
+ xcm: XcmGroup<UniqueHelper>;
+ xTokens: XTokensGroup<UniqueHelper>;
+ tokens: TokensGroup<UniqueHelper>;
constructor(logger?: ILogger, options: {[key: string]: any} = {}) {
- super(logger);
-
- this.helperBase = options.helperBase ?? UniqueHelper;
+ super(logger, options.helperBase ?? UniqueHelper);
- this.chain = new ChainGroup(this);
this.balance = new BalanceGroup(this);
- this.address = new AddressGroup(this);
this.collection = new CollectionGroup(this);
this.nft = new NFTGroup(this);
this.rft = new RFTGroup(this);
this.ft = new FTGroup(this);
this.staking = new StakingGroup(this);
this.scheduler = new SchedulerGroup(this);
+ this.foreignAssets = new ForeignAssetsGroup(this);
+ this.xcm = new XcmGroup(this, 'polkadotXcm');
+ this.xTokens = new XTokensGroup(this);
+ this.tokens = new TokensGroup(this);
}
- clone(helperCls: UniqueHelperConstructor, options: {[key: string]: any} = {}) {
- Object.setPrototypeOf(helperCls.prototype, this);
- const newHelper = new helperCls(this.logger, options);
+ getSudo<T extends UniqueHelper>() {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const SudoHelperType = SudoHelper(this.helperBase);
+ return this.clone(SudoHelperType) as T;
+ }
+}
+
+export class XcmChainHelper extends ChainHelperBase {
+ async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
+ const wsProvider = new WsProvider(wsEndpoint);
+ this.api = new ApiPromise({
+ provider: wsProvider,
+ });
+ await this.api.isReadyOrError;
+ this.network = await UniqueHelper.detectNetwork(this.api);
+ }
+}
- newHelper.api = this.api;
- newHelper.network = this.network;
- newHelper.forceNetwork = this.forceNetwork;
+export class RelayHelper extends XcmChainHelper {
+ xcm: XcmGroup<RelayHelper>;
- this.children.push(newHelper);
+ constructor(logger?: ILogger, options: {[key: string]: any} = {}) {
+ super(logger, options.helperBase ?? RelayHelper);
- return newHelper;
+ this.xcm = new XcmGroup(this, 'xcmPallet');
}
+}
- getSudo<T extends UniqueHelper>() {
+export class WestmintHelper extends XcmChainHelper {
+ balance: SubstrateBalanceGroup<WestmintHelper>;
+ xcm: XcmGroup<WestmintHelper>;
+ assets: AssetsGroup<WestmintHelper>;
+ xTokens: XTokensGroup<WestmintHelper>;
+
+ constructor(logger?: ILogger, options: {[key: string]: any} = {}) {
+ super(logger, options.helperBase ?? WestmintHelper);
+
+ this.balance = new SubstrateBalanceGroup(this);
+ this.xcm = new XcmGroup(this, 'polkadotXcm');
+ this.assets = new AssetsGroup(this);
+ this.xTokens = new XTokensGroup(this);
+ }
+}
+
+export class MoonbeamHelper extends XcmChainHelper {
+ balance: EthereumBalanceGroup<MoonbeamHelper>;
+ assetManager: MoonbeamAssetManagerGroup;
+ assets: AssetsGroup<MoonbeamHelper>;
+ xTokens: XTokensGroup<MoonbeamHelper>;
+ democracy: MoonbeamDemocracyGroup;
+ collective: {
+ council: MoonbeamCollectiveGroup,
+ techCommittee: MoonbeamCollectiveGroup,
+ };
+
+ constructor(logger?: ILogger, options: {[key: string]: any} = {}) {
+ super(logger, options.helperBase ?? MoonbeamHelper);
+
+ this.balance = new EthereumBalanceGroup(this);
+ this.assetManager = new MoonbeamAssetManagerGroup(this);
+ this.assets = new AssetsGroup(this);
+ this.xTokens = new XTokensGroup(this);
+ this.democracy = new MoonbeamDemocracyGroup(this);
+ this.collective = {
+ council: new MoonbeamCollectiveGroup(this, 'councilCollective'),
+ techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),
+ };
+ }
+}
+
+export class AcalaHelper extends XcmChainHelper {
+ balance: SubstrateBalanceGroup<AcalaHelper>;
+ assetRegistry: AcalaAssetRegistryGroup;
+ xTokens: XTokensGroup<AcalaHelper>;
+ tokens: TokensGroup<AcalaHelper>;
+
+ constructor(logger?: ILogger, options: {[key: string]: any} = {}) {
+ super(logger, options.helperBase ?? AcalaHelper);
+
+ this.balance = new SubstrateBalanceGroup(this);
+ this.assetRegistry = new AcalaAssetRegistryGroup(this);
+ this.xTokens = new XTokensGroup(this);
+ this.tokens = new TokensGroup(this);
+ }
+
+ getSudo<T extends AcalaHelper>() {
// eslint-disable-next-line @typescript-eslint/naming-convention
- const SudoHelperType = SudoUniqueHelper(this.helperBase);
+ const SudoHelperType = SudoHelper(this.helperBase);
return this.clone(SudoHelperType) as T;
}
}
@@ -2411,7 +2774,7 @@
}
// eslint-disable-next-line @typescript-eslint/naming-convention
-function SudoUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {
+function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {
return class extends Base {
constructor(...args: any[]) {
super(...args);
tests/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);
});
-
});
tests/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;
});
});
tests/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;
});
});