difftreelog
Merge branch 'feature/multi-assets-redone' of https://github.com/UniqueNetwork/unique-chain into feature/multi-assets-redone
in: master
28 files changed
.docker/xcm-config/launch-config-xcm-unique-rococo.jsondiffbeforeafterboth--- /dev/null
+++ b/.docker/xcm-config/launch-config-xcm-unique-rococo.json
@@ -0,0 +1,207 @@
+{
+ "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": "2037",
+ "balance": "1000000000000000000000000",
+ "nodes": [
+ {
+ "port": 31200,
+ "wsPort": 9944,
+ "rpcPort": 9933,
+ "name": "alice",
+ "flags": [
+ "-lruntime=trace",
+ "-lxcm=trace",
+ "--unsafe-rpc-external",
+ "--unsafe-ws-external"
+ ]
+ }
+ ]
+ },
+ {
+ "bin": "/acala/target/release/acala",
+ "id": "2000",
+ "chain": "acala-dev",
+ "balance": "1000000000000000000000",
+ "chainInitializer": [
+ "chainql",
+ "-e",
+ "(import '${spec}') {id+: '-local'}"
+ ],
+ "nodes": [
+ {
+ "wsPort": 9946,
+ "port": 31202,
+ "name": "alice",
+ "flags": [
+ "-lruntime=trace",
+ "-lxcm=trace",
+ "--unsafe-rpc-external",
+ "--unsafe-ws-external"
+ ]
+ }
+ ]
+ },
+ {
+ "bin": "/moonbeam/target/release/moonbeam",
+ "id": "2004",
+ "balance": "1000000000000000000000",
+ "chain": "moonbeam-local",
+ "nodes": [
+ {
+ "wsPort": 9947,
+ "port": 31203,
+ "name": "alice",
+ "flags": [
+ "-lruntime=trace",
+ "-lxcm=trace",
+ "--unsafe-rpc-external",
+ "--unsafe-ws-external",
+ "--",
+ "--execution=wasm"
+ ]
+ }
+ ]
+ },
+ {
+ "bin": "/cumulus/target/release/cumulus",
+ "id": "1000",
+ "chain": "statemint-local",
+ "balance": "1000000000000000000000000",
+ "nodes": [
+ {
+ "wsPort": 9948,
+ "port": 31204,
+ "name": "alice",
+ "flags": [
+ "-lruntime=trace",
+ "-lxcm=trace",
+ "--unsafe-rpc-external",
+ "--unsafe-ws-external"
+ ]
+ }
+ ]
+ }
+ ],
+ "simpleParachains": [],
+ "hrmpChannels": [
+ {
+ "sender": 2037,
+ "recipient": 2000,
+ "maxCapacity": 8,
+ "maxMessageSize": 512
+ },
+ {
+ "sender": 2000,
+ "recipient": 2037,
+ "maxCapacity": 8,
+ "maxMessageSize": 512
+ },
+ {
+ "sender": 2037,
+ "recipient": 2004,
+ "maxCapacity": 8,
+ "maxMessageSize": 512
+ },
+ {
+ "sender": 2004,
+ "recipient": 2037,
+ "maxCapacity": 8,
+ "maxMessageSize": 512
+ },
+ {
+ "sender": 2037,
+ "recipient": 1000,
+ "maxCapacity": 8,
+ "maxMessageSize": 512
+ },
+ {
+ "sender": 1000,
+ "recipient": 2037,
+ "maxCapacity": 8,
+ "maxMessageSize": 512
+ }
+ ],
+ "finalization": false
+}
+
.docker/xcm-config/launch-config-xcm-unique.jsondiffbeforeafterboth--- a/.docker/xcm-config/launch-config-xcm-unique.json
+++ b/.docker/xcm-config/launch-config-xcm-unique.json
@@ -101,6 +101,11 @@
"id": "2000",
"chain": "acala-dev",
"balance": "1000000000000000000000",
+ "chainInitializer": [
+ "chainql",
+ "-e",
+ "(import '${spec}') {id+: '-local'}"
+ ],
"nodes": [
{
"wsPort": 9946,
.envdiffbeforeafterboth--- a/.env
+++ b/.env
@@ -15,6 +15,13 @@
POLKADOT_LAUNCH_BRANCH=feature/rewrite-chain-id-in-spec
-ACALA_BUILD_BRANCH=2.9.0
-MOONBEAM_BUILD_BRANCH=v0.25.0
-CUMULUS_BUILD_BRANCH=release-v0.9.230
+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
+
.github/workflows/ci-develop.ymldiffbeforeafterboth--- a/.github/workflows/ci-develop.yml
+++ b/.github/workflows/ci-develop.yml
@@ -12,27 +12,23 @@
jobs:
yarn-test-dev:
- if: ${{ github.event.pull_request.draft == 'false' }}
uses: ./.github/workflows/dev-build-tests_v2.yml
unit-test:
- if: ${{ github.event.pull_request.draft == 'false' }}
uses: ./.github/workflows/unit-test_v2.yml
-
- forkless:
- if: ${{ contains( github.event.pull_request.labels.*.name, 'forkless') }}
- uses: ./.github/workflows/forkless.yml
canary:
if: ${{ contains( github.event.pull_request.labels.*.name, 'canary') }}
uses: ./.github/workflows/canary.yml
secrets: inherit # pass all secrets
-
xcm:
if: ${{ contains( github.event.pull_request.labels.*.name, 'xcm') }}
uses: ./.github/workflows/xcm.yml
secrets: inherit # pass all secrets
codestyle:
- uses: ./.github/workflows/codestyle_v2.yml
\ No newline at end of file
+ uses: ./.github/workflows/codestyle_v2.yml
+
+ yarn_eslint:
+ uses: ./.github/workflows/test_codestyle_v2.yml
.github/workflows/ci-master.ymldiffbeforeafterboth--- a/.github/workflows/ci-master.yml
+++ b/.github/workflows/ci-master.yml
@@ -12,11 +12,9 @@
jobs:
unit-test:
- if: ${{ github.event.pull_request.draft != 'true' }}
uses: ./.github/workflows/unit-test_v2.yml
node-only-update:
- if: ${{ github.event.pull_request.draft == 'false' }}
uses: ./.github/workflows/node-only-update_v2.yml
forkless:
@@ -34,5 +32,4 @@
secrets: inherit # pass all secrets
codestyle:
- if: ${{ github.event.pull_request.draft == 'false' }}
uses: ./.github/workflows/codestyle_v2.yml
\ No newline at end of file
.github/workflows/dev-build-tests_v2.ymldiffbeforeafterboth--- a/.github/workflows/dev-build-tests_v2.yml
+++ b/.github/workflows/dev-build-tests_v2.yml
@@ -37,23 +37,6 @@
features: "unique-runtime"
steps:
- - name: Skip if pull request is in Draft
- # `if: github.event.pull_request.draft == true` should be kept here, at
- # the step level, rather than at the job level. The latter is not
- # recommended because when the PR is moved from "Draft" to "Ready to
- # review" the workflow will immediately be passing (since it was skipped),
- # even though it hasn't actually ran, since it takes a few seconds for
- # the workflow to start. This is also disclosed in:
- # https://github.community/t/dont-run-actions-on-draft-pull-requests/16817/17
- # That scenario would open an opportunity for the check to be bypassed:
- # 1. Get your PR approved
- # 2. Move it to Draft
- # 3. Push whatever commits you want
- # 4. Move it to "Ready for review"; now the workflow is passing (it was
- # skipped) and "Check reviews" is also passing (it won't be updated
- # until the workflow is finished)
- if: github.event.pull_request.draft == true
- run: exit 1
- name: Clean Workspace
uses: AutoModality/action-clean@v1.1.0
@@ -92,7 +75,6 @@
yarn install
yarn add mochawesome
echo "Ready to start tests"
- node scripts/readyness.js
NOW=$(date +%s) && yarn test --reporter mochawesome --reporter-options reportFilename=test-${NOW}
env:
RPC_URL: http://127.0.0.1:9933/
.github/workflows/test_codestyle_v2.ymldiffbeforeafterboth--- a/.github/workflows/test_codestyle_v2.yml
+++ b/.github/workflows/test_codestyle_v2.yml
@@ -5,7 +5,7 @@
jobs:
code_style:
- runs-on: self-hosted-ci
+ runs-on: [ self-hosted-ci ]
steps:
- uses: actions/checkout@v3
.github/workflows/xcm-testnet-build.ymldiffbeforeafterboth--- a/.github/workflows/xcm-testnet-build.yml
+++ b/.github/workflows/xcm-testnet-build.yml
@@ -18,7 +18,7 @@
name: Prepare execution matrix
- runs-on: XL
+ runs-on: [XL]
outputs:
matrix: ${{ steps.create_matrix.outputs.matrix }}
@@ -40,9 +40,9 @@
id: create_matrix
with:
matrix: |
- network {opal}, runtime {opal}, features {opal-runtime}
- network {quartz}, runtime {quartz}, features {quartz-runtime}
- network {unique}, runtime {unique}, features {unique-runtime}
+ network {opal}, runtime {opal}, features {opal-runtime}, acala_version {${{ env.ACALA_BUILD_BRANCH }}}, moonbeam_version {${{ env.MOONBEAM_BUILD_BRANCH }}}, cumulus_version {${{ env.WESTMINT_BUILD_BRANCH }}}
+ network {quartz}, runtime {quartz}, features {quartz-runtime}, acala_version {${{ env.KARURA_BUILD_BRANCH }}}, moonbeam_version {${{ env.MOONRIVER_BUILD_BRANCH }}}, cumulus_version {${{ env.STATEMINE_BUILD_BRANCH }}}
+ network {unique}, runtime {unique}, features {unique-runtime}, acala_version {${{ env.ACALA_BUILD_BRANCH }}}, moonbeam_version {${{ env.MOONBEAM_BUILD_BRANCH }}}, cumulus_version {${{ env.STATEMINT_BUILD_BRANCH }}}
xcm-build:
@@ -89,9 +89,9 @@
FEATURE=${{ matrix.features }}
RUNTIME=${{ matrix.runtime }}
BRANCH=${{ github.head_ref }}
- ACALA_BUILD_BRANCH=${{ env.ACALA_BUILD_BRANCH }}
- MOONBEAM_BUILD_BRANCH=${{ env.MOONBEAM_BUILD_BRANCH }}
- CUMULUS_BUILD_BRANCH=${{ env.CUMULUS_BUILD_BRANCH }}
+ ACALA_BUILD_BRANCH=${{ matrix.acala_version }}
+ MOONBEAM_BUILD_BRANCH=${{ matrix.moonbeam_version }}
+ CUMULUS_BUILD_BRANCH=${{ matrix.cumulus_version }}
- name: Show build Dockerfile
run: cat .docker/Dockerfile-xcm.${{ matrix.network }}.yml
@@ -114,13 +114,13 @@
password: ${{ secrets.CORE_DOCKERHUB_TOKEN }}
- name: Pull acala docker image
- run: docker pull uniquenetwork/builder-acala:${{ env.ACALA_BUILD_BRANCH }}
+ run: docker pull uniquenetwork/builder-acala:${{ matrix.acala_version }}
- name: Pull moonbeam docker image
- run: docker pull uniquenetwork/builder-moonbeam:${{ env.MOONBEAM_BUILD_BRANCH }}
+ run: docker pull uniquenetwork/builder-moonbeam:${{ matrix.moonbeam_version }}
- name: Pull cumulus docker image
- run: docker pull uniquenetwork/builder-cumulus:${{ env.CUMULUS_BUILD_BRANCH }}
+ run: docker pull uniquenetwork/builder-cumulus:${{ matrix.cumulus_version }}
- name: Pull polkadot docker image
run: docker pull uniquenetwork/builder-polkadot:${{ env.POLKADOT_BUILD_BRANCH }}
.github/workflows/xcm-tests_v2.ymldiffbeforeafterboth--- a/.github/workflows/xcm-tests_v2.yml
+++ b/.github/workflows/xcm-tests_v2.yml
@@ -146,6 +146,7 @@
run: |
yarn install
yarn add mochawesome
+ node scripts/readyness.js
echo "Ready to start tests"
NOW=$(date +%s) && yarn ${{ matrix.runtest }} --reporter mochawesome --reporter-options reportFilename=test-${NOW}
node/cli/Cargo.tomldiffbeforeafterboth--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -302,7 +302,7 @@
[dependencies]
futures = '0.3.17'
-log = '0.4.14'
+log = '0.4.16'
flexi_logger = "0.22.5"
parking_lot = '0.12.1'
clap = "3.1.2"
pallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-contract-helpers/Cargo.toml
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -8,7 +8,7 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
-log = { default-features = false, version = "0.4.14" }
+log = { default-features = false, version = "0.4.16" }
# Substrate
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
pallets/foreing-assets/Cargo.tomldiffbeforeafterboth--- a/pallets/foreing-assets/Cargo.toml
+++ b/pallets/foreing-assets/Cargo.toml
@@ -5,7 +5,7 @@
edition = "2021"
[dependencies]
-log = { version = "0.4.14", default-features = false }
+log = { version = "0.4.16", default-features = false }
serde = { version = "1.0.136", optional = true }
scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false }
pallets/scheduler/Cargo.tomldiffbeforeafterboth--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -25,7 +25,7 @@
frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.27" }
-log = { version = "0.4.14", default-features = false }
+log = { version = "0.4.16", default-features = false }
[dev-dependencies]
sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
runtime/common/construct_runtime/mod.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -42,7 +42,7 @@
Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,
Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,
Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,
- #[runtimes(opal)]
+
XTokens: orml_xtokens = 38,
Tokens: orml_tokens = 39,
// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,
runtime/opal/src/xcm_config.rsdiffbeforeafterboth--- a/runtime/opal/src/xcm_config.rs
+++ b/runtime/opal/src/xcm_config.rs
@@ -498,7 +498,7 @@
impl orml_xtokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
- type CurrencyId = AssetIds;
+ type CurrencyId = CurrencyId;
type CurrencyIdConvert = CurrencyIdConvert;
type AccountIdToMultiLocation = AccountIdToMultiLocation;
type SelfLocation = SelfLocation;
runtime/quartz/src/xcm_config.rsdiffbeforeafterboth--- a/runtime/quartz/src/xcm_config.rs
+++ b/runtime/quartz/src/xcm_config.rs
@@ -180,11 +180,10 @@
type OnKilledTokenAccount = ();
}
-/*
impl orml_xtokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
- type CurrencyId = AssetIds;
+ type CurrencyId = CurrencyId;
type CurrencyIdConvert = CurrencyIdConvert;
type AccountIdToMultiLocation = AccountIdToMultiLocation;
type SelfLocation = SelfLocation;
@@ -197,8 +196,8 @@
type MultiLocationsFilter = Everything;
type ReserveProvider = AbsoluteReserveProvider;
}
- */
+
parameter_type_with_key! {
pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance {
match currency_id {
@@ -218,7 +217,7 @@
}
}
-/*
+
pub struct CurrencyIdConvert;
impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
fn convert(id: AssetIds) -> Option<MultiLocation> {
@@ -228,12 +227,11 @@
X1(Parachain(ParachainInfo::get().into())),
)),
AssetIds::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
- AssetIds::ForeignAssetId(foreign_asset_id) => {
- XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)
- }
+ AssetIds::ForeignAssetId(_) => None,
}
}
}
+/*
impl Convert<MultiLocation, Option<CurrencyId>> for CurrencyIdConvert {
fn convert(location: MultiLocation) -> Option<CurrencyId> {
if location == MultiLocation::here()
runtime/unique/src/xcm_config.rsdiffbeforeafterboth--- a/runtime/unique/src/xcm_config.rs
+++ b/runtime/unique/src/xcm_config.rs
@@ -88,6 +88,8 @@
MultiLocation { parents: 1, interior: Here },
// Karura/Acala location
MultiLocation { parents: 1, interior: X1(Parachain(2000)) },
+ // Moonbeam location
+ MultiLocation { parents: 1, interior: X1(Parachain(2004)) },
// Self parachain address
MultiLocation { parents: 1, interior: X1(Parachain(ParachainInfo::get().into())) },
]
@@ -201,10 +203,42 @@
type OnKilledTokenAccount = ();
}
+impl orml_xtokens::Config for Runtime {
+ type Event = Event;
+ type Balance = Balance;
+ type CurrencyId = CurrencyId;
+ type CurrencyIdConvert = CurrencyIdConvert;
+ type AccountIdToMultiLocation = AccountIdToMultiLocation;
+ type SelfLocation = SelfLocation;
+ type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
+ type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
+ type BaseXcmWeight = BaseXcmWeight;
+ type LocationInverter = LocationInverter<Ancestry>;
+ type MaxAssetsForTransfer = MaxAssetsForTransfer;
+ type MinXcmFee = ParachainMinFee;
+ type MultiLocationsFilter = Everything;
+ type ReserveProvider = AbsoluteReserveProvider;
+}
+
+pub struct CurrencyIdConvert;
+impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
+ fn convert(id: AssetIds) -> Option<MultiLocation> {
+ match id {
+ AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
+ 1,
+ X1(Parachain(ParachainInfo::get().into())),
+ )),
+ _ => None,
+ }
+ }
+}
parameter_types! {
pub const BaseXcmWeight: Weight = 100_000_000; // TODO: recheck this
pub const MaxAssetsForTransfer: usize = 2;
+
+ pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
+ pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
}
parameter_type_with_key! {
@@ -223,4 +257,4 @@
})
.into()
}
-}
\ No newline at end of file
+}
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -74,11 +74,12 @@
"testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.test.ts",
"testScheduler": "mocha --timeout 9999999 -r ts-node/register ./**/scheduler.test.ts",
"testSchedulingEVM": "mocha --timeout 9999999 -r ts-node/register ./**/eth/scheduling.test.ts",
- "testXcmUnique": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmUnique.test.ts",
+ "testXcmUnique": "RUN_XCM_TESTS=1 mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmUnique.test.ts",
+ "testXcmQuartz": "RUN_XCM_TESTS=1 mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmQuartz.test.ts",
"testXcmOpal": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmOpal.test.ts",
"testXcmTransferAcala": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmTransferAcala.test.ts acalaId=2000 uniqueId=5000",
"testXcmTransferStatemine": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmTransferStatemine.test.ts statemineId=1000 uniqueId=5000",
- "testXcmTransferMoonbeam": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmTransferMoonbeam.test.ts moonbeamId=2000 uniqueId=5000",
+ "testXcmTransferMoonbeam": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmTransferMoonbeam.test.ts",
"testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
"testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
"testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",
tests/scripts/readyness.jsdiffbeforeafterboth--- a/tests/scripts/readyness.js
+++ b/tests/scripts/readyness.js
@@ -6,9 +6,9 @@
await api.isReadyOrError;
const head = (await api.rpc.chain.getHeader()).number.toNumber();
+ await api.disconnect();
if(head < 1) throw Error('No block #1');
- await api.disconnect();
}
const sleep = time => {
tests/src/substrate/substrate-api.tsdiffbeforeafterboth--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -85,7 +85,7 @@
for (const arg of args) {
if (typeof arg !== 'string')
continue;
- if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))
+ if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
return;
}
printer(...args);
@@ -169,13 +169,24 @@
/* eslint no-async-promise-executor: "off" */
return new Promise(async (resolve, reject) => {
try {
- await transaction.signAndSend(sender, ({events = [], status}) => {
+ await transaction.signAndSend(sender, ({events = [], status, dispatchError}) => {
const transactionStatus = getTransactionStatus(events, status);
if (transactionStatus === TransactionStatus.Success) {
resolve(events);
} else if (transactionStatus === TransactionStatus.Fail) {
- console.log(`Something went wrong with transaction. Status: ${status}`);
+ let moduleError = null;
+
+ if (dispatchError) {
+ if (dispatchError.isModule) {
+ const modErr = dispatchError.asModule;
+ const errorMeta = dispatchError.registry.findMetaError(modErr);
+
+ moduleError = JSON.stringify(errorMeta, null, 4);
+ }
+ }
+
+ console.log(`Something went wrong with transaction. Status: ${status}\nModule error: ${moduleError}`);
reject(events);
}
});
tests/src/util/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} 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 BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';31import {Context} from 'mocha';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37 Substrate: string,38} | {39 Ethereum: string,40};414243export enum Pallets {44 Inflation = 'inflation',45 RmrkCore = 'rmrkcore',46 RmrkEquip = 'rmrkequip',47 ReFungible = 'refungible',48 Fungible = 'fungible',49 NFT = 'nonfungible',50 Scheduler = 'scheduler',51}5253export async function isUnique(): Promise<boolean> {54 return usingApi(async api => {55 const chain = await api.rpc.system.chain();5657 return chain.eq('UNIQUE');58 });59}6061export async function isQuartz(): Promise<boolean> {62 return usingApi(async api => {63 const chain = await api.rpc.system.chain();64 65 return chain.eq('QUARTZ');66 });67}6869let modulesNames: any;70export function getModuleNames(api: ApiPromise): string[] {71 if (typeof modulesNames === 'undefined') 72 modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());73 return modulesNames;74}7576export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {77 return await usingApi(async api => {78 const pallets = getModuleNames(api);7980 return requiredPallets.filter(p => !pallets.includes(p));81 });82}8384export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {85 return (await missingRequiredPallets(requiredPallets)).length == 0;86}8788export async function requirePallets(mocha: Context, requiredPallets: string[]) {89 const missingPallets = await missingRequiredPallets(requiredPallets);9091 if (missingPallets.length > 0) {92 const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;93 const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;94 const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9596 console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9798 mocha.skip();99 }100}101102export function bigIntToSub(api: ApiPromise, number: bigint) {103 return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();104}105106export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {107 if (typeof input === 'string') {108 if (input.length >= 47) {109 return {Substrate: input};110 } else if (input.length === 42 && input.startsWith('0x')) {111 return {Ethereum: input.toLowerCase()};112 } else if (input.length === 40 && !input.startsWith('0x')) {113 return {Ethereum: '0x' + input.toLowerCase()};114 } else {115 throw new Error(`Unknown address format: "${input}"`);116 }117 }118 if ('address' in input) {119 return {Substrate: input.address};120 }121 if ('Ethereum' in input) {122 return {123 Ethereum: input.Ethereum.toLowerCase(),124 };125 } else if ('ethereum' in input) {126 return {127 Ethereum: (input as any).ethereum.toLowerCase(),128 };129 } else if ('Substrate' in input) {130 return input;131 } else if ('substrate' in input) {132 return {133 Substrate: (input as any).substrate,134 };135 }136137 // AccountId138 return {Substrate: input.toString()};139}140export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {141 input = normalizeAccountId(input);142 if ('Substrate' in input) {143 return input.Substrate;144 } else {145 return evmToAddress(input.Ethereum);146 }147}148149export const U128_MAX = (1n << 128n) - 1n;150151const MICROUNIQUE = 1_000_000_000_000n;152const MILLIUNIQUE = 1_000n * MICROUNIQUE;153const CENTIUNIQUE = 10n * MILLIUNIQUE;154export const UNIQUE = 100n * CENTIUNIQUE;155156interface GenericResult<T> {157 success: boolean;158 data: T | null;159}160161interface CreateCollectionResult {162 success: boolean;163 collectionId: number;164}165166interface CreateItemResult {167 success: boolean;168 collectionId: number;169 itemId: number;170 recipient?: CrossAccountId;171 amount?: number;172}173174interface DestroyItemResult {175 success: boolean;176 collectionId: number;177 itemId: number;178 owner: CrossAccountId;179 amount: number;180}181182interface TransferResult {183 collectionId: number;184 itemId: number;185 sender?: CrossAccountId;186 recipient?: CrossAccountId;187 value: bigint;188}189190interface IReFungibleOwner {191 fraction: BN;192 owner: number[];193}194195interface IGetMessage {196 checkMsgUnqMethod: string;197 checkMsgTrsMethod: string;198 checkMsgSysMethod: string;199}200201export interface IFungibleTokenDataType {202 value: number;203}204205export interface IChainLimits {206 collectionNumbersLimit: number;207 accountTokenOwnershipLimit: number;208 collectionsAdminsLimit: number;209 customDataLimit: number;210 nftSponsorTransferTimeout: number;211 fungibleSponsorTransferTimeout: number;212 refungibleSponsorTransferTimeout: number;213 //offchainSchemaLimit: number;214 //constOnChainSchemaLimit: number;215}216217export interface IReFungibleTokenDataType {218 owner: IReFungibleOwner[];219}220221export function uniqueEventMessage(events: EventRecord[]): IGetMessage {222 let checkMsgUnqMethod = '';223 let checkMsgTrsMethod = '';224 let checkMsgSysMethod = '';225 events.forEach(({event: {method, section}}) => {226 if (section === 'common') {227 checkMsgUnqMethod = method;228 } else if (section === 'treasury') {229 checkMsgTrsMethod = method;230 } else if (section === 'system') {231 checkMsgSysMethod = method;232 } else { return null; }233 });234 const result: IGetMessage = {235 checkMsgUnqMethod,236 checkMsgTrsMethod,237 checkMsgSysMethod,238 };239 return result;240}241242export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {243 const event = events.find(r => check(r.event));244 if (!event) return;245 return event.event as T;246}247248export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;249export function getGenericResult<T>(250 events: EventRecord[],251 expectSection: string,252 expectMethod: string,253 extractAction: (data: GenericEventData) => T254): GenericResult<T>;255256export function getGenericResult<T>(257 events: EventRecord[],258 expectSection?: string,259 expectMethod?: string,260 extractAction?: (data: GenericEventData) => T,261): GenericResult<T> {262 let success = false;263 let successData = null;264265 events.forEach(({event: {data, method, section}}) => {266 // console.log(` ${phase}: ${section}.${method}:: ${data}`);267 if (method === 'ExtrinsicSuccess') {268 success = true;269 } else if ((expectSection == section) && (expectMethod == method)) {270 successData = extractAction!(data as any);271 }272 });273274 const result: GenericResult<T> = {275 success,276 data: successData,277 };278 return result;279}280281export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {282 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));283 const result: CreateCollectionResult = {284 success: genericResult.success,285 collectionId: genericResult.data ?? 0,286 };287 return result;288}289290export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {291 const results: CreateItemResult[] = [];292 293 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {294 const collectionId = parseInt(data[0].toString(), 10);295 const itemId = parseInt(data[1].toString(), 10);296 const recipient = normalizeAccountId(data[2].toJSON() as any);297 const amount = parseInt(data[3].toString(), 10);298299 const itemRes: CreateItemResult = {300 success: true,301 collectionId,302 itemId,303 recipient,304 amount,305 };306307 results.push(itemRes);308 return results;309 });310311 if (!genericResult.success) return [];312 return results;313}314315export function getCreateItemResult(events: EventRecord[]): CreateItemResult {316 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));317 318 if (genericResult.data == null) 319 return {320 success: genericResult.success,321 collectionId: 0,322 itemId: 0,323 amount: 0,324 };325 else 326 return {327 success: genericResult.success,328 collectionId: genericResult.data[0] as number,329 itemId: genericResult.data[1] as number,330 recipient: normalizeAccountId(genericResult.data![2] as any),331 amount: genericResult.data[3] as number,332 };333}334335export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {336 const results: DestroyItemResult[] = [];337 338 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {339 const collectionId = parseInt(data[0].toString(), 10);340 const itemId = parseInt(data[1].toString(), 10);341 const owner = normalizeAccountId(data[2].toJSON() as any);342 const amount = parseInt(data[3].toString(), 10);343344 const itemRes: DestroyItemResult = {345 success: true,346 collectionId,347 itemId,348 owner,349 amount,350 };351352 results.push(itemRes);353 return results;354 });355356 if (!genericResult.success) return [];357 return results;358}359360export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {361 for (const {event} of events) {362 if (api.events.common.Transfer.is(event)) {363 const [collection, token, sender, recipient, value] = event.data;364 return {365 collectionId: collection.toNumber(),366 itemId: token.toNumber(),367 sender: normalizeAccountId(sender.toJSON() as any),368 recipient: normalizeAccountId(recipient.toJSON() as any),369 value: value.toBigInt(),370 };371 }372 }373 throw new Error('no transfer event');374}375376interface Nft {377 type: 'NFT';378}379380interface Fungible {381 type: 'Fungible';382 decimalPoints: number;383}384385interface ReFungible {386 type: 'ReFungible';387}388389export type CollectionMode = Nft | Fungible | ReFungible;390391export type Property = {392 key: any,393 value: any,394};395396type Permission = {397 mutable: boolean;398 collectionAdmin: boolean;399 tokenOwner: boolean;400}401402type PropertyPermission = {403 key: any;404 permission: Permission;405}406407export type CreateCollectionParams = {408 mode: CollectionMode,409 name: string,410 description: string,411 tokenPrefix: string,412 properties?: Array<Property>,413 propPerm?: Array<PropertyPermission>414};415416const defaultCreateCollectionParams: CreateCollectionParams = {417 description: 'description',418 mode: {type: 'NFT'},419 name: 'name',420 tokenPrefix: 'prefix',421};422423export async function424createCollection(425 api: ApiPromise,426 sender: IKeyringPair,427 params: Partial<CreateCollectionParams> = {},428): Promise<CreateCollectionResult> {429 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};430431 let modeprm = {};432 if (mode.type === 'NFT') {433 modeprm = {nft: null};434 } else if (mode.type === 'Fungible') {435 modeprm = {fungible: mode.decimalPoints};436 } else if (mode.type === 'ReFungible') {437 modeprm = {refungible: null};438 }439440 const tx = api.tx.unique.createCollectionEx({441 name: strToUTF16(name),442 description: strToUTF16(description),443 tokenPrefix: strToUTF16(tokenPrefix),444 mode: modeprm as any,445 });446 const events = await executeTransaction(api, sender, tx);447 return getCreateCollectionResult(events);448}449450export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {451 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};452453 let collectionId = 0;454 await usingApi(async (api, privateKeyWrapper) => {455 // Get number of collections before the transaction456 const collectionCountBefore = await getCreatedCollectionCount(api);457458 // Run the CreateCollection transaction459 const alicePrivateKey = privateKeyWrapper('//Alice');460461 const result = await createCollection(api, alicePrivateKey, params);462463 // Get number of collections after the transaction464 const collectionCountAfter = await getCreatedCollectionCount(api);465466 // Get the collection467 const collection = await queryCollectionExpectSuccess(api, result.collectionId);468469 // What to expect470 // tslint:disable-next-line:no-unused-expression471 expect(result.success).to.be.true;472 expect(result.collectionId).to.be.equal(collectionCountAfter);473 // tslint:disable-next-line:no-unused-expression474 expect(collection).to.be.not.null;475 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');476 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));477 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);478 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);479 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);480481 collectionId = result.collectionId;482 });483484 return collectionId;485}486487export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {488 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};489490 let collectionId = 0;491 await usingApi(async (api, privateKeyWrapper) => {492 // Get number of collections before the transaction493 const collectionCountBefore = await getCreatedCollectionCount(api);494495 // Run the CreateCollection transaction496 const alicePrivateKey = privateKeyWrapper('//Alice');497498 let modeprm = {};499 if (mode.type === 'NFT') {500 modeprm = {nft: null};501 } else if (mode.type === 'Fungible') {502 modeprm = {fungible: mode.decimalPoints};503 } else if (mode.type === 'ReFungible') {504 modeprm = {refungible: null};505 }506507 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});508 const events = await submitTransactionAsync(alicePrivateKey, tx);509 const result = getCreateCollectionResult(events);510511 // Get number of collections after the transaction512 const collectionCountAfter = await getCreatedCollectionCount(api);513514 // Get the collection515 const collection = await queryCollectionExpectSuccess(api, result.collectionId);516517 // What to expect518 // tslint:disable-next-line:no-unused-expression519 expect(result.success).to.be.true;520 expect(result.collectionId).to.be.equal(collectionCountAfter);521 // tslint:disable-next-line:no-unused-expression522 expect(collection).to.be.not.null;523 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');524 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));525 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);526 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);527 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);528529530 collectionId = result.collectionId;531 });532533 return collectionId;534}535536export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {537 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};538539 await usingApi(async (api, privateKeyWrapper) => {540 // Get number of collections before the transaction541 const collectionCountBefore = await getCreatedCollectionCount(api);542543 // Run the CreateCollection transaction544 const alicePrivateKey = privateKeyWrapper('//Alice');545546 let modeprm = {};547 if (mode.type === 'NFT') {548 modeprm = {nft: null};549 } else if (mode.type === 'Fungible') {550 modeprm = {fungible: mode.decimalPoints};551 } else if (mode.type === 'ReFungible') {552 modeprm = {refungible: null};553 }554555 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});556 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;557558559 // Get number of collections after the transaction560 const collectionCountAfter = await getCreatedCollectionCount(api);561562 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');563 });564}565566export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {567 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};568569 let modeprm = {};570 if (mode.type === 'NFT') {571 modeprm = {nft: null};572 } else if (mode.type === 'Fungible') {573 modeprm = {fungible: mode.decimalPoints};574 } else if (mode.type === 'ReFungible') {575 modeprm = {refungible: null};576 }577578 await usingApi(async (api, privateKeyWrapper) => {579 // Get number of collections before the transaction580 const collectionCountBefore = await getCreatedCollectionCount(api);581582 // Run the CreateCollection transaction583 const alicePrivateKey = privateKeyWrapper('//Alice');584 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});585 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;586587 // Get number of collections after the transaction588 const collectionCountAfter = await getCreatedCollectionCount(api);589590 // What to expect591 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');592 });593}594595export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {596 let bal = 0n;597 let unused;598 do {599 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;600 unused = privateKeyWrapper(`//${randomSeed}`);601 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();602 } while (bal !== 0n);603 return unused;604}605606export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {607 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();608}609610export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {611 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));612}613614export async function findNotExistingCollection(api: ApiPromise): Promise<number> {615 const totalNumber = await getCreatedCollectionCount(api);616 const newCollection: number = totalNumber + 1;617 return newCollection;618}619620function getDestroyResult(events: EventRecord[]): boolean {621 let success = false;622 events.forEach(({event: {method}}) => {623 if (method == 'ExtrinsicSuccess') {624 success = true;625 }626 });627 return success;628}629630export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {631 await usingApi(async (api, privateKeyWrapper) => {632 // Run the DestroyCollection transaction633 const alicePrivateKey = privateKeyWrapper(senderSeed);634 const tx = api.tx.unique.destroyCollection(collectionId);635 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;636 });637}638639export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {640 await usingApi(async (api, privateKeyWrapper) => {641 // Run the DestroyCollection transaction642 const alicePrivateKey = privateKeyWrapper(senderSeed);643 const tx = api.tx.unique.destroyCollection(collectionId);644 const events = await submitTransactionAsync(alicePrivateKey, tx);645 const result = getDestroyResult(events);646 expect(result).to.be.true;647648 // What to expect649 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;650 });651}652653export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {654 await usingApi(async (api) => {655 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);656 const events = await submitTransactionAsync(sender, tx);657 const result = getGenericResult(events);658659 expect(result.success).to.be.true;660 });661}662663export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {664 await usingApi(async(api) => {665 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);666 const events = await submitTransactionAsync(sender, tx);667 const result = getGenericResult(events);668669 expect(result.success).to.be.true;670 });671};672673export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {674 await usingApi(async (api) => {675 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);676 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;677 const result = getGenericResult(events);678679 expect(result.success).to.be.false;680 });681}682683export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {684 await usingApi(async (api, privateKeyWrapper) => {685686 // Run the transaction687 const senderPrivateKey = privateKeyWrapper(sender);688 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);689 const events = await submitTransactionAsync(senderPrivateKey, tx);690 const result = getGenericResult(events);691692 // Get the collection693 const collection = await queryCollectionExpectSuccess(api, collectionId);694695 // What to expect696 expect(result.success).to.be.true;697 expect(collection.sponsorship.toJSON()).to.deep.equal({698 unconfirmed: sponsor,699 });700 });701}702703export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {704 await usingApi(async (api, privateKeyWrapper) => {705706 // Run the transaction707 const alicePrivateKey = privateKeyWrapper(sender);708 const tx = api.tx.unique.removeCollectionSponsor(collectionId);709 const events = await submitTransactionAsync(alicePrivateKey, tx);710 const result = getGenericResult(events);711712 // Get the collection713 const collection = await queryCollectionExpectSuccess(api, collectionId);714715 // What to expect716 expect(result.success).to.be.true;717 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});718 });719}720721export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {722 await usingApi(async (api, privateKeyWrapper) => {723724 // Run the transaction725 const alicePrivateKey = privateKeyWrapper(senderSeed);726 const tx = api.tx.unique.removeCollectionSponsor(collectionId);727 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;728 });729}730731export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {732 await usingApi(async (api, privateKeyWrapper) => {733734 // Run the transaction735 const alicePrivateKey = privateKeyWrapper(senderSeed);736 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);737 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;738 });739}740741export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {742 await usingApi(async (api, privateKeyWrapper) => {743744 // Run the transaction745 const sender = privateKeyWrapper(senderSeed);746 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);747 });748}749750export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {751 await usingApi(async (api, privateKeyWrapper) => {752753 // Run the transaction754 const tx = api.tx.unique.confirmSponsorship(collectionId);755 const events = await submitTransactionAsync(sender, tx);756 const result = getGenericResult(events);757758 // Get the collection759 const collection = await queryCollectionExpectSuccess(api, collectionId);760761 // What to expect762 expect(result.success).to.be.true;763 expect(collection.sponsorship.toJSON()).to.be.deep.equal({764 confirmed: sender.address,765 });766 });767}768769770export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {771 await usingApi(async (api, privateKeyWrapper) => {772773 // Run the transaction774 const sender = privateKeyWrapper(senderSeed);775 const tx = api.tx.unique.confirmSponsorship(collectionId);776 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;777 });778}779780export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {781 await usingApi(async (api) => {782 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);783 const events = await submitTransactionAsync(sender, tx);784 const result = getGenericResult(events);785786 expect(result.success).to.be.true;787 });788}789790export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {791 await usingApi(async (api) => {792 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);793 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;794 const result = getGenericResult(events);795796 expect(result.success).to.be.false;797 });798}799800export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {801802 await usingApi(async (api) => {803804 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);805 const events = await submitTransactionAsync(sender, tx);806 const result = getGenericResult(events);807808 expect(result.success).to.be.true;809 });810}811812export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {813814 await usingApi(async (api) => {815816 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);817 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;818 const result = getGenericResult(events);819820 expect(result.success).to.be.false;821 });822}823824export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {825 await usingApi(async (api) => {826 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);827 const events = await submitTransactionAsync(sender, tx);828 const result = getGenericResult(events);829830 expect(result.success).to.be.true;831 });832}833834export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {835 await usingApi(async (api) => {836 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);837 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;838 const result = getGenericResult(events);839840 expect(result.success).to.be.false;841 });842}843844export async function getNextSponsored(845 api: ApiPromise,846 collectionId: number,847 account: string | CrossAccountId,848 tokenId: number,849): Promise<number> {850 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));851}852853export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {854 await usingApi(async (api) => {855 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);856 const events = await submitTransactionAsync(sender, tx);857 const result = getGenericResult(events);858859 expect(result.success).to.be.true;860 });861}862863export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {864 let allowlisted = false;865 await usingApi(async (api) => {866 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;867 });868 return allowlisted;869}870871export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {872 await usingApi(async (api) => {873 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());874 const events = await submitTransactionAsync(sender, tx);875 const result = getGenericResult(events);876877 expect(result.success).to.be.true;878 });879}880881export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {882 await usingApi(async (api) => {883 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());884 const events = await submitTransactionAsync(sender, tx);885 const result = getGenericResult(events);886887 expect(result.success).to.be.true;888 });889}890891export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {892 await usingApi(async (api) => {893 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());894 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;895 const result = getGenericResult(events);896897 expect(result.success).to.be.false;898 });899}900901export interface CreateFungibleData {902 readonly Value: bigint;903}904905export interface CreateReFungibleData { }906export interface CreateNftData { }907908export type CreateItemData = {909 NFT: CreateNftData;910} | {911 Fungible: CreateFungibleData;912} | {913 ReFungible: CreateReFungibleData;914};915916export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {917 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);918 const events = await submitTransactionAsync(sender, tx);919 return getGenericResult(events).success;920}921922export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {923 await usingApi(async (api) => {924 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);925 // if burning token by admin - use adminButnItemExpectSuccess926 expect(balanceBefore >= BigInt(value)).to.be.true;927928 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;929930 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);931 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);932 });933}934935export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {936 await usingApi(async (api) => {937 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);938939 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;940 const result = getCreateCollectionResult(events);941 // tslint:disable-next-line:no-unused-expression942 expect(result.success).to.be.false;943 });944}945946export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {947 await usingApi(async (api) => {948 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);949 const events = await submitTransactionAsync(sender, tx);950 return getGenericResult(events).success;951 });952}953954export async function955approve(956 api: ApiPromise,957 collectionId: number,958 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,959) {960 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);961 const events = await submitTransactionAsync(owner, approveUniqueTx);962 return getGenericResult(events).success;963}964965export async function966approveExpectSuccess(967 collectionId: number,968 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,969) {970 await usingApi(async (api: ApiPromise) => {971 const result = await approve(api, collectionId, tokenId, owner, approved, amount);972 expect(result).to.be.true;973974 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));975 });976}977978export async function adminApproveFromExpectSuccess(979 collectionId: number,980 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,981) {982 await usingApi(async (api: ApiPromise) => {983 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);984 const events = await submitTransactionAsync(admin, approveUniqueTx);985 const result = getGenericResult(events);986 expect(result.success).to.be.true;987988 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));989 });990}991992export async function993transferFrom(994 api: ApiPromise,995 collectionId: number,996 tokenId: number,997 accountApproved: IKeyringPair,998 accountFrom: IKeyringPair | CrossAccountId,999 accountTo: IKeyringPair | CrossAccountId,1000 value: number | bigint,1001) {1002 const from = normalizeAccountId(accountFrom);1003 const to = normalizeAccountId(accountTo);1004 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1005 const events = await submitTransactionAsync(accountApproved, transferFromTx);1006 return getGenericResult(events).success;1007}10081009export async function1010transferFromExpectSuccess(1011 collectionId: number,1012 tokenId: number,1013 accountApproved: IKeyringPair,1014 accountFrom: IKeyringPair | CrossAccountId,1015 accountTo: IKeyringPair | CrossAccountId,1016 value: number | bigint = 1,1017 type = 'NFT',1018) {1019 await usingApi(async (api: ApiPromise) => {1020 const from = normalizeAccountId(accountFrom);1021 const to = normalizeAccountId(accountTo);1022 let balanceBefore = 0n;1023 if (type === 'Fungible' || type === 'ReFungible') {1024 balanceBefore = await getBalance(api, collectionId, to, tokenId);1025 }1026 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1027 if (type === 'NFT') {1028 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1029 }1030 if (type === 'Fungible') {1031 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1032 if (JSON.stringify(to) !== JSON.stringify(from)) {1033 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1034 } else {1035 expect(balanceAfter).to.be.equal(balanceBefore);1036 }1037 }1038 if (type === 'ReFungible') {1039 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1040 }1041 });1042}10431044export async function1045transferFromExpectFail(1046 collectionId: number,1047 tokenId: number,1048 accountApproved: IKeyringPair,1049 accountFrom: IKeyringPair,1050 accountTo: IKeyringPair,1051 value: number | bigint = 1,1052) {1053 await usingApi(async (api: ApiPromise) => {1054 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1055 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1056 const result = getCreateCollectionResult(events);1057 // tslint:disable-next-line:no-unused-expression1058 expect(result.success).to.be.false;1059 });1060}10611062/* eslint no-async-promise-executor: "off" */1063export async function getBlockNumber(api: ApiPromise): Promise<number> {1064 return new Promise<number>(async (resolve) => {1065 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1066 unsubscribe();1067 resolve(head.number.toNumber());1068 });1069 });1070}10711072export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1073 await usingApi(async (api) => {1074 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1075 const events = await submitTransactionAsync(sender, changeAdminTx);1076 const result = getCreateCollectionResult(events);1077 expect(result.success).to.be.true;1078 });1079}10801081export async function adminApproveFromExpectFail(1082 collectionId: number,1083 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1084) {1085 await usingApi(async (api: ApiPromise) => {1086 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1087 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1088 const result = getGenericResult(events);1089 expect(result.success).to.be.false;1090 });1091}10921093export async function1094getFreeBalance(account: IKeyringPair): Promise<bigint> {1095 let balance = 0n;1096 await usingApi(async (api) => {1097 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1098 });10991100 return balance;1101}11021103export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1104 return usingApi(async api => {1105 const siblingPrefix = '0x7369626c';1106 const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1107 const suffix = '000000000000000000000000000000000000000000000000';11081109 return siblingPrefix + encodedParaId + suffix;1110 });1111}11121113export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1114 const tx = api.tx.balances.transfer(target, amount);1115 const events = await submitTransactionAsync(source, tx);1116 const result = getGenericResult(events);1117 expect(result.success).to.be.true;1118}11191120export async function1121scheduleExpectSuccess(1122 operationTx: any,1123 sender: IKeyringPair,1124 blockSchedule: number,1125 scheduledId: string,1126 period = 1,1127 repetitions = 1,1128) {1129 await usingApi(async (api: ApiPromise) => {1130 const blockNumber: number | undefined = await getBlockNumber(api);1131 const expectedBlockNumber = blockNumber + blockSchedule;11321133 expect(blockNumber).to.be.greaterThan(0);1134 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1135 scheduledId,1136 expectedBlockNumber, 1137 repetitions > 1 ? [period, repetitions] : null, 1138 0, 1139 {Value: operationTx as any},1140 );11411142 const events = await submitTransactionAsync(sender, scheduleTx);1143 expect(getGenericResult(events).success).to.be.true;1144 });1145}11461147export async function1148scheduleExpectFailure(1149 operationTx: any,1150 sender: IKeyringPair,1151 blockSchedule: number,1152 scheduledId: string,1153 period = 1,1154 repetitions = 1,1155) {1156 await usingApi(async (api: ApiPromise) => {1157 const blockNumber: number | undefined = await getBlockNumber(api);1158 const expectedBlockNumber = blockNumber + blockSchedule;11591160 expect(blockNumber).to.be.greaterThan(0);1161 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1162 scheduledId,1163 expectedBlockNumber, 1164 repetitions <= 1 ? null : [period, repetitions], 1165 0, 1166 {Value: operationTx as any},1167 );11681169 //const events = 1170 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1171 //expect(getGenericResult(events).success).to.be.false;1172 });1173}11741175export async function1176scheduleTransferAndWaitExpectSuccess(1177 collectionId: number,1178 tokenId: number,1179 sender: IKeyringPair,1180 recipient: IKeyringPair,1181 value: number | bigint = 1,1182 blockSchedule: number,1183 scheduledId: string,1184) {1185 await usingApi(async (api: ApiPromise) => {1186 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11871188 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11891190 // sleep for n + 1 blocks1191 await waitNewBlocks(blockSchedule + 1);11921193 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11941195 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1196 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1197 });1198}11991200export async function1201scheduleTransferExpectSuccess(1202 collectionId: number,1203 tokenId: number,1204 sender: IKeyringPair,1205 recipient: IKeyringPair,1206 value: number | bigint = 1,1207 blockSchedule: number,1208 scheduledId: string,1209) {1210 await usingApi(async (api: ApiPromise) => {1211 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12121213 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12141215 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1216 });1217}12181219export async function1220scheduleTransferFundsPeriodicExpectSuccess(1221 amount: bigint,1222 sender: IKeyringPair,1223 recipient: IKeyringPair,1224 blockSchedule: number,1225 scheduledId: string,1226 period: number,1227 repetitions: number,1228) {1229 await usingApi(async (api: ApiPromise) => {1230 const transferTx = api.tx.balances.transfer(recipient.address, amount);12311232 const balanceBefore = await getFreeBalance(recipient);1233 1234 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12351236 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1237 });1238}12391240export async function1241transfer(1242 api: ApiPromise,1243 collectionId: number,1244 tokenId: number,1245 sender: IKeyringPair,1246 recipient: IKeyringPair | CrossAccountId,1247 value: number | bigint,1248) : Promise<boolean> {1249 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1250 const events = await executeTransaction(api, sender, transferTx);1251 return getGenericResult(events).success;1252}12531254export async function1255transferExpectSuccess(1256 collectionId: number,1257 tokenId: number,1258 sender: IKeyringPair,1259 recipient: IKeyringPair | CrossAccountId,1260 value: number | bigint = 1,1261 type = 'NFT',1262) {1263 await usingApi(async (api: ApiPromise) => {1264 const from = normalizeAccountId(sender);1265 const to = normalizeAccountId(recipient);12661267 let balanceBefore = 0n;1268 if (type === 'Fungible' || type === 'ReFungible') {1269 balanceBefore = await getBalance(api, collectionId, to, tokenId);1270 }12711272 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1273 const events = await executeTransaction(api, sender, transferTx);1274 const result = getTransferResult(api, events);12751276 expect(result.collectionId).to.be.equal(collectionId);1277 expect(result.itemId).to.be.equal(tokenId);1278 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1279 expect(result.recipient).to.be.deep.equal(to);1280 expect(result.value).to.be.equal(BigInt(value));12811282 if (type === 'NFT') {1283 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1284 }1285 if (type === 'Fungible' || type === 'ReFungible') {1286 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1287 if (JSON.stringify(to) !== JSON.stringify(from)) {1288 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1289 } else {1290 expect(balanceAfter).to.be.equal(balanceBefore);1291 }1292 }1293 });1294}12951296export async function1297transferExpectFailure(1298 collectionId: number,1299 tokenId: number,1300 sender: IKeyringPair,1301 recipient: IKeyringPair | CrossAccountId,1302 value: number | bigint = 1,1303) {1304 await usingApi(async (api: ApiPromise) => {1305 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1306 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1307 const result = getGenericResult(events);1308 // if (events && Array.isArray(events)) {1309 // const result = getCreateCollectionResult(events);1310 // tslint:disable-next-line:no-unused-expression1311 expect(result.success).to.be.false;1312 //}1313 });1314}13151316export async function1317approveExpectFail(1318 collectionId: number,1319 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1320) {1321 await usingApi(async (api: ApiPromise) => {1322 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1323 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1324 const result = getCreateCollectionResult(events);1325 // tslint:disable-next-line:no-unused-expression1326 expect(result.success).to.be.false;1327 });1328}13291330export async function getBalance(1331 api: ApiPromise,1332 collectionId: number,1333 owner: string | CrossAccountId | IKeyringPair,1334 token: number,1335): Promise<bigint> {1336 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1337}1338export async function getTokenOwner(1339 api: ApiPromise,1340 collectionId: number,1341 token: number,1342): Promise<CrossAccountId> {1343 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1344 if (owner == null) throw new Error('owner == null');1345 return normalizeAccountId(owner);1346}1347export async function getTopmostTokenOwner(1348 api: ApiPromise,1349 collectionId: number,1350 token: number,1351): Promise<CrossAccountId> {1352 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1353 if (owner == null) throw new Error('owner == null');1354 return normalizeAccountId(owner);1355}1356export async function getTokenChildren(1357 api: ApiPromise,1358 collectionId: number,1359 tokenId: number,1360): Promise<UpDataStructsTokenChild[]> {1361 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1362}1363export async function isTokenExists(1364 api: ApiPromise,1365 collectionId: number,1366 token: number,1367): Promise<boolean> {1368 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1369}1370export async function getLastTokenId(1371 api: ApiPromise,1372 collectionId: number,1373): Promise<number> {1374 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1375}1376export async function getAdminList(1377 api: ApiPromise,1378 collectionId: number,1379): Promise<string[]> {1380 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1381}1382export async function getTokenProperties(1383 api: ApiPromise,1384 collectionId: number,1385 tokenId: number,1386 propertyKeys: string[],1387): Promise<UpDataStructsProperty[]> {1388 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1389}13901391export async function createFungibleItemExpectSuccess(1392 sender: IKeyringPair,1393 collectionId: number,1394 data: CreateFungibleData,1395 owner: CrossAccountId | string = sender.address,1396) {1397 return await usingApi(async (api) => {1398 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13991400 const events = await submitTransactionAsync(sender, tx);1401 const result = getCreateItemResult(events);14021403 expect(result.success).to.be.true;1404 return result.itemId;1405 });1406}14071408export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1409 await usingApi(async (api) => {1410 const to = normalizeAccountId(owner);1411 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14121413 const events = await submitTransactionAsync(sender, tx);1414 expect(getGenericResult(events).success).to.be.true;1415 });1416}14171418export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1419 await usingApi(async (api) => {1420 const to = normalizeAccountId(owner);1421 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14221423 const events = await submitTransactionAsync(sender, tx);1424 const result = getCreateItemsResult(events);14251426 for (const res of result) {1427 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1428 }1429 });1430}14311432export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1433 await usingApi(async (api) => {1434 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14351436 const events = await submitTransactionAsync(sender, tx);1437 const result = getCreateItemsResult(events);14381439 for (const res of result) {1440 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1441 }1442 });1443}14441445export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1446 let newItemId = 0;1447 await usingApi(async (api) => {1448 const to = normalizeAccountId(owner);1449 const itemCountBefore = await getLastTokenId(api, collectionId);1450 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14511452 let tx;1453 if (createMode === 'Fungible') {1454 const createData = {fungible: {value: 10}};1455 tx = api.tx.unique.createItem(collectionId, to, createData as any);1456 } else if (createMode === 'ReFungible') {1457 const createData = {refungible: {pieces: 100}};1458 tx = api.tx.unique.createItem(collectionId, to, createData as any);1459 } else {1460 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1461 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1462 }14631464 const events = await submitTransactionAsync(sender, tx);1465 const result = getCreateItemResult(events);14661467 const itemCountAfter = await getLastTokenId(api, collectionId);1468 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14691470 if (createMode === 'NFT') {1471 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1472 }14731474 // What to expect1475 // tslint:disable-next-line:no-unused-expression1476 expect(result.success).to.be.true;1477 if (createMode === 'Fungible') {1478 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1479 } else {1480 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1481 }1482 expect(collectionId).to.be.equal(result.collectionId);1483 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1484 expect(to).to.be.deep.equal(result.recipient);1485 newItemId = result.itemId;1486 });1487 return newItemId;1488}14891490export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1491 await usingApi(async (api) => {14921493 let tx;1494 if (createMode === 'NFT') {1495 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1496 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1497 } else {1498 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1499 }150015011502 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1503 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1504 const result = getCreateItemResult(events);15051506 expect(result.success).to.be.false;1507 });1508}15091510export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1511 let newItemId = 0;1512 await usingApi(async (api) => {1513 const to = normalizeAccountId(owner);1514 const itemCountBefore = await getLastTokenId(api, collectionId);1515 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15161517 let tx;1518 if (createMode === 'Fungible') {1519 const createData = {fungible: {value: 10}};1520 tx = api.tx.unique.createItem(collectionId, to, createData as any);1521 } else if (createMode === 'ReFungible') {1522 const createData = {refungible: {pieces: 100}};1523 tx = api.tx.unique.createItem(collectionId, to, createData as any);1524 } else {1525 const createData = {nft: {}};1526 tx = api.tx.unique.createItem(collectionId, to, createData as any);1527 }15281529 const events = await executeTransaction(api, sender, tx);1530 const result = getCreateItemResult(events);15311532 const itemCountAfter = await getLastTokenId(api, collectionId);1533 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15341535 // What to expect1536 // tslint:disable-next-line:no-unused-expression1537 expect(result.success).to.be.true;1538 if (createMode === 'Fungible') {1539 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1540 } else {1541 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1542 }1543 expect(collectionId).to.be.equal(result.collectionId);1544 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1545 expect(to).to.be.deep.equal(result.recipient);1546 newItemId = result.itemId;1547 });1548 return newItemId;1549}15501551export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1552 const createData = {refungible: {pieces: amount}};1553 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15541555 const events = await submitTransactionAsync(sender, tx);1556 return getCreateItemResult(events);1557}15581559export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1560 await usingApi(async (api) => {1561 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15621563 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1564 const result = getCreateItemResult(events);15651566 expect(result.success).to.be.false;1567 });1568}15691570export async function setPublicAccessModeExpectSuccess(1571 sender: IKeyringPair, collectionId: number,1572 accessMode: 'Normal' | 'AllowList',1573) {1574 await usingApi(async (api) => {15751576 // Run the transaction1577 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1578 const events = await submitTransactionAsync(sender, tx);1579 const result = getGenericResult(events);15801581 // Get the collection1582 const collection = await queryCollectionExpectSuccess(api, collectionId);15831584 // What to expect1585 // tslint:disable-next-line:no-unused-expression1586 expect(result.success).to.be.true;1587 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1588 });1589}15901591export async function setPublicAccessModeExpectFail(1592 sender: IKeyringPair, collectionId: number,1593 accessMode: 'Normal' | 'AllowList',1594) {1595 await usingApi(async (api) => {15961597 // Run the transaction1598 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1599 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1600 const result = getGenericResult(events);16011602 // What to expect1603 // tslint:disable-next-line:no-unused-expression1604 expect(result.success).to.be.false;1605 });1606}16071608export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1609 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1610}16111612export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1613 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1614}16151616export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1617 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1618}16191620export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1621 await usingApi(async (api) => {16221623 // Run the transaction1624 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1625 const events = await submitTransactionAsync(sender, tx);1626 const result = getGenericResult(events);1627 expect(result.success).to.be.true;16281629 // Get the collection1630 const collection = await queryCollectionExpectSuccess(api, collectionId);16311632 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1633 });1634}16351636export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1637 await setMintPermissionExpectSuccess(sender, collectionId, true);1638}16391640export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1641 await usingApi(async (api) => {1642 // Run the transaction1643 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1644 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1645 const result = getCreateCollectionResult(events);1646 // tslint:disable-next-line:no-unused-expression1647 expect(result.success).to.be.false;1648 });1649}16501651export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1652 await usingApi(async (api) => {1653 // Run the transaction1654 const tx = api.tx.unique.setChainLimits(limits);1655 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1656 const result = getCreateCollectionResult(events);1657 // tslint:disable-next-line:no-unused-expression1658 expect(result.success).to.be.false;1659 });1660}16611662export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1663 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1664}16651666export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1667 await usingApi(async (api) => {1668 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16691670 // Run the transaction1671 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1672 const events = await submitTransactionAsync(sender, tx);1673 const result = getGenericResult(events);1674 expect(result.success).to.be.true;16751676 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1677 });1678}16791680export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1681 await usingApi(async (api) => {16821683 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16841685 // Run the transaction1686 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1687 const events = await submitTransactionAsync(sender, tx);1688 const result = getGenericResult(events);1689 expect(result.success).to.be.true;16901691 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1692 });1693}16941695export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1696 await usingApi(async (api) => {16971698 // Run the transaction1699 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1700 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1701 const result = getGenericResult(events);17021703 // What to expect1704 // tslint:disable-next-line:no-unused-expression1705 expect(result.success).to.be.false;1706 });1707}17081709export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1710 await usingApi(async (api) => {1711 // Run the transaction1712 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1713 const events = await submitTransactionAsync(sender, tx);1714 const result = getGenericResult(events);17151716 // What to expect1717 // tslint:disable-next-line:no-unused-expression1718 expect(result.success).to.be.true;1719 });1720}17211722export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1723 await usingApi(async (api) => {1724 // Run the transaction1725 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1726 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1727 const result = getGenericResult(events);17281729 // What to expect1730 // tslint:disable-next-line:no-unused-expression1731 expect(result.success).to.be.false;1732 });1733}17341735export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1736 : Promise<UpDataStructsRpcCollection | null> => {1737 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1738};17391740export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1741 // set global object - collectionsCount1742 return (await api.rpc.unique.collectionStats()).created.toNumber();1743};17441745export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1746 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1747}17481749export async function waitNewBlocks(blocksCount = 1): Promise<void> {1750 await usingApi(async (api) => {1751 const promise = new Promise<void>(async (resolve) => {1752 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1753 if (blocksCount > 0) {1754 blocksCount--;1755 } else {1756 unsubscribe();1757 resolve();1758 }1759 });1760 });1761 return promise;1762 });1763}17641765export async function repartitionRFT(1766 api: ApiPromise,1767 collectionId: number,1768 sender: IKeyringPair,1769 tokenId: number,1770 amount: bigint,1771): Promise<boolean> {1772 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1773 const events = await submitTransactionAsync(sender, tx);1774 const result = getGenericResult(events);17751776 return result.success;1777}17781779export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1780 let i: any = it;1781 if (opts.only) i = i.only;1782 else if (opts.skip) i = i.skip;1783 i(name, async () => {1784 await usingApi(async (api, privateKeyWrapper) => {1785 await cb({api, privateKeyWrapper});1786 });1787 });1788}17891790itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1791itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});17921793let accountSeed = 10000;17941795const keyringEth = new Keyring({type: 'ethereum'});1796const keyringEd25519 = new Keyring({type: 'ed25519'});1797const keyringSr25519 = new Keyring({type: 'sr25519'});17981799export function generateKeyringPair(type: 'ethereum' | 'sr25519' | 'ed25519' = 'sr25519') {1800 const privateKey = `0xDEADBEEF${(accountSeed++).toString(16).padStart(56,'0')}`;1801 if (type == 'sr25519') {1802 return keyringSr25519.addFromUri(privateKey);1803 } else if (type == 'ed25519') {1804 return keyringEd25519.addFromUri(privateKey);1805 }1806 return keyringEth.addFromUri(privateKey);1807}tests/src/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -26,7 +26,7 @@
for (const arg of args) {
if (typeof arg !== 'string')
continue;
- if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))
+ if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
return;
}
printer(...args);
@@ -49,4 +49,4 @@
console.log = consoleLog;
console.warn = consoleWarn;
}
-};
\ No newline at end of file
+};
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -103,7 +103,6 @@
let accountsCreated = false;
// checkBalances retry up to 5 blocks
for (let index = 0; index < 5; index++) {
- console.log(await this.helper.chain.getLatestBlockNumber());
accountsCreated = await checkBalances();
if(accountsCreated) break;
await this.waitNewBlocks(1);
tests/src/xcm/xcmOpal.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmOpal.test.ts
+++ b/tests/src/xcm/xcmOpal.test.ts
@@ -35,7 +35,7 @@
const RELAY_PORT = '9844';
const UNIQUE_PORT = '9944';
-const STATEMINE_PORT = '9946';
+const STATEMINE_PORT = '9948';
const STATEMINE_PALLET_INSTANCE = 50;
const ASSET_ID = 100;
const ASSET_METADATA_DECIMALS = 18;
tests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -0,0 +1,682 @@
+// 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 {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, describe_xcm} from '../util/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';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+const QUARTZ_CHAIN = 2095;
+const KARURA_CHAIN = 2000;
+const MOONRIVER_CHAIN = 2023;
+
+const KARURA_PORT = 9946;
+const MOONRIVER_PORT = 9947;
+
+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);
+}
+
+describe_xcm('Integration test: Exchanging tokens with Karura', () => {
+ let alice: IKeyringPair;
+ let randomAccount: IKeyringPair;
+
+ let balanceQuartzTokenInit: bigint;
+ let balanceQuartzTokenMiddle: bigint;
+ let balanceQuartzTokenFinal: bigint;
+ let balanceKaruraTokenInit: bigint;
+ let balanceKaruraTokenMiddle: bigint;
+ let balanceKaruraTokenFinal: bigint;
+ let balanceQuartzForeignTokenInit: bigint;
+ let balanceQuartzForeignTokenMiddle: bigint;
+ let balanceQuartzForeignTokenFinal: bigint;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ randomAccount = generateKeyringPair();
+ });
+
+ // 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) => {
+
+ const destination = {
+ V0: {
+ X2: [
+ 'Parent',
+ {
+ Parachain: KARURA_CHAIN,
+ },
+ ],
+ },
+ };
+
+ const beneficiary = {
+ V0: {
+ X1: {
+ AccountId32: {
+ network: 'Any',
+ id: randomAccount.addressRaw,
+ },
+ },
+ },
+ };
+
+ const assets = {
+ V1: [
+ {
+ id: {
+ Concrete: {
+ parents: 0,
+ interior: 'Here',
+ },
+ },
+ fun: {
+ Fungible: TRANSFER_AMOUNT,
+ },
+ },
+ ],
+ };
+
+ const feeAssetItem = 0;
+
+ const weightLimit = {
+ Limited: 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;
+
+ [balanceQuartzTokenMiddle] = await getBalance(api, [randomAccount.address]);
+
+ const qtzFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;
+ console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', qtzFees);
+ expect(qtzFees > 0n).to.be.true;
+ });
+
+ // 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);
+
+ [balanceKaruraTokenMiddle] = await getBalance(api, [randomAccount.address]);
+
+ const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;
+ const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;
+
+ console.log('[Quartz -> Karura] transaction fees on Karura: %s KAR', karFees);
+ console.log('[Quartz -> Karura] income %s QTZ', qtzIncomeTransfer);
+ expect(karFees == 0n).to.be.true;
+ expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
+ },
+ karuraOptions(),
+ );
+ });
+
+ 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,
+ },
+ },
+ ],
+ },
+ },
+ };
+
+ const id = {
+ ForeignAsset: 0,
+ };
+
+ const destWeight = 50000000;
+
+ const tx = api.tx.xTokens.transfer(id, TRANSFER_AMOUNT, destination, destWeight);
+ const events = await submitTransactionAsync(randomAccount, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+
+ [balanceKaruraTokenFinal] = await getBalance(api, [randomAccount.address]);
+ {
+ const {free} = (await api.query.tokens.accounts(randomAccount.addressRaw, {ForeignAsset: 0})).toJSON() as any;
+ balanceQuartzForeignTokenFinal = BigInt(free);
+ }
+
+ const karFees = balanceKaruraTokenMiddle - balanceKaruraTokenFinal;
+ const qtzOutcomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenFinal;
+
+ console.log('[Karura -> Quartz] transaction fees on Karura: %s KAR', karFees);
+ console.log('[Karura -> Quartz] outcome %s QTZ', qtzOutcomeTransfer);
+
+ expect(karFees > 0).to.be.true;
+ expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
+ },
+ karuraOptions(),
+ );
+
+ // Quartz side
+ await usingApi(async (api) => {
+ await waitNewBlocks(api, 3);
+
+ [balanceQuartzTokenFinal] = await getBalance(api, [randomAccount.address]);
+ const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;
+ expect(actuallyDelivered > 0).to.be.true;
+
+ console.log('[Karura -> Quartz] actually delivered %s QTZ', actuallyDelivered);
+
+ const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;
+ console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', qtzFees);
+ expect(qtzFees == 0n).to.be.true;
+ });
+ });
+
+ it('Quartz rejects KAR tokens from Karura', async () => {
+ // This test is relevant only when the foreign asset pallet is disabled
+
+ await usingApi(async (api) => {
+ const destination = {
+ V1: {
+ parents: 1,
+ interior: {
+ X2: [
+ {Parachain: QUARTZ_CHAIN},
+ {
+ AccountId32: {
+ network: 'Any',
+ id: randomAccount.addressRaw,
+ },
+ },
+ ],
+ },
+ },
+ };
+
+ const id = {
+ Token: 'KAR',
+ };
+
+ const destWeight = 50000000;
+
+ const tx = api.tx.xTokens.transfer(id, 100_000_000_000, destination, destWeight);
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+ }, karuraOptions());
+
+ await usingApi(async api => {
+ const maxWaitBlocks = 3;
+ const xcmpQueueFailEvent = await waitEvent(api, maxWaitBlocks, 'xcmpQueue', 'Fail');
+
+ expect(
+ xcmpQueueFailEvent != null,
+ 'Only native token is supported when the Foreign-Assets pallet is not connected',
+ ).to.be.true;
+ });
+ });
+});
+
+describe_xcm('Integration test: Exchanging QTZ with Moonriver', () => {
+
+ // Quartz constants
+ let quartzAlice: IKeyringPair;
+ let quartzAssetLocation;
+
+ let randomAccountQuartz: IKeyringPair;
+ let randomAccountMoonriver: IKeyringPair;
+
+ // 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;
+ const votingPeriod = 3;
+ const delayPeriod = 0;
+
+ const quartzAssetMetadata = {
+ name: 'xcQuartz',
+ symbol: 'xcQTZ',
+ decimals: 18,
+ isFrozen: false,
+ minimalBalance: 1,
+ };
+
+ let balanceQuartzTokenInit: bigint;
+ let balanceQuartzTokenMiddle: bigint;
+ let balanceQuartzTokenFinal: bigint;
+ let balanceForeignQtzTokenInit: bigint;
+ let balanceForeignQtzTokenMiddle: bigint;
+ let balanceForeignQtzTokenFinal: bigint;
+ let balanceMovrTokenInit: bigint;
+ let balanceMovrTokenMiddle: bigint;
+ let balanceMovrTokenFinal: bigint;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ quartzAlice = privateKeyWrapper('//Alice');
+ randomAccountQuartz = generateKeyringPair();
+ randomAccountMoonriver = generateKeyringPair('ethereum');
+
+ balanceForeignQtzTokenInit = 0n;
+ });
+
+ await usingApi(
+ async (api) => {
+
+ // >>> 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 <<<
+
+ const sourceLocation: MultiLocation = api.createType(
+ 'MultiLocation',
+ {
+ parents: 1,
+ interior: {X1: {Parachain: QUARTZ_CHAIN}},
+ },
+ );
+
+ quartzAssetLocation = {XCM: sourceLocation};
+ const existentialDeposit = 1;
+ const isSufficient = true;
+ const unitsPerSecond = '1';
+ 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 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 <<<
+
+ // >>> 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;
+
+ 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;
+ }
+
+ 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 <<<
+
+ // >>> 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;
+
+ 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;
+ }
+
+ 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 <<<
+
+ // >>> 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 <<<
+
+ // >>> Acquire Quartz AssetId Info on Moonriver >>>
+ console.log('Acquire Quartz AssetId Info on Moonriver.......');
+
+ // Wait for the democracy execute
+ await waitNewBlocks(api, 5);
+
+ assetId = (await api.query.assetManager.assetTypeId({
+ XCM: sourceLocation,
+ })).toString();
+
+ console.log('QTZ asset ID is %s', assetId);
+ console.log('Acquire Quartz AssetId Info on Moonriver.......DONE');
+ // >>> Acquire Quartz AssetId Info on Moonriver >>>
+
+ // >>> 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 <<<
+
+ [balanceMovrTokenInit] = await getBalance(api, [randomAccountMoonriver.address]);
+ },
+ moonriverOptions(),
+ );
+
+ 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;
+
+ [balanceQuartzTokenInit] = await getBalance(api, [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}},
+ ],
+ },
+ },
+ };
+ 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;
+
+ [balanceQuartzTokenMiddle] = await getBalance(api, [randomAccountQuartz.address]);
+ expect(balanceQuartzTokenMiddle < balanceQuartzTokenInit).to.be.true;
+
+ const transactionFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;
+ console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', transactionFees);
+ expect(transactionFees > 0).to.be.true;
+ });
+
+ await usingApi(
+ async (api) => {
+ await waitNewBlocks(api, 3);
+
+ [balanceMovrTokenMiddle] = await getBalance(api, [randomAccountMoonriver.address]);
+
+ const movrFees = balanceMovrTokenInit - balanceMovrTokenMiddle;
+ console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR', 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', qtzIncomeTransfer);
+ expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
+ },
+ moonriverOptions(),
+ );
+ });
+
+ 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},
+ },
+ },
+ },
+ fun: {
+ Fungible: TRANSFER_AMOUNT,
+ },
+ },
+ };
+ 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;
+
+ [balanceMovrTokenFinal] = await getBalance(api, [randomAccountMoonriver.address]);
+
+ const movrFees = balanceMovrTokenMiddle - balanceMovrTokenFinal;
+ console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', movrFees);
+ expect(movrFees > 0).to.be.true;
+
+ const qtzRandomAccountAsset = (
+ await api.query.assets.account(assetId, randomAccountMoonriver.address)
+ ).toJSON()! as any;
+
+ expect(qtzRandomAccountAsset).to.be.null;
+
+ balanceForeignQtzTokenFinal = 0n;
+
+ const qtzOutcomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenFinal;
+ console.log('[Quartz -> Moonriver] outcome %s QTZ', qtzOutcomeTransfer);
+ expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
+ },
+ moonriverOptions(),
+ );
+
+ await usingApi(async (api) => {
+ await waitNewBlocks(api, 3);
+
+ [balanceQuartzTokenFinal] = await getBalance(api, [randomAccountQuartz.address]);
+ const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;
+ expect(actuallyDelivered > 0).to.be.true;
+
+ console.log('[Moonriver -> Quartz] actually delivered %s QTZ', actuallyDelivered);
+
+ const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;
+ console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', qtzFees);
+ expect(qtzFees == 0n).to.be.true;
+ });
+ });
+});
tests/src/xcm/xcmTransferMoonbeam.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmTransferMoonbeam.test.ts
+++ b/tests/src/xcm/xcmTransferMoonbeam.test.ts
@@ -50,7 +50,7 @@
});
const UNIQUE_PORT = '9944';
-const MOONBEAM_PORT = '9946';
+const MOONBEAM_PORT = '9947';
const TRANSFER_AMOUNT = 2000000000000000000000000n;
describe('Integration test: Exchanging UNQ with Moonbeam', () => {
tests/src/xcm/xcmTransferStatemine.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmTransferStatemine.test.ts
+++ b/tests/src/xcm/xcmTransferStatemine.test.ts
@@ -53,7 +53,7 @@
const RELAY_PORT = '9844';
const UNIQUE_PORT = '9944';
-const STATEMINE_PORT = '9946';
+const STATEMINE_PORT = '9948';
const STATEMINE_PALLET_INSTANCE = 50;
const ASSET_ID = 100;
const ASSET_METADATA_DECIMALS = 18;
tests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -17,11 +17,13 @@
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
-import {WsProvider} from '@polkadot/api';
+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} from '../util/helpers';
+import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm} from '../util/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';
@@ -30,23 +32,39 @@
const UNIQUE_CHAIN = 2037;
const ACALA_CHAIN = 2000;
+const MOONBEAM_CHAIN = 2004;
-const ACALA_PORT = '9946';
+const ACALA_PORT = 9946;
+const MOONBEAM_PORT = 9947;
const TRANSFER_AMOUNT = 2000000000000000000000000n;
-describe('Integration test: Exchanging UNQ with Acala', () => {
+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);
+}
+
+describe_xcm('Integration test: Exchanging tokens with Acala', () => {
let alice: IKeyringPair;
let randomAccount: IKeyringPair;
- let balanceUniqueTokenBefore: bigint;
- let balanceUniqueTokenAfter: bigint;
+ let balanceUniqueTokenInit: bigint;
+ let balanceUniqueTokenMiddle: bigint;
let balanceUniqueTokenFinal: bigint;
- let balanceAcalaTokenBefore: bigint;
- let balanceAcalaTokenAfter: bigint;
+ let balanceAcalaTokenInit: bigint;
+ let balanceAcalaTokenMiddle: bigint;
let balanceAcalaTokenFinal: bigint;
- let balanceUniqueForeignTokenAfter: bigint;
- let balanceUniqueForeignTokenBefore: bigint;
+ let balanceUniqueForeignTokenInit: bigint;
+ let balanceUniqueForeignTokenMiddle: bigint;
let balanceUniqueForeignTokenFinal: bigint;
before(async () => {
@@ -54,11 +72,7 @@
alice = privateKeyWrapper('//Alice');
randomAccount = generateKeyringPair();
});
-
- const acalaApiOptions: ApiOptions = {
- provider: new WsProvider('ws://127.0.0.1:' + ACALA_PORT),
- };
-
+
// Acala side
await usingApi(
async (api) => {
@@ -91,13 +105,13 @@
const result1 = getGenericResult(events1);
expect(result1.success).to.be.true;
- [balanceAcalaTokenBefore] = await getBalance(api, [randomAccount.address]);
+ [balanceAcalaTokenInit] = await getBalance(api, [randomAccount.address]);
{
const {free} = (await api.query.tokens.accounts(randomAccount.addressRaw, {ForeignAsset: 0})).toJSON() as any;
- balanceUniqueForeignTokenBefore = BigInt(free);
+ balanceUniqueForeignTokenInit = BigInt(free);
}
},
- acalaApiOptions,
+ acalaOptions(),
);
// Unique side
@@ -107,7 +121,7 @@
const result0 = getGenericResult(events0);
expect(result0.success).to.be.true;
- [balanceUniqueTokenBefore] = await getBalance(api, [randomAccount.address]);
+ [balanceUniqueTokenInit] = await getBalance(api, [randomAccount.address]);
});
});
@@ -165,9 +179,9 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- [balanceUniqueTokenAfter] = await getBalance(api, [randomAccount.address]);
+ [balanceUniqueTokenMiddle] = await getBalance(api, [randomAccount.address]);
- const unqFees = balanceUniqueTokenBefore - balanceUniqueTokenAfter;
+ const unqFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;
console.log('[Unique -> Acala] transaction fees on Unique: %s UNQ', unqFees);
expect(unqFees > 0n).to.be.true;
});
@@ -175,24 +189,21 @@
// Acala side
await usingApi(
async (api) => {
- // todo do something about instant sealing, where there might not be any new blocks
await waitNewBlocks(api, 3);
const {free} = (await api.query.tokens.accounts(randomAccount.addressRaw, {ForeignAsset: 0})).toJSON() as any;
- balanceUniqueForeignTokenAfter = BigInt(free);
+ balanceUniqueForeignTokenMiddle = BigInt(free);
- [balanceAcalaTokenAfter] = await getBalance(api, [randomAccount.address]);
+ [balanceAcalaTokenMiddle] = await getBalance(api, [randomAccount.address]);
- const acaFees = balanceAcalaTokenBefore - balanceAcalaTokenAfter;
- const unqDiffAfterIncomeTransfer = balanceUniqueForeignTokenAfter - balanceUniqueForeignTokenBefore;
-
- const unqFees = unqDiffAfterIncomeTransfer - TRANSFER_AMOUNT;
+ const acaFees = balanceAcalaTokenInit - balanceAcalaTokenMiddle;
+ const unqIncomeTransfer = balanceUniqueForeignTokenMiddle - balanceUniqueForeignTokenInit;
console.log('[Unique -> Acala] transaction fees on Acala: %s ACA', acaFees);
- console.log('[Unique -> Acala] transaction fees on Acala: %s UNQ', unqFees);
+ console.log('[Unique -> Acala] income %s UNQ', unqIncomeTransfer);
expect(acaFees == 0n).to.be.true;
- expect(unqFees == 0n).to.be.true;
+ expect(unqIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
},
- {provider: new WsProvider('ws://127.0.0.1:' + ACALA_PORT)},
+ acalaOptions(),
);
});
@@ -221,11 +232,10 @@
const id = {
ForeignAsset: 0,
};
-
- const amount = TRANSFER_AMOUNT;
+
const destWeight = 50000000;
- const tx = api.tx.xTokens.transfer(id, amount, destination, destWeight);
+ const tx = api.tx.xTokens.transfer(id, TRANSFER_AMOUNT, destination, destWeight);
const events = await submitTransactionAsync(randomAccount, tx);
const result = getGenericResult(events);
expect(result.success).to.be.true;
@@ -236,32 +246,437 @@
balanceUniqueForeignTokenFinal = BigInt(free);
}
- const acaFees = balanceAcalaTokenAfter - balanceAcalaTokenFinal;
- const unqDiffAfterOutcomeTransfer = balanceUniqueForeignTokenAfter - TRANSFER_AMOUNT;
-
- const unqFees = unqDiffAfterOutcomeTransfer - balanceUniqueForeignTokenFinal;
+ const acaFees = balanceAcalaTokenMiddle - balanceAcalaTokenFinal;
+ const unqOutcomeTransfer = balanceUniqueForeignTokenMiddle - balanceUniqueForeignTokenFinal;
console.log('[Acala -> Unique] transaction fees on Acala: %s ACA', acaFees);
- console.log('[Acala -> Unique] transaction fees on Acala: %s UNQ', unqFees);
+ console.log('[Acala -> Unique] outcome %s UNQ', unqOutcomeTransfer);
expect(acaFees > 0).to.be.true;
- expect(unqFees == 0n).to.be.true;
+ expect(unqOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
},
- {provider: new WsProvider('ws://127.0.0.1:' + ACALA_PORT)},
+ acalaOptions(),
);
// Unique side
await usingApi(async (api) => {
- // todo do something about instant sealing, where there might not be any new blocks
await waitNewBlocks(api, 3);
[balanceUniqueTokenFinal] = await getBalance(api, [randomAccount.address]);
- const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenAfter;
+ const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenMiddle;
expect(actuallyDelivered > 0).to.be.true;
+
+ console.log('[Acala -> Unique] actually delivered %s UNQ', actuallyDelivered);
const unqFees = TRANSFER_AMOUNT - actuallyDelivered;
console.log('[Acala -> Unique] transaction fees on Unique: %s UNQ', unqFees);
expect(unqFees == 0n).to.be.true;
});
});
+
+ it('Unique rejects ACA tokens from Acala', async () => {
+ // This test is relevant only when the foreign asset pallet is disabled
+
+ await usingApi(async (api) => {
+ const destination = {
+ V1: {
+ parents: 1,
+ interior: {
+ X2: [
+ {Parachain: UNIQUE_CHAIN},
+ {
+ AccountId32: {
+ network: 'Any',
+ id: randomAccount.addressRaw,
+ },
+ },
+ ],
+ },
+ },
+ };
+
+ const id = {
+ Token: 'ACA',
+ };
+
+ const destWeight = 50000000;
+
+ const tx = api.tx.xTokens.transfer(id, 100_000_000_000, destination, destWeight);
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getGenericResult(events);
+ expect(result.success).to.be.true;
+ }, acalaOptions());
+
+ await usingApi(async api => {
+ const maxWaitBlocks = 3;
+ const xcmpQueueFailEvent = await waitEvent(api, maxWaitBlocks, 'xcmpQueue', 'Fail');
+
+ expect(
+ xcmpQueueFailEvent != null,
+ 'Only native token is supported when the Foreign-Assets pallet is not connected',
+ ).to.be.true;
+ });
+ });
+});
+
+describe_xcm('Integration test: Exchanging UNQ with Moonbeam', () => {
+
+ // Unique constants
+ let uniqueAlice: IKeyringPair;
+ let uniqueAssetLocation;
+
+ let randomAccountUnique: IKeyringPair;
+ let randomAccountMoonbeam: IKeyringPair;
+
+ // 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;
+ const delayPeriod = 0;
+
+ const uniqueAssetMetadata = {
+ name: 'xcUnique',
+ symbol: 'xcUNQ',
+ decimals: 18,
+ isFrozen: false,
+ minimalBalance: 1,
+ };
+
+ let balanceUniqueTokenInit: bigint;
+ let balanceUniqueTokenMiddle: bigint;
+ let balanceUniqueTokenFinal: bigint;
+ let balanceForeignUnqTokenInit: bigint;
+ let balanceForeignUnqTokenMiddle: bigint;
+ let balanceForeignUnqTokenFinal: bigint;
+ let balanceGlmrTokenInit: bigint;
+ let balanceGlmrTokenMiddle: bigint;
+ let balanceGlmrTokenFinal: bigint;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ uniqueAlice = privateKeyWrapper('//Alice');
+ randomAccountUnique = generateKeyringPair();
+ randomAccountMoonbeam = generateKeyringPair('ethereum');
+
+ balanceForeignUnqTokenInit = 0n;
+ });
+
+ await usingApi(
+ async (api) => {
+
+ // >>> 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 <<<
+
+ const sourceLocation: MultiLocation = api.createType(
+ 'MultiLocation',
+ {
+ parents: 1,
+ interior: {X1: {Parachain: UNIQUE_CHAIN}},
+ },
+ );
+
+ uniqueAssetLocation = {XCM: sourceLocation};
+ const existentialDeposit = 1;
+ const isSufficient = true;
+ const unitsPerSecond = '1';
+ 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 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 <<<
+
+ // >>> 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;
+
+ 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;
+ }
+
+ 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 <<<
+
+ // >>> 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;
+
+ 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;
+ }
+
+ 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 <<<
+
+ // >>> 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 <<<
+
+ // >>> Acquire Unique AssetId Info on Moonbeam >>>
+ console.log('Acquire Unique AssetId Info on Moonbeam.......');
+
+ // Wait for the democracy execute
+ await waitNewBlocks(api, 5);
+
+ assetId = (await api.query.assetManager.assetTypeId({
+ XCM: sourceLocation,
+ })).toString();
+
+ console.log('UNQ asset ID is %s', assetId);
+ console.log('Acquire Unique AssetId Info on Moonbeam.......DONE');
+ // >>> Acquire Unique AssetId Info on Moonbeam >>>
+
+ // >>> 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 <<<
+
+ [balanceGlmrTokenInit] = await getBalance(api, [randomAccountMoonbeam.address]);
+ },
+ moonbeamOptions(),
+ );
+
+ 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;
+
+ [balanceUniqueTokenInit] = await getBalance(api, [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}},
+ ],
+ },
+ },
+ };
+ 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;
+
+ [balanceUniqueTokenMiddle] = await getBalance(api, [randomAccountUnique.address]);
+ expect(balanceUniqueTokenMiddle < balanceUniqueTokenInit).to.be.true;
+
+ const transactionFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;
+ console.log('[Unique -> Moonbeam] transaction fees on Unique: %s UNQ', transactionFees);
+ expect(transactionFees > 0).to.be.true;
+ });
+
+ await usingApi(
+ async (api) => {
+ await waitNewBlocks(api, 3);
+
+ [balanceGlmrTokenMiddle] = await getBalance(api, [randomAccountMoonbeam.address]);
+
+ const glmrFees = balanceGlmrTokenInit - balanceGlmrTokenMiddle;
+ console.log('[Unique -> Moonbeam] transaction fees on Moonbeam: %s GLMR', glmrFees);
+ expect(glmrFees == 0n).to.be.true;
+
+ const unqRandomAccountAsset = (
+ await api.query.assets.account(assetId, randomAccountMoonbeam.address)
+ ).toJSON()! as any;
+
+ balanceForeignUnqTokenMiddle = BigInt(unqRandomAccountAsset['balance']);
+ const unqIncomeTransfer = balanceForeignUnqTokenMiddle - balanceForeignUnqTokenInit;
+ console.log('[Unique -> Moonbeam] income %s UNQ', unqIncomeTransfer);
+ expect(unqIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
+ },
+ moonbeamOptions(),
+ );
+ });
+
+ 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},
+ },
+ },
+ },
+ fun: {
+ Fungible: TRANSFER_AMOUNT,
+ },
+ },
+ };
+ const destination = {
+ V1: {
+ parents: 1,
+ interior: {
+ X2: [
+ {Parachain: UNIQUE_CHAIN},
+ {AccountId32: {network: 'Any', id: randomAccountUnique.addressRaw}},
+ ],
+ },
+ },
+ };
+ 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;
+
+ [balanceGlmrTokenFinal] = await getBalance(api, [randomAccountMoonbeam.address]);
+
+ const glmrFees = balanceGlmrTokenMiddle - balanceGlmrTokenFinal;
+ console.log('[Moonbeam -> Unique] transaction fees on Moonbeam: %s GLMR', glmrFees);
+ expect(glmrFees > 0).to.be.true;
+
+ const unqRandomAccountAsset = (
+ await api.query.assets.account(assetId, randomAccountMoonbeam.address)
+ ).toJSON()! as any;
+
+ expect(unqRandomAccountAsset).to.be.null;
+
+ balanceForeignUnqTokenFinal = 0n;
+
+ const unqOutcomeTransfer = balanceForeignUnqTokenMiddle - balanceForeignUnqTokenFinal;
+ console.log('[Unique -> Moonbeam] outcome %s UNQ', unqOutcomeTransfer);
+ expect(unqOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
+ },
+ moonbeamOptions(),
+ );
+
+ await usingApi(async (api) => {
+ await waitNewBlocks(api, 3);
+
+ [balanceUniqueTokenFinal] = await getBalance(api, [randomAccountUnique.address]);
+ const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenMiddle;
+ expect(actuallyDelivered > 0).to.be.true;
+
+ console.log('[Moonbeam -> Unique] actually delivered %s UNQ', actuallyDelivered);
+
+ const unqFees = TRANSFER_AMOUNT - actuallyDelivered;
+ console.log('[Moonbeam -> Unique] transaction fees on Unique: %s UNQ', unqFees);
+ expect(unqFees == 0n).to.be.true;
+ });
+ });
});