diff --git a/Cargo.lock b/Cargo.lock index 4370682aa..67c58cdff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1019,6 +1019,55 @@ dependencies = [ "sp-api", ] +[[package]] +name = "bifrost-integration-tests" +version = "0.8.0" +dependencies = [ + "bifrost-asset-registry", + "bifrost-currencies", + "bifrost-polkadot-runtime", + "bifrost-primitives", + "bifrost-runtime-common", + "bifrost-slp", + "bifrost-vtoken-voting", + "bifrost-xcm-interface", + "cumulus-primitives-core", + "env_logger", + "frame-support", + "frame-system", + "hex-literal 0.4.1", + "log", + "orml-tokens", + "orml-traits", + "orml-xtokens", + "pallet-assets", + "pallet-balances", + "pallet-conviction-voting", + "pallet-message-queue", + "pallet-referenda", + "pallet-staking", + "pallet-xcm", + "parachains-common", + "parity-scale-codec", + "polkadot-core-primitives", + "polkadot-parachain-primitives", + "polkadot-runtime-common", + "polkadot-runtime-parachains", + "scale-info", + "serde", + "sp-core", + "sp-io", + "sp-runtime", + "sp-staking", + "sp-std", + "staging-parachain-info", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "xcm-emulator", + "xcm-simulator", +] + [[package]] name = "bifrost-kusama-runtime" version = "0.8.0" @@ -7506,11 +7555,13 @@ version = "29.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed783679921ad8b96807d683d320c314e305753b230d5c04dc713bab7aca64c" dependencies = [ + "frame-benchmarking", "frame-support", "frame-system", "pallet-transaction-payment", "parity-scale-codec", "scale-info", + "serde", "sp-core", "sp-io", "sp-runtime", @@ -16080,6 +16131,41 @@ dependencies = [ "time", ] +[[package]] +name = "xcm-emulator" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b49681988880dd6d08a4d5f6b7cb612a0f12172270349655c1e2f870b3526fd" +dependencies = [ + "cumulus-pallet-parachain-system", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "cumulus-primitives-parachain-inherent", + "cumulus-test-relay-sproof-builder", + "frame-support", + "frame-system", + "impl-trait-for-tuples", + "lazy_static", + "log", + "pallet-balances", + "pallet-message-queue", + "parachains-common", + "parity-scale-codec", + "paste", + "polkadot-parachain-primitives", + "polkadot-primitives", + "polkadot-runtime-parachains", + "sp-arithmetic", + "sp-core", + "sp-crypto-hashing", + "sp-io", + "sp-runtime", + "sp-std", + "sp-tracing", + "staging-xcm", + "staging-xcm-executor", +] + [[package]] name = "xcm-procedural" version = "8.0.0" diff --git a/Cargo.toml b/Cargo.toml index 36d17fcee..e18eda964 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,8 @@ members = [ "runtime/bifrost-kusama", "runtime/bifrost-polkadot", + + "integration-tests" ] resolver = "2" diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml new file mode 100644 index 000000000..4f1942630 --- /dev/null +++ b/integration-tests/Cargo.toml @@ -0,0 +1,50 @@ +[package] +name = "bifrost-integration-tests" +version = "0.8.0" +authors = ["hqwangningbo <2536935847@qq.com>"] +edition = "2021" + +[dev-dependencies] +bifrost-asset-registry = { workspace = true } +bifrost-currencies = { workspace = true } +bifrost-polkadot-runtime = { workspace = true } +bifrost-primitives = { workspace = true } +bifrost-runtime-common = { workspace = true } +bifrost-slp = { workspace = true } +bifrost-vtoken-voting = { workspace = true } +bifrost-xcm-interface = { workspace = true } +cumulus-primitives-core = { workspace = true } +env_logger = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +hex-literal = { workspace = true } +log = { workspace = true } +orml-tokens = { workspace = true } +orml-traits = { workspace = true } +orml-xtokens = { workspace = true } +pallet-assets = { workspace = true } +pallet-balances = { workspace = true } +pallet-conviction-voting = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-referenda = { workspace = true } +pallet-staking = { workspace = true } +pallet-xcm = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +parity-scale-codec = { workspace = true } +polkadot-core-primitives = { workspace = true } +polkadot-parachain-primitives = { workspace = true, features = ["std"] } +polkadot-runtime-common = { workspace = true, features = ["std"] } +polkadot-runtime-parachains = { workspace = true, features = ["std"] } +scale-info = { workspace = true } +serde = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-staking = { workspace = true } +sp-std = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-emulator = { workspace = true } +xcm-executor = { workspace = true } +xcm-simulator = { workspace = true } diff --git a/integration-tests/bifrost-kusama/Cargo.toml b/integration-tests/bifrost-kusama/Cargo.toml deleted file mode 100644 index 0957a8cb8..000000000 --- a/integration-tests/bifrost-kusama/Cargo.toml +++ /dev/null @@ -1,45 +0,0 @@ -[package] -name = "bifrost-kusama-integration-tests" -version = "0.8.0" -authors = ["Ron Yang "] -edition = "2021" - -[dependencies] -env_logger = { workspace = true } -log = { workspace = true } -hex-literal = { workspace = true } -parity-scale-codec = { workspace = true } - -# Substrate -sp-runtime = { workspace = true } -sp-io = { workspace = true } -sp-staking = { workspace = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -pallet-balances = { workspace = true } -pallet-assets = { workspace = true } -pallet-conviction-voting = { workspace = true } -pallet-referenda = { workspace = true } -pallet-staking = { workspace = true } - -# Polkadot -polkadot-parachain-primitives = { workspace = true } -kusama-runtime = { workspace = true } -xcm = { workspace = true } -pallet-xcm = { workspace = true } -pallet-message-queue = { workspace = true } - -# Cumulus -parachains-common = { workspace = true } -xcm-emulator = { workspace = true } - -# Local -integration-tests-common = { path = "../common", default-features = false } -bifrost-slp = { workspace = true } -bifrost-vtoken-voting = { workspace = true } -bifrost-primitives = { workspace = true } -bifrost-asset-registry = { workspace = true } -bifrost-kusama-runtime = { workspace = true } -bifrost-runtime-common = { workspace = true } -orml-traits = { workspace = true } -orml-tokens = { workspace = true } diff --git a/integration-tests/bifrost-kusama/src/account_id.rs b/integration-tests/bifrost-kusama/src/account_id.rs deleted file mode 100644 index 71785f649..000000000 --- a/integration-tests/bifrost-kusama/src/account_id.rs +++ /dev/null @@ -1,185 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use frame_support::PalletId; -use integration_tests_common::{ - impls::{AccountId, ParaId}, - BifrostKusama, -}; -use polkadot_parachain_primitives::primitives::Sibling; -use sp_runtime::{app_crypto::Ss58Codec, traits::AccountIdConversion}; -use xcm_emulator::TestExt; - -pub const TREASURY_PALLET_ID: PalletId = PalletId(*b"bf/trsry"); -pub const BIFROST_CROWDLOAN_ID: PalletId = PalletId(*b"bf/salp#"); -pub const BIFROST_SALP_LITE_CROWDLOAN_ID: PalletId = PalletId(*b"bf/salpl"); -pub const LIQUIDITY_MINING_PALLET_ID: PalletId = PalletId(*b"bf/lm###"); -pub const LIQUIDITY_MINING_DOTPALLET_ID: PalletId = PalletId(*b"bf/lmdot"); -pub const LIGHTENING_REDEEM_PALLET_ID: PalletId = PalletId(*b"bf/ltnrd"); -pub const MERKLE_DIRTRIBUTOR_PALLET_ID: PalletId = PalletId(*b"bf/mklds"); -pub const VSBOND_AUCTION_PALLET_ID: PalletId = PalletId(*b"bf/vsbnd"); -pub const PARACHAIN_STAKING_PALLET_ID: PalletId = PalletId(*b"bf/stake"); -pub const BIFROST_VSBOND_PALLET_ID: PalletId = PalletId(*b"bf/salpb"); -pub const SLP_ENTRANCE_PALLET_ID: PalletId = PalletId(*b"bf/vtkin"); -pub const SLP_EXIT_PALLET_ID: PalletId = PalletId(*b"bf/vtout"); -pub const STABLE_AMM_PALLET_ID: PalletId = PalletId(*b"bf/stamm"); -pub const FARMING_KEEPER_PALLET_ID: PalletId = PalletId(*b"bf/fmkpr"); -pub const FARMING_REWARD_ISSUER_PALLET_ID: PalletId = PalletId(*b"bf/fmrir"); -pub const SYSTEM_STAKING_PALLET_ID: PalletId = PalletId(*b"bf/sysst"); -pub const BUYBACK_PALLET_ID: PalletId = PalletId(*b"bf/salpc"); -pub const SYSTEM_MAKER_PALLET_ID: PalletId = PalletId(*b"bf/sysmk"); - -#[test] -fn parachain_account_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!( - >::into_account_truncating(&ParaId::from( - 2001 - )), - AccountId::from_ss58check("F7fq1jMmNj5j2jAHcBxgM26JzUn2N4duXu1U4UZNdkfZEPV").unwrap() - ); - assert_eq!( - >::into_account_truncating(&ParaId::from( - 2030 - )), - AccountId::from_ss58check("eGJryu57ZpFQjFRiya9nGcqiGG2RZeGWuXMENq4Na7jFNjs").unwrap() - ); - assert_eq!( - >::into_account_truncating(&Sibling::from( - 2034 - )), - AccountId::from_ss58check("eLHN5PtznDscogoZVS9feWwMGaziRRryQ451m1ocUHB1cMe").unwrap() - ); - }) -} - -#[test] -fn pallet_id_account_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!( - >::into_account_truncating( - &TREASURY_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNYdM3UjBNxcBNBqGxtz3SEEfydKragtL4pJ4F").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &BIFROST_CROWDLOAN_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNQGSkjt2tjezJRdzUJNGgdgAihwxKQsa4LdPN").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &BIFROST_SALP_LITE_CROWDLOAN_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNQGSkmPV2DLuQyBiG1dA5eMWAvRFGkQjZ7YDU").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &LIQUIDITY_MINING_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGMTkdAd9Z5P96SQ4UheKhx4pWNg5Pu734mRHbm").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &LIQUIDITY_MINING_DOTPALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGMTm5SYswh7EECLDTdu9gFbjt2HALzH1gazWUG").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &LIGHTENING_REDEEM_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGMTyaXsM7F3G8oR4bAgy6qU27xfobQkzN5CH3h").unwrap() - ); - // - assert_eq!( - >::into_account_truncating( - &MERKLE_DIRTRIBUTOR_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGMbYEwSupkwsPfjzzSGSf9MWxCHf1mEUyUyc4Y").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &VSBOND_AUCTION_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNpLKqNkBEJLLkTkSzHt41QDhqiECF5shU8Qsp").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &PARACHAIN_STAKING_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNQr7VZ48fkCX5vkt1H16F8Np9g2hYssRXHZJF").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &BIFROST_VSBOND_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNQGSkmBWD7AfnKVcXzjriDdZs2ezEjKfsR4h5").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &SLP_ENTRANCE_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNpNATVMhrmGeJj8drJWWGXrHtVo4Vym2cUnSz").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &SLP_EXIT_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNpNC5wLwUw92XQSHZ9tyrU5SYVDmRyodCrdAR").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &STABLE_AMM_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNQr7Vjo4uHNjwii1g4zfTHyWC5iBMrQj7R4P2").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &FARMING_KEEPER_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGLejANY2XNJzg7B8cB4mBx8Rbw4tXHpY6GK5YE").unwrap() - ); - // - assert_eq!( - >::into_account_truncating( - &FARMING_REWARD_ISSUER_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGLejDBGEgnWnj8mNePufttUVCjF3snTttG6SDZ").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &SYSTEM_STAKING_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNR17nzbZNJxo7G9mYziLiJcujnWXCNB2CUakX").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &BUYBACK_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNQGSkmChh1z6Lz4d7CRneZWAJ22p98daSPJsF").unwrap() - ); - assert_eq!( - >::into_account_truncating( - &SYSTEM_MAKER_PALLET_ID - ), - AccountId::from_ss58check("eCSrvbA5gGNR17nSgitMhUyrqX8e4a8wuk5Q7UKUBhxdi5S").unwrap() - ); - }) -} diff --git a/integration-tests/bifrost-kusama/src/dollor_tests.rs b/integration-tests/bifrost-kusama/src/dollor_tests.rs deleted file mode 100644 index 9ba5c8ed9..000000000 --- a/integration-tests/bifrost-kusama/src/dollor_tests.rs +++ /dev/null @@ -1,129 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use bifrost_kusama_runtime::Runtime; -use bifrost_primitives::{CurrencyId, TokenSymbol::*}; -use bifrost_runtime_common::{cent, dollar, micro, microcent, milli, millicent}; -use integration_tests_common::BifrostKusama; -use xcm_emulator::TestExt; - -const DECIMAL_18: u128 = 1_000_000_000_000_000_000; -const DECIMAL_12: u128 = 1_000_000_000_000; -const DOT_DECIMALS: u128 = 10_000_000_000; - -#[test] -fn dollar_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(dollar::(CurrencyId::Token(ASG)), DECIMAL_12); - assert_eq!(dollar::(CurrencyId::Token(BNC)), DECIMAL_12); - assert_eq!(dollar::(CurrencyId::Token(KUSD)), DECIMAL_12); - assert_eq!(dollar::(CurrencyId::Token(DOT)), DOT_DECIMALS); - assert_eq!(dollar::(CurrencyId::Token(KSM)), DECIMAL_12); - assert_eq!(dollar::(CurrencyId::Token(ETH)), DECIMAL_18); - assert_eq!(dollar::(CurrencyId::Token(KAR)), DECIMAL_12); - assert_eq!(dollar::(CurrencyId::Token(ZLK)), DECIMAL_18); - assert_eq!(dollar::(CurrencyId::Token(PHA)), DECIMAL_12); - assert_eq!(dollar::(CurrencyId::Token(RMRK)), DOT_DECIMALS); - assert_eq!(dollar::(CurrencyId::Token(MOVR)), DECIMAL_18); - }); -} - -#[test] -fn milli_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(milli::(CurrencyId::Token(ASG)), DECIMAL_12 / 1000); - assert_eq!(milli::(CurrencyId::Token(BNC)), DECIMAL_12 / 1000); - assert_eq!(milli::(CurrencyId::Token(KUSD)), DECIMAL_12 / 1000); - assert_eq!(milli::(CurrencyId::Token(DOT)), DOT_DECIMALS / 1000); - assert_eq!(milli::(CurrencyId::Token(KSM)), DECIMAL_12 / 1000); - assert_eq!(milli::(CurrencyId::Token(ETH)), DECIMAL_18 / 1000); - assert_eq!(milli::(CurrencyId::Token(KAR)), DECIMAL_12 / 1000); - assert_eq!(milli::(CurrencyId::Token(ZLK)), DECIMAL_18 / 1000); - assert_eq!(milli::(CurrencyId::Token(PHA)), DECIMAL_12 / 1000); - assert_eq!(milli::(CurrencyId::Token(RMRK)), DOT_DECIMALS / 1000); - assert_eq!(milli::(CurrencyId::Token(MOVR)), DECIMAL_18 / 1000); - }); -} - -#[test] -fn micro_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(micro::(CurrencyId::Token(ASG)), DECIMAL_12 / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(BNC)), DECIMAL_12 / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(KUSD)), DECIMAL_12 / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(DOT)), DOT_DECIMALS / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(KSM)), DECIMAL_12 / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(ETH)), DECIMAL_18 / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(KAR)), DECIMAL_12 / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(ZLK)), DECIMAL_18 / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(PHA)), DECIMAL_12 / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(RMRK)), DOT_DECIMALS / 1_000_000); - assert_eq!(micro::(CurrencyId::Token(MOVR)), DECIMAL_18 / 1_000_000); - }); -} - -#[test] -fn cent_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(cent::(CurrencyId::Token(ASG)), DECIMAL_12 / 100); - assert_eq!(cent::(CurrencyId::Token(BNC)), DECIMAL_12 / 100); - assert_eq!(cent::(CurrencyId::Token(KUSD)), DECIMAL_12 / 100); - assert_eq!(cent::(CurrencyId::Token(DOT)), DOT_DECIMALS / 100); - assert_eq!(cent::(CurrencyId::Token(KSM)), DECIMAL_12 / 100); - assert_eq!(cent::(CurrencyId::Token(ETH)), DECIMAL_18 / 100); - assert_eq!(cent::(CurrencyId::Token(KAR)), DECIMAL_12 / 100); - assert_eq!(cent::(CurrencyId::Token(ZLK)), DECIMAL_18 / 100); - assert_eq!(cent::(CurrencyId::Token(PHA)), DECIMAL_12 / 100); - assert_eq!(cent::(CurrencyId::Token(RMRK)), DOT_DECIMALS / 100); - assert_eq!(cent::(CurrencyId::Token(MOVR)), DECIMAL_18 / 100); - }); -} - -#[test] -fn millicent_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(millicent::(CurrencyId::Token(ASG)), DECIMAL_12 / 100_000); - assert_eq!(millicent::(CurrencyId::Token(BNC)), DECIMAL_12 / 100_000); - assert_eq!(millicent::(CurrencyId::Token(KUSD)), DECIMAL_12 / 100_000); - assert_eq!(millicent::(CurrencyId::Token(DOT)), DOT_DECIMALS / 100_000); - assert_eq!(millicent::(CurrencyId::Token(KSM)), DECIMAL_12 / 100_000); - assert_eq!(millicent::(CurrencyId::Token(ETH)), DECIMAL_18 / 100_000); - assert_eq!(millicent::(CurrencyId::Token(KAR)), DECIMAL_12 / 100_000); - assert_eq!(millicent::(CurrencyId::Token(ZLK)), DECIMAL_18 / 100_000); - assert_eq!(millicent::(CurrencyId::Token(PHA)), DECIMAL_12 / 100_000); - assert_eq!(millicent::(CurrencyId::Token(RMRK)), DOT_DECIMALS / 100_000); - assert_eq!(millicent::(CurrencyId::Token(MOVR)), DECIMAL_18 / 100_000); - }); -} - -#[test] -fn microcent_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(microcent::(CurrencyId::Token(ASG)), DECIMAL_12 / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(BNC)), DECIMAL_12 / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(KUSD)), DECIMAL_12 / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(DOT)), DOT_DECIMALS / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(KSM)), DECIMAL_12 / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(ETH)), DECIMAL_18 / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(KAR)), DECIMAL_12 / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(ZLK)), DECIMAL_18 / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(PHA)), DECIMAL_12 / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(RMRK)), DOT_DECIMALS / 100_000_000); - assert_eq!(microcent::(CurrencyId::Token(MOVR)), DECIMAL_18 / 100_000_000); - }); -} diff --git a/integration-tests/bifrost-kusama/src/general_key.rs b/integration-tests/bifrost-kusama/src/general_key.rs deleted file mode 100644 index a811dbd3f..000000000 --- a/integration-tests/bifrost-kusama/src/general_key.rs +++ /dev/null @@ -1,41 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use bifrost_primitives::{CurrencyId, TokenSymbol}; -use integration_tests_common::BifrostKusama; -use parity_scale_codec::Encode; -use sp_runtime::BoundedVec; -use xcm::prelude::*; -use xcm_emulator::TestExt; - -#[test] -fn dollar_should_work() { - BifrostKusama::execute_with(|| { - let id = CurrencyId::Token(TokenSymbol::KSM); - assert_eq!( - Junction::from(BoundedVec::try_from(id.encode()).unwrap()), - GeneralKey { - length: 2, - data: [ - 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0 - ] - } - ); - }); -} diff --git a/integration-tests/bifrost-kusama/src/salp.rs b/integration-tests/bifrost-kusama/src/salp.rs deleted file mode 100644 index 6124e97b8..000000000 --- a/integration-tests/bifrost-kusama/src/salp.rs +++ /dev/null @@ -1,843 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use crate::{kusama_integration_tests::*, kusama_test_net::*}; -use bifrost_asset_registry::AssetIdMaps; -use bifrost_kusama_runtime::{LeasePeriod, MinContribution, Runtime}; -use bifrost_salp::{Error, FundInfo, FundStatus}; -use frame_support::{assert_noop, assert_ok}; -use frame_system::RawOrigin; -use xcm_emulator::TestExt; - -const KSM: u128 = 1_000_000_000_000; - -#[test] -fn set_confirm_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::set_multisig_confirm_account( - RawOrigin::Root.into(), - AccountId::new(BOB) - )); - assert_eq!(Salp::multisig_confirm_account(), Some(AccountId::new(BOB)),); - }); - }) -} - -#[test] -fn create_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_eq!(AssetIdMaps::::check_token_registered(TokenSymbol::KSM), true); - assert_eq!( - AssetIdMaps::::check_vsbond_registered(TokenSymbol::KSM, 3000, 1, 8), - false - ); - // first_slot + 7 >= last_slot - assert_ok!(Salp::create( - RawOrigin::Root.into(), - //paraid - 3_000, - //cap - 100 * KSM, - //first_slot - 1, - //last_slot - SlotLength::get() - )); - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: Zero::zero(), - cap: 100 * KSM, - first_slot: 1, - last_slot: SlotLength::get(), - trie_index: 0, - status: FundStatus::Ongoing, - } - ); - assert_eq!( - AssetIdMaps::::check_vsbond_registered(TokenSymbol::KSM, 3000, 1, 8), - true - ); - }); - }) -} - -#[test] -fn edit_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create( - RawOrigin::Root.into(), - 3_000, - 100 * KSM, - 1, - SlotLength::get() - )); - - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: Zero::zero(), - cap: 100 * KSM, - first_slot: 1, - last_slot: SlotLength::get(), - trie_index: 0, - status: FundStatus::Ongoing, - } - ); - - assert_ok!(Salp::edit( - RawOrigin::Root.into(), - //paraid - 3_000, - //cap - 1000 * KSM, - //raised - 150, - //first_slot - 2, - //last_slot - SlotLength::get() + 1, - Some(FundStatus::Ongoing) - )); - - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 150, - cap: 1000 * KSM, - first_slot: 2, - last_slot: 9, - trie_index: 0, - status: FundStatus::Ongoing, - } - ); - }); - }) -} - -#[test] -fn contribute_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create( - RawOrigin::Root.into(), - 3_000, - 100 * KSM, - 1, - SlotLength::get() - )); - //MinContribution 0.1 KSM - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 1 * KSM - )); - //7200 1 day - let (contributed, status) = Salp::contribution(0, &AccountId::from(BOB)); - assert_eq!(contributed, 0); - assert_eq!(status.is_contributing(), true); - assert_eq!(status.contributing(), 1 * KSM); - //check free balance 9 ksm, should reserve 1 ksm - assert_eq!( - Currencies::free_balance( - CurrencyId::Token(TokenSymbol::KSM), - &AccountId::from(BOB) - ), - 9 * KSM - ); - - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - sp_runtime::AccountId32::from(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - - //check free balance 9 ksm - assert_eq!( - Currencies::free_balance( - CurrencyId::Token(TokenSymbol::KSM), - &AccountId::from(BOB) - ), - 9 * KSM - ); - - //check free balance 9 ksm - assert_eq!( - Currencies::free_balance( - CurrencyId::Token(TokenSymbol::KSM), - &AccountId::from(BOB) - ), - 9 * KSM - ); - - //check free balance 1 vsksm - assert_eq!( - Currencies::free_balance( - CurrencyId::VSToken(TokenSymbol::KSM), - &AccountId::from(BOB) - ), - 1 * KSM - ); - //check free balance 1 vsbondksm - assert_eq!( - Currencies::free_balance( - CurrencyId::VSBond(TokenSymbol::KSM, 3000, 1, 8), - &AccountId::from(BOB) - ), - 1 * KSM - ); - - let (contributed, status) = Salp::contribution(0, &sp_runtime::AccountId32::from(BOB)); - assert_eq!(contributed, 1 * KSM); - assert_eq!(status.is_contributing(), false); - assert_eq!(status.contributing(), 0); - - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 1 * KSM, - cap: 100 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::Ongoing, - } - ); - }); - }) -} - -#[test] -fn double_contribute_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 3_000, 5 * KSM, 1, SlotLength::get())); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 1 * KSM - )); - - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - - assert_noop!( - Salp::contribute(RuntimeOrigin::signed(AccountId::new(BOB)), 3_000, 5 * KSM), - Error::::CapExceeded - ); - - assert_noop!( - Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - MinContribution::get() - 1 - ), - Error::::ContributionTooSmall - ); - - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 2 * KSM - )); - - let (contributed, status) = Salp::contribution(0, &sp_runtime::AccountId32::from(BOB)); - assert_eq!(contributed, 1 * KSM); - assert_eq!(status.is_contributing(), true); - assert_eq!(status.contributing(), 2 * KSM); - - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 1 * KSM, - cap: 5 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::Ongoing, - } - ); - }); - }) -} - -#[test] -fn fund_fail_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 3_000, 5 * KSM, 1, SlotLength::get())); - // crownload is failed, so enable the withdrawal function of vsToken/vsBond - assert_ok!(Salp::fund_fail(RawOrigin::Root.into(), 3_000,)); - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 0, - cap: 5 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::Failed, - } - ); - }); - }) -} - -#[test] -fn fund_retire_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 3_000, 10 * KSM, 1, SlotLength::get())); - //Failed/Retired - assert_ok!(Salp::fund_success(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::fund_retire(RawOrigin::Root.into(), 3_000)); - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 0, - cap: 10 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::Retired, - } - ); - }); - }) -} - -#[test] -fn fund_retire_withdraw_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 3_000, 10 * KSM, 1, SlotLength::get())); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 1 * KSM - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - //Failed/Retired - assert_ok!(Salp::fund_success(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::fund_retire(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::withdraw(RawOrigin::Root.into(), 3_000)); - - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 1 * KSM, - cap: 10 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::RedeemWithdrew, - } - ); - assert_eq!(Salp::redeem_pool(), 1 * KSM); - }); - }) -} - -#[test] -fn fund_fail_withdraw_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 3_000, 10 * KSM, 1, SlotLength::get())); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 1 * KSM - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - //Failed/Retired - assert_ok!(Salp::fund_fail(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::withdraw(RawOrigin::Root.into(), 3_000)); - - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 1 * KSM, - cap: 10 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::RefundWithdrew, - } - ); - assert_eq!(Salp::redeem_pool(), 1 * KSM); - }); - }) -} - -#[test] -fn continue_fund_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 3_000, 10 * KSM, 1, SlotLength::get())); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 1 * KSM - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - //Failed/Retired - assert_ok!(Salp::fund_fail(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::withdraw(RawOrigin::Root.into(), 3_000)); - - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 1 * KSM, - cap: 10 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::RefundWithdrew, - } - ); - assert_eq!(Salp::redeem_pool(), 1 * KSM); - - assert_ok!(Salp::continue_fund(RawOrigin::Root.into(), 3_000, 2, 9)); - assert_eq!( - Salp::failed_funds_to_refund((3_000, 1, 8)).unwrap(), - FundInfo { - raised: 1 * KSM, - cap: 10 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::FailedToContinue, - } - ); - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 1 * KSM, - cap: 10 * KSM, - first_slot: 2, - last_slot: 9, - trie_index: 0, - status: FundStatus::Ongoing, - } - ); - }); - }) -} - -#[test] -fn refund_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 3_000, 10 * KSM, 1, SlotLength::get())); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 1 * KSM - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - //check free balance 1 vsksm - assert_eq!( - Currencies::free_balance( - CurrencyId::VSToken(TokenSymbol::KSM), - &AccountId::from(BOB) - ), - 1 * KSM - ); - //check free balance 1 vsbondksm - assert_eq!( - Currencies::free_balance( - CurrencyId::VSBond(TokenSymbol::KSM, 3000, 1, 8), - &AccountId::from(BOB) - ), - 1 * KSM - ); - assert_ok!(Salp::fund_fail(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::withdraw(RawOrigin::Root.into(), 3_000)); - //fund_fail-> withdraw -> RefundWithdrew - assert_ok!(Salp::refund( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 1, - SlotLength::get(), - KSM / 2 - )); - - //check free balance 0.5 vsksm - assert_eq!( - Currencies::free_balance( - CurrencyId::VSToken(TokenSymbol::KSM), - &AccountId::from(BOB) - ), - KSM / 2 - ); - //check free balance 0.5 vsbondksm - assert_eq!( - Currencies::free_balance( - CurrencyId::VSBond(TokenSymbol::KSM, 3000, 1, 8), - &AccountId::from(BOB) - ), - KSM / 2 - ); - //check free balance 0.5 ksm - assert_eq!(Salp::redeem_pool(), KSM / 2); - - //check funds - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 1 * KSM - KSM / 2, - cap: 10 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::RefundWithdrew, - } - ); - - //check free balance 9.5 ksm - assert_eq!( - Currencies::free_balance( - CurrencyId::Token(TokenSymbol::KSM), - &AccountId::from(BOB) - ), - 9 * KSM + KSM / 2 - ); - }); - }) -} - -#[test] -fn redeem_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 3_000, 10 * KSM, 1, SlotLength::get())); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 1 * KSM - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - //Failed/Retired - assert_ok!(Salp::fund_success(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::fund_retire(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::withdraw(RawOrigin::Root.into(), 3_000)); - - //check free balance 1 vsksm - assert_eq!( - Currencies::free_balance( - CurrencyId::VSToken(TokenSymbol::KSM), - &AccountId::from(BOB) - ), - 1 * KSM - ); - //check free balance 1 vsbondksm - assert_eq!( - Currencies::free_balance( - CurrencyId::VSBond(TokenSymbol::KSM, 3000, 1, 8), - &AccountId::from(BOB) - ), - 1 * KSM - ); - - assert_ok!(Salp::redeem(RuntimeOrigin::signed(AccountId::new(BOB)), 3_000, KSM / 2)); - - //check free balance 0.5 ksm - assert_eq!(Salp::redeem_pool(), KSM / 2); - - //check funds - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 1 * KSM - KSM / 2, - cap: 10 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::RedeemWithdrew, - } - ); - //check free balance 9.5 ksm - assert_eq!( - Currencies::free_balance( - CurrencyId::Token(TokenSymbol::KSM), - &AccountId::from(BOB) - ), - 9 * KSM + KSM / 2 - ); - }); - }) -} - -#[test] -fn redeem_with_speical_vsbond_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 2001, 1000_000_000_000, 13, 20)); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 2001, - 100_000_000_000 - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 2001, - true, - CONTRIBUTON_INDEX - )); - - assert_ok!(Salp::fund_success(RawOrigin::Root.into(), 2001)); - assert_ok!(Salp::unlock( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 2001 - )); - - // Mock the BlockNumber - let block_begin_redeem = (SlotLength::get() + 1) * LeasePeriod::get(); - System::set_block_number(block_begin_redeem); - - assert_ok!(Salp::fund_retire(RawOrigin::Root.into(), 2001)); - assert_ok!(Salp::withdraw(RawOrigin::Root.into(), 2001)); - - let vs_token = - ::CurrencyIdConversion::convert_to_vstoken( - RelayCurrencyId::get(), - ) - .unwrap(); - let vs_bond = - ::CurrencyIdConversion::convert_to_vsbond( - RelayCurrencyId::get(), - 2001, - 13, - 20, - ) - .unwrap(); - - assert_ok!(>::transfer( - vs_token, - &AccountId::new(BOB), - &AccountId::new(CATHI), - 500_000_000 - )); - assert_ok!(>::transfer( - vs_bond, - &AccountId::new(BOB), - &AccountId::new(CATHI), - 500_000_000 - )); - assert_ok!(Salp::redeem(RuntimeOrigin::signed(AccountId::new(BOB)), 2001, 500_000_000)); - assert_ok!(Salp::redeem( - RuntimeOrigin::signed(AccountId::new(CATHI)), - 2001, - 500_000_000 - )); - }); - }) -} - -#[test] -fn dissolve_refunded_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create(RawOrigin::Root.into(), 3_000, 10 * KSM, 1, SlotLength::get())); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 1 * KSM - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - //Failed/Retired - assert_ok!(Salp::fund_fail(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::withdraw(RawOrigin::Root.into(), 3_000)); - - assert_eq!( - Salp::funds(3_000).unwrap(), - FundInfo { - raised: 1 * KSM, - cap: 10 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::RefundWithdrew, - } - ); - assert_eq!(Salp::redeem_pool(), 1 * KSM); - - assert_ok!(Salp::continue_fund(RawOrigin::Root.into(), 3_000, 2, 9)); - assert_eq!( - Salp::failed_funds_to_refund((3_000, 1, 8)).unwrap(), - FundInfo { - raised: 1 * KSM, - cap: 10 * KSM, - first_slot: 1, - last_slot: 8, - trie_index: 0, - status: FundStatus::FailedToContinue, - } - ); - - assert_ok!(Salp::dissolve_refunded(RawOrigin::Root.into(), 3_000, 1, 8)); - - assert_eq!(Salp::failed_funds_to_refund((3_000, 1, 8)), None); - }); - }) -} - -#[test] -fn dissolve_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create( - RawOrigin::Root.into(), - 3_000, - 1000_000_000_000, - 1, - SlotLength::get() - )); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 100_000_000_000 - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - assert_ok!(Salp::fund_success(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::fund_retire(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::withdraw(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::fund_end(RawOrigin::Root.into(), 3_000)); - - assert_ok!(Salp::dissolve(RawOrigin::Root.into(), 3_000)); - - assert!(Salp::funds(3_000).is_none()); - }); - }) -} - -#[test] -fn batch_unlock_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create( - RawOrigin::Root.into(), - 3_000, - 1000_000_000_000, - 1, - SlotLength::get() - )); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 100_000_000_000 - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - - assert_ok!(Salp::fund_success(RawOrigin::Root.into(), 3_000)); - assert_ok!(Salp::batch_unlock(RuntimeOrigin::signed(AccountId::new(ALICE)), 3_000)); - }) - }) -} - -#[test] -fn unlock_when_fund_ongoing_should_work() { - sp_io::TestExternalities::default().execute_with(|| { - Bifrost::execute_with(|| { - assert_ok!(Salp::create( - RawOrigin::Root.into(), - 3_000, - 1000_000_000_000, - 1, - SlotLength::get() - )); - assert_ok!(Salp::contribute( - RuntimeOrigin::signed(AccountId::new(BOB)), - 3_000, - 100_000_000_000 - )); - assert_ok!(Salp::confirm_contribute( - RuntimeOrigin::signed(AccountId::new(ALICE)), - AccountId::new(BOB), - 3_000, - true, - CONTRIBUTON_INDEX - )); - assert_ok!(Salp::unlock( - RuntimeOrigin::signed(AccountId::new(BOB)), - AccountId::new(BOB), - 3_000 - )); - }); - }) -} diff --git a/integration-tests/bifrost-kusama/src/slp.rs b/integration-tests/bifrost-kusama/src/slp.rs deleted file mode 100644 index 5e1b10a3b..000000000 --- a/integration-tests/bifrost-kusama/src/slp.rs +++ /dev/null @@ -1,1079 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -//! Cross-chain transfer tests within Kusama network. - -use bifrost_kusama_runtime::{ - Balances, Currencies, NativeCurrencyId, RelayCurrencyId, Runtime, RuntimeOrigin, Slp, Tokens, - VtokenMinting, XcmDestWeightAndFeeHandler, -}; -use bifrost_primitives::{TimeUnit, XcmOperationType as XcmOperation, KSM, VKSM}; -use bifrost_slp::{primitives::UnlockChunk, Delays, Ledger, MinimumsMaximums, SubstrateLedger}; -use frame_support::{assert_ok, BoundedVec}; -use integration_tests_common::{impls::AccountId, BifrostKusama, Kusama}; -use orml_traits::MultiCurrency; -use sp_runtime::Permill; -use xcm::{prelude::*, v3::Weight, VersionedMultiAssets, VersionedMultiLocation}; -use xcm_emulator::{assert_expected_events, Chain, ParaId, TestExt}; - -pub const ALICE: [u8; 32] = - hex_literal::hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"]; -pub const BOB: [u8; 32] = - hex_literal::hex!["8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48"]; -pub const KUSAMA_ALICE_STASH_ACCOUNT: [u8; 32] = - hex_literal::hex!["be5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f"]; -pub const KUSAMA_BOB_STASH_ACCOUNT: [u8; 32] = - hex_literal::hex!["fe65717dad0447d715f660a0a58411de509b42e6efb8375f562f58a554d5860e"]; -const ENTRANCE_ACCOUNT: [u8; 32] = - hex_literal::hex!["6d6f646c62662f76746b696e0000000000000000000000000000000000000000"]; -const BIFROST_TREASURY_ACCOUNT: [u8; 32] = - hex_literal::hex!["6d6f646c62662f74727372790000000000000000000000000000000000000000"]; -const KSM_DELEGATOR_0_ACCOUNT: [u8; 32] = - hex_literal::hex!["5a53736d8e96f1c007cf0d630acf5209b20611617af23ce924c8e25328eb5d28"]; - -const EXIT_ACCOUNT: [u8; 32] = - hex_literal::hex!["6d6f646c62662f76746f75740000000000000000000000000000000000000000"]; - -const BIFROST_TREASURY_MULTILOCATION: MultiLocation = MultiLocation { - parents: 0, - interior: X1(AccountId32 { network: None, id: BIFROST_TREASURY_ACCOUNT }), -}; -const KSM_DELEGATOR_0_MULTILOCATION: MultiLocation = MultiLocation { - parents: 1, - interior: X1(AccountId32 { network: None, id: KSM_DELEGATOR_0_ACCOUNT }), -}; - -const ENTRANCE_ACCOUNT_MULTILOCATION: MultiLocation = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: ENTRANCE_ACCOUNT }) }; - -const EXIT_ACCOUNT_MULTILOCATION: MultiLocation = - MultiLocation { parents: 0, interior: X1(AccountId32 { network: None, id: EXIT_ACCOUNT }) }; - -const KUSAMA_ALICE_MULTILOCATION: MultiLocation = - MultiLocation { parents: 1, interior: X1(AccountId32 { network: None, id: ALICE }) }; -const KUSAMA_ALICE_STASH_MULTILOCATION: MultiLocation = MultiLocation { - parents: 1, - interior: X1(AccountId32 { network: None, id: KUSAMA_ALICE_STASH_ACCOUNT }), -}; -const KUSAMA_BOB_STASH_MULTILOCATION: MultiLocation = MultiLocation { - parents: 1, - interior: X1(AccountId32 { network: None, id: KUSAMA_BOB_STASH_ACCOUNT }), -}; - -const KSM_DECIMALS: u128 = 1_000_000_000_000; -const BNC_DECIMALS: u128 = 1_000_000_000_000; - -/// **************************************************** -/// ********* Preparation section ******************** -/// **************************************************** - -// Preparation: register sub-account index 0. -fn slp_setup() { - cross_ksm_to_bifrost(BIFROST_TREASURY_ACCOUNT, 10000 * KSM_DECIMALS); - // cross_ksm_to_bifrost(ENTRANCE_ACCOUNT, 10000 * KSM_DECIMALS); - cross_ksm_to_bifrost(ALICE, 10000 * KSM_DECIMALS); - cross_ksm_to_bifrost(BOB, 10000 * KSM_DECIMALS); - - Kusama::execute_with(|| { - assert_ok!(kusama_runtime::Balances::force_set_balance( - kusama_runtime::RuntimeOrigin::root(), - sp_runtime::MultiAddress::Id(AccountId::from(KSM_DELEGATOR_0_ACCOUNT)), - 10000 * KSM_DECIMALS - )); - kusama_runtime::System::reset_events(); - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - sp_runtime::MultiAddress::Id(AccountId::from(BIFROST_TREASURY_ACCOUNT)), - 10000 * BNC_DECIMALS - )); - assert_ok!(Tokens::set_balance( - RuntimeOrigin::root(), - sp_runtime::MultiAddress::Id(AccountId::from(ALICE)), - KSM, - 10000 * KSM_DECIMALS, - 0 - )); - }); - - BifrostKusama::execute_with(|| { - // set operate origin to be ALICE for vksm - assert_ok!(Slp::set_operate_origin( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Some(AccountId::from(ALICE)) - )); - // Set OngoingTimeUnitUpdateInterval as 1/3 Era(1800 blocks per Era, 12 seconds per - // block) - assert_ok!(Slp::set_ongoing_time_unit_update_interval( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Some(1) - )); - // Initialize ongoing timeunit as 0. - assert_ok!(Slp::update_ongoing_time_unit( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - TimeUnit::Era(0) - )); - assert_ok!(Slp::set_ongoing_time_unit_update_interval( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Some(600) - )); - - // set fee_source for ksm to be treasury - assert_ok!(Slp::set_fee_source( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Some((BIFROST_TREASURY_MULTILOCATION, 1 * KSM_DECIMALS)) - )); - // set fee_source for ksm to be treasury - assert_ok!(Slp::set_fee_source( - RuntimeOrigin::root(), - NativeCurrencyId::get(), - Some((BIFROST_TREASURY_MULTILOCATION, 1 * BNC_DECIMALS)) - )); - - let mins_and_maxs = MinimumsMaximums { - delegator_bonded_minimum: KSM_DECIMALS / 10, - bond_extra_minimum: KSM_DECIMALS / 1000, - unbond_minimum: KSM_DECIMALS / 1000, - rebond_minimum: KSM_DECIMALS / 1000, - unbond_record_maximum: 32, - validators_back_maximum: 24, - delegator_active_staking_maximum: 80000 * KSM_DECIMALS, - validators_reward_maximum: 256, - delegation_amount_minimum: KSM_DECIMALS / 1000, - delegators_maximum: 100, - validators_maximum: 300, - }; - - // Set minimums and maximums - assert_ok!(Slp::set_minimums_and_maximums( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Some(mins_and_maxs) - )); - - // Initialize currency delays. - let delay = - Delays { unlock_delay: TimeUnit::Era(0), leave_delegators_delay: TimeUnit::Era(0) }; - assert_ok!(Slp::set_currency_delays( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Some(delay) - )); - - assert_ok!(Slp::set_hosting_fees( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Some((Permill::from_parts(1000), BIFROST_TREASURY_MULTILOCATION)) - )); - - assert_ok!(Slp::set_currency_tune_exchange_rate_limit( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Some((10, Permill::from_parts(1000))) - )); - - // add Alice and Bob to validators - assert_ok!(Slp::add_validator( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Box::new(KUSAMA_ALICE_STASH_MULTILOCATION), - )); - assert_ok!(Slp::add_validator( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Box::new(KUSAMA_BOB_STASH_MULTILOCATION), - )); - - // Register Operation weight and fee - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::TransferTo, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::Bond, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::BondExtra, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::Unbond, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::Rebond, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::Delegate, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::Payout, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::Liquidize, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::Chill, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - assert_ok!( - ::XcmWeightAndFeeHandler::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::TransferBack, - Some((Weight::from_parts(10000000000, 1000000), 10_000_000_000)), - ) - ); - - // initialize two delegators - assert_ok!(Slp::initialize_delegator(RuntimeOrigin::root(), RelayCurrencyId::get(), None)); - - bifrost_kusama_runtime::System::reset_events(); - }); -} - -fn cross_ksm_to_bifrost(to: [u8; 32], amount: u128) { - Kusama::execute_with(|| { - assert_ok!(kusama_runtime::Balances::force_set_balance( - kusama_runtime::RuntimeOrigin::root(), - sp_runtime::MultiAddress::Id(AccountId::from(to)), - amount - )); - assert_ok!(kusama_runtime::XcmPallet::reserve_transfer_assets( - kusama_runtime::RuntimeOrigin::signed(to.into()), - Box::new(VersionedMultiLocation::V3(X1(Parachain(2001)).into())), - Box::new(VersionedMultiLocation::V3( - X1(Junction::AccountId32 { id: to, network: None }).into() - )), - Box::new(VersionedMultiAssets::V3((Here, amount / 10).into())), - 0, - )); - }); -} - -#[test] -fn vtoken_minting() { - sp_io::TestExternalities::default().execute_with(|| { - slp_setup(); - BifrostKusama::execute_with(|| { - assert_eq!(Currencies::free_balance(VKSM, &AccountId::from(ALICE)), 0); - assert_eq!( - Currencies::free_balance(KSM, &AccountId::from(ALICE)), - 10000 * KSM_DECIMALS - ); - assert_ok!(VtokenMinting::mint( - RuntimeOrigin::signed(AccountId::from(ALICE)), - KSM, - 100 * KSM_DECIMALS, - BoundedVec::default(), - None - )); - // alice account should have 99.9 vKSM - assert_eq!(Currencies::free_balance(VKSM, &AccountId::from(ALICE)), 100 * KSM_DECIMALS); - assert_eq!( - Currencies::free_balance(KSM, &AccountId::from(ENTRANCE_ACCOUNT)), - 100 * KSM_DECIMALS - ); - assert_eq!(Currencies::free_balance(KSM, &AccountId::from(ALICE)), 9900 * KSM_DECIMALS); - }) - }); -} - -#[test] -fn transfer_to() { - slp_setup(); - - Kusama::execute_with(|| { - assert_eq!( - kusama_runtime::Balances::free_balance(&AccountId::from(KSM_DELEGATOR_0_ACCOUNT)), - 10000 * KSM_DECIMALS - ); - }); - - BifrostKusama::execute_with(|| { - // Bond 50 ksm for sub-account index 0 - assert_ok!(VtokenMinting::mint( - RuntimeOrigin::signed(AccountId::from(ALICE)), - KSM, - 100 * KSM_DECIMALS, - BoundedVec::default(), - None - )); - - assert_ok!(Slp::transfer_to( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(ENTRANCE_ACCOUNT_MULTILOCATION), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - )); - - assert_eq!( - Currencies::free_balance(KSM, &AccountId::from(ENTRANCE_ACCOUNT)), - 50 * KSM_DECIMALS - ); - }); - - Kusama::execute_with(|| { - assert_eq!( - kusama_runtime::Balances::free_balance(&AccountId::from(KSM_DELEGATOR_0_ACCOUNT)), - 10050009921672574 - ); - }); -} - -#[test] -fn transfer_back() { - slp_setup(); - Kusama::execute_with(|| { - assert_eq!( - kusama_runtime::Balances::free_balance(&AccountId::from(KSM_DELEGATOR_0_ACCOUNT)), - 10000 * KSM_DECIMALS - ); - }); - - BifrostKusama::execute_with(|| { - // Bond 50 ksm for sub-account index 0 - assert_eq!(Currencies::free_balance(KSM, &AccountId::from(EXIT_ACCOUNT)), 0); - - assert_ok!(Slp::transfer_back( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - Box::new(EXIT_ACCOUNT_MULTILOCATION), - 50 * KSM_DECIMALS, - None - )); - }); - - Kusama::execute_with(|| { - assert_eq!( - kusama_runtime::Balances::free_balance(&AccountId::from(KSM_DELEGATOR_0_ACCOUNT)), - 9949998630000371 - ); - }); - - BifrostKusama::execute_with(|| { - assert_eq!(Currencies::free_balance(KSM, &AccountId::from(EXIT_ACCOUNT)), 49999919630000); - }); -} - -#[test] -fn bond_works() { - sp_io::TestExternalities::default().execute_with(|| { - slp_setup(); - - BifrostKusama::execute_with(|| { - // Bond 50 ksm for sub-account index 0 - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None, - )); - }); - - Kusama::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - assert_expected_events!( - Kusama, - vec![ - RuntimeEvent::Staking(pallet_staking::Event::Bonded { stash, amount}) => { - stash: *stash == AccountId::from(KSM_DELEGATOR_0_ACCOUNT), - amount: *amount == 50 * KSM_DECIMALS, - }, - ] - ); - }); - - BifrostKusama::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - // Bond 50 ksm and auto confirm - assert_expected_events!( - BifrostKusama, - vec![ - // Amount to reserve transfer is transferred to System Parachain's Sovereign account - RuntimeEvent::Slp(bifrost_slp::Event::DelegatorLedgerQueryResponseConfirmed {..}) => { }, - ] - ); - assert_eq!( - Slp::get_delegator_ledger(RelayCurrencyId::get(), KSM_DELEGATOR_0_MULTILOCATION), - Some(Ledger::Substrate(SubstrateLedger { - account: KSM_DELEGATOR_0_MULTILOCATION, - total: 50 * KSM_DECIMALS, - active: 50 * KSM_DECIMALS, - unlocking: vec![], - })) - ); - }); - }) -} - -#[test] -fn bond_extra_works() { - sp_io::TestExternalities::default().execute_with(|| { - slp_setup(); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None, - )); - }); - BifrostKusama::execute_with(|| { - // Bond_extra 20 ksm for sub-account index 0 - assert_ok!(Slp::bond_extra( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - None, - 20 * KSM_DECIMALS, - None - )); - }); - - Kusama::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - assert_expected_events!( - Kusama, - vec![ - RuntimeEvent::Staking(pallet_staking::Event::Bonded { stash, amount}) => { - stash: *stash == AccountId::from(KSM_DELEGATOR_0_ACCOUNT), - amount: *amount == 20 * KSM_DECIMALS, - }, - ] - ); - }); - - BifrostKusama::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - // Bond 20 ksm and auto confirm - assert_expected_events!( - BifrostKusama, - vec![ - RuntimeEvent::Slp(bifrost_slp::Event::DelegatorLedgerQueryResponseConfirmed {..}) => { }, - ] - ); - assert_eq!( - Slp::get_delegator_ledger(RelayCurrencyId::get(), KSM_DELEGATOR_0_MULTILOCATION), - Some(Ledger::Substrate(SubstrateLedger { - account: KSM_DELEGATOR_0_MULTILOCATION, - total: 70 * KSM_DECIMALS, - active: 70 * KSM_DECIMALS, - unlocking: vec![], - })) - ); - }); - }) -} - -#[test] -fn unbond_works() { - slp_setup(); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None, - )); - }); - - Kusama::execute_with(|| {}); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::unbond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - None, - 20 * KSM_DECIMALS, - None - )); - }); - - Kusama::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - assert_expected_events!( - Kusama, - vec![ - RuntimeEvent::Staking(pallet_staking::Event::Unbonded { stash, amount}) => { - stash: *stash == AccountId::from(KSM_DELEGATOR_0_ACCOUNT), - amount: *amount == 20 * KSM_DECIMALS, - }, - ] - ); - }); - - BifrostKusama::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - assert_expected_events!( - BifrostKusama, - vec![ - // Amount to reserve transfer is transferred to System Parachain's Sovereign account - RuntimeEvent::Slp(bifrost_slp::Event::DelegatorLedgerQueryResponseConfirmed {..}) => { }, - ] - ); - assert_eq!( - Slp::get_delegator_ledger(RelayCurrencyId::get(), KSM_DELEGATOR_0_MULTILOCATION), - Some(Ledger::Substrate(SubstrateLedger { - account: KSM_DELEGATOR_0_MULTILOCATION, - total: 50 * KSM_DECIMALS, - active: 30 * KSM_DECIMALS, - unlocking: vec![UnlockChunk { - value: 20 * KSM_DECIMALS, - unlock_time: TimeUnit::Era(0) - }], - })) - ); - }); -} - -#[test] -fn unbond_all_works() { - slp_setup(); - - BifrostKusama::execute_with(|| { - // Unbond 0.5 ksm, 0.5 ksm left. - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None, - )); - }); - - Kusama::execute_with(|| {}); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::unbond_all( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - None - )); - }); - - Kusama::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - assert_expected_events!( - Kusama, - vec![ - RuntimeEvent::Staking(pallet_staking::Event::Unbonded { stash, amount}) => { - stash: *stash == AccountId::from(KSM_DELEGATOR_0_ACCOUNT), - amount: *amount == 20 * KSM_DECIMALS, - }, - ] - ); - }); - - BifrostKusama::execute_with(|| { - // Bond 70 ksm and auto confirm - assert_eq!( - Slp::get_delegator_ledger(RelayCurrencyId::get(), KSM_DELEGATOR_0_MULTILOCATION), - Some(Ledger::Substrate(SubstrateLedger { - account: KSM_DELEGATOR_0_MULTILOCATION, - total: 50 * KSM_DECIMALS, - active: 0, - unlocking: vec![UnlockChunk { - value: 50 * KSM_DECIMALS, - unlock_time: TimeUnit::Era(0) - }], - })) - ); - }); -} - -#[test] -fn rebond_works() { - slp_setup(); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None, - )); - }); - - Kusama::execute_with(|| { - // TODO: Assert events; - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::unbond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - None, - 30 * KSM_DECIMALS, - None - )); - }); - - Kusama::execute_with(|| { - // TODO: Assert events; - }); - - BifrostKusama::execute_with(|| { - // rebond 0.5 ksm. - assert_ok!(Slp::rebond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - None, - Some(20 * KSM_DECIMALS), - None - )); - }); - - // So the bonded amount should be 1 ksm - Kusama::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - assert_expected_events!( - Kusama, - vec![ - RuntimeEvent::Staking(pallet_staking::Event::Bonded { stash, amount}) => { - stash: *stash == AccountId::from(KSM_DELEGATOR_0_ACCOUNT), - amount: *amount == 20 * KSM_DECIMALS, - }, - ] - ); - }); - - BifrostKusama::execute_with(|| { - // Bond 70 ksm and auto confirm - assert_eq!( - Slp::get_delegator_ledger(RelayCurrencyId::get(), KSM_DELEGATOR_0_MULTILOCATION), - Some(Ledger::Substrate(SubstrateLedger { - account: KSM_DELEGATOR_0_MULTILOCATION, - total: 50 * KSM_DECIMALS, - active: 40 * KSM_DECIMALS, - unlocking: vec![UnlockChunk { - value: 10 * KSM_DECIMALS, - unlock_time: TimeUnit::Era(0) - }], - })) - ); - }); -} - -#[test] -fn delegate_works() { - sp_io::TestExternalities::default().execute_with(|| { - // bond 1 ksm for sub-account index 0 - slp_setup(); - - Kusama::execute_with(|| { - use kusama_runtime::System; - System::reset_events(); - }); - - BifrostKusama::execute_with(|| { - // Unbond 0.5 ksm, 0.5 ksm left. - assert_ok!(VtokenMinting::mint( - RuntimeOrigin::signed(AccountId::from(ALICE)), - KSM, - 100 * KSM_DECIMALS, - BoundedVec::default(), - None - )); - - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None, - )); - }); - - Kusama::execute_with(|| {}); - - BifrostKusama::execute_with(|| { - // delegate - assert_ok!(Slp::delegate( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - vec![KUSAMA_ALICE_STASH_MULTILOCATION, KUSAMA_BOB_STASH_MULTILOCATION], - None - )); - }); - - Kusama::execute_with(|| { - Kusama::assert_ump_queue_processed(true, Some(ParaId::new(2001)), None); - }); - }) -} - -#[test] -fn undelegate_works() { - slp_setup(); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None, - )); - }); - - Kusama::execute_with(|| { - // TODO: Assert events; - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::delegate( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - vec![KUSAMA_ALICE_STASH_MULTILOCATION, KUSAMA_BOB_STASH_MULTILOCATION], - None - )); - }); - - Kusama::execute_with(|| { - // TODO: Assert events; - }); - - BifrostKusama::execute_with(|| { - // Undelegate validator 0. Only validator 1 left. - assert_ok!(Slp::undelegate( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - vec![KUSAMA_ALICE_STASH_MULTILOCATION], - None - )); - }); - - Kusama::execute_with(|| { - Kusama::assert_ump_queue_processed(true, Some(ParaId::new(2001)), None); - }); -} - -#[test] -fn redelegate_works() { - slp_setup(); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None, - )); - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::delegate( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - vec![KUSAMA_ALICE_STASH_MULTILOCATION, KUSAMA_BOB_STASH_MULTILOCATION], - None - )); - }); - - Kusama::execute_with(|| { - // TODO: Assert events; - }); - - BifrostKusama::execute_with(|| { - // Undelegate validator 0. Only validator 1 left. - assert_ok!(Slp::undelegate( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - vec![KUSAMA_ALICE_STASH_MULTILOCATION], - None - )); - }); - - Kusama::execute_with(|| { - // TODO: Assert events; - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::redelegate( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - Some(vec![KUSAMA_ALICE_STASH_MULTILOCATION, KUSAMA_BOB_STASH_MULTILOCATION]), - None - )); - }); - - Kusama::execute_with(|| { - Kusama::assert_ump_queue_processed(true, Some(ParaId::new(2001)), None); - }); -} - -#[test] -fn payout_works() { - slp_setup(); - BifrostKusama::execute_with(|| { - // Bond 1 ksm for sub-account index 0 - assert_ok!(Slp::payout( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - Box::new(KUSAMA_ALICE_STASH_MULTILOCATION), - Some(TimeUnit::Era(27)), - None - )); - }); -} - -#[test] -fn liquidize_works() { - slp_setup(); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None, - )); - }); - - Kusama::execute_with(|| { - // TODO: Assert events; - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::delegate( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - vec![KUSAMA_ALICE_STASH_MULTILOCATION, KUSAMA_BOB_STASH_MULTILOCATION], - None - )); - }); - - Kusama::execute_with(|| { - // TODO: Assert events; - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::unbond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - None, - 20 * KSM_DECIMALS, - None - )); - }); - - Kusama::execute_with(|| { - // TODO: Assert events; - }); - - BifrostKusama::execute_with(|| { - // Bond 70 ksm and auto confirm - assert_eq!( - Slp::get_delegator_ledger(RelayCurrencyId::get(), KSM_DELEGATOR_0_MULTILOCATION), - Some(Ledger::Substrate(SubstrateLedger { - account: KSM_DELEGATOR_0_MULTILOCATION, - total: 50 * KSM_DECIMALS, - active: 30 * KSM_DECIMALS, - unlocking: vec![UnlockChunk { - value: 20 * KSM_DECIMALS, - unlock_time: TimeUnit::Era(0) - }], - })) - ); - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::liquidize( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - Some(TimeUnit::SlashingSpan(5)), - None, - None, - None - )); - }); - - Kusama::execute_with(|| { - Kusama::assert_ump_queue_processed(true, Some(ParaId::new(2001)), None); - }); - - BifrostKusama::execute_with(|| { - assert_eq!( - Slp::get_delegator_ledger(RelayCurrencyId::get(), KSM_DELEGATOR_0_MULTILOCATION), - Some(Ledger::Substrate(SubstrateLedger { - account: KSM_DELEGATOR_0_MULTILOCATION, - total: 30 * KSM_DECIMALS, - active: 30 * KSM_DECIMALS, - unlocking: vec![], - })) - ); - }); -} - -#[test] -fn chill_works() { - sp_io::TestExternalities::default().execute_with(|| { - slp_setup(); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::bond( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - 50 * KSM_DECIMALS, - None, - None - )); - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::delegate( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - vec![KUSAMA_ALICE_STASH_MULTILOCATION, KUSAMA_BOB_STASH_MULTILOCATION], - None - )); - }); - - // check if sub-account index 0 belongs to the group of nominators - Kusama::execute_with(|| { - assert_eq!( - kusama_runtime::Staking::ledger(AccountId::from(KSM_DELEGATOR_0_ACCOUNT).into()) - .is_ok(), - true - ); - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::chill( - RuntimeOrigin::signed(AccountId::from(ALICE)), - RelayCurrencyId::get(), - Box::new(KSM_DELEGATOR_0_MULTILOCATION), - None - )); - }); - - // check if sub-account index 0 belongs to the group of nominators - Kusama::execute_with(|| {}); - }) -} - -#[test] -fn supplement_fee_reserve_works() { - sp_io::TestExternalities::default().execute_with(|| { - slp_setup(); - Kusama::execute_with(|| { - assert_eq!( - kusama_runtime::Balances::free_balance(&AccountId::from(KSM_DELEGATOR_0_ACCOUNT)), - 10000 * KSM_DECIMALS - ); - }); - - BifrostKusama::execute_with(|| { - assert_ok!(Slp::supplement_fee_reserve( - RuntimeOrigin::root(), - RelayCurrencyId::get(), - Box::new(KUSAMA_ALICE_MULTILOCATION), - )); - }); - - Kusama::execute_with(|| { - assert_eq!( - kusama_runtime::Balances::free_balance(&AccountId::from(KSM_DELEGATOR_0_ACCOUNT)), - 10000 * KSM_DECIMALS - ); - }); - }) -} diff --git a/integration-tests/bifrost-kusama/src/total_issuance.rs b/integration-tests/bifrost-kusama/src/total_issuance.rs deleted file mode 100644 index 3dec79e52..000000000 --- a/integration-tests/bifrost-kusama/src/total_issuance.rs +++ /dev/null @@ -1,51 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use bifrost_kusama_runtime::{ - constants::currency::{BNCS, MILLIBNC}, - Balances, RuntimeOrigin, -}; -use frame_support::{assert_ok, traits::Currency}; -use integration_tests_common::{ - BifrostKusama, BifrostKusamaAlice, BifrostKusamaBob, BifrostKusamaTreasury, -}; -use xcm_emulator::TestExt; - -#[test] -fn remove_dust_account_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(Balances::minimum_balance(), 10 * MILLIBNC); - - assert_eq!(Balances::total_issuance(), 8_000_0000 * BNCS); - - assert_ok!(Balances::transfer_allow_death( - RuntimeOrigin::signed(BifrostKusamaAlice::get()), - BifrostKusamaBob::get().into(), - Balances::free_balance(&BifrostKusamaAlice::get()) - MILLIBNC - )); - - // As expected dust balance is removed. - assert_eq!(Balances::free_balance(&BifrostKusamaAlice::get()), 0); - assert_eq!( - Balances::free_balance(&BifrostKusamaTreasury::get()), - 1_000_0000 * BNCS + MILLIBNC - ); - - assert_eq!(Balances::total_issuance(), 8_000_0000 * BNCS); - }); -} diff --git a/integration-tests/bifrost-kusama/src/transact.rs b/integration-tests/bifrost-kusama/src/transact.rs deleted file mode 100644 index b5506c994..000000000 --- a/integration-tests/bifrost-kusama/src/transact.rs +++ /dev/null @@ -1,141 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use crate::vtoken_voting::set_balance_proposal_bounded; -use bifrost_kusama_runtime::{Runtime, RuntimeCall, RuntimeEvent, System}; -use bifrost_primitives::Balance; -use frame_support::{ - assert_ok, - dispatch::{GetDispatchInfo, RawOrigin}, -}; -use integration_tests_common::{BifrostKusama, Kusama, KusamaAlice}; -use pallet_conviction_voting::{AccountVote, Vote}; -use parity_scale_codec::Encode; -use xcm::v3::{prelude::*, Weight}; -use xcm_emulator::{bx, Parachain, RelayChain, TestExt}; - -#[test] -fn relaychain_transact_works() { - let vote_call = - kusama_runtime::RuntimeCall::ConvictionVoting(pallet_conviction_voting::Call::< - kusama_runtime::Runtime, - >::vote { - poll_index: 0, - vote: aye(1_000_000_000_000u128, 1), - }); - - let notify_vote_call = - RuntimeCall::VtokenVoting(bifrost_vtoken_voting::Call::::notify_vote { - query_id: 0, - response: Default::default(), - }); - - Kusama::execute_with(|| { - use frame_support::traits::schedule::DispatchTime; - use kusama_runtime::{Balances, Referenda, RuntimeEvent, RuntimeOrigin, System}; - - println!("KusamaNet vote_call weight: {:?}", vote_call.get_dispatch_info().weight); - - assert_ok!(Referenda::submit( - RuntimeOrigin::signed(KusamaAlice::get()), - bx!(RawOrigin::Root.into()), - set_balance_proposal_bounded(1), - DispatchTime::At(1), - )); - - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - Kusama::sovereign_account_id_of_child_para(BifrostKusama::para_id()).into(), - 100_000_000_000_000u128 - )); - - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::Referenda(pallet_referenda::Event::Submitted { - index: 0, - track: _, - proposal: _, - }) - ))); - }); - - BifrostKusama::execute_with(|| { - let notify_vote_call_weight = notify_vote_call.get_dispatch_info().weight; - let query_id = pallet_xcm::Pallet::::new_notify_query( - MultiLocation::parent(), - notify_vote_call, - 100u32.into(), - Here, - ); - - let asset: MultiAsset = - MultiAsset { id: Concrete(MultiLocation::here()), fun: Fungible(1000000000000) }; - let msg = Xcm(vec![ - WithdrawAsset(asset.clone().into()), - BuyExecution { fees: asset, weight_limit: Unlimited }, - Transact { - origin_kind: OriginKind::SovereignAccount, - require_weight_at_most: Weight::from_parts(1019439000, 83866), - call: vote_call.encode().into(), - }, - ReportTransactStatus(QueryResponseInfo { - destination: MultiLocation::from(X1(Parachain(2001))), - query_id, - max_weight: notify_vote_call_weight, - }), - RefundSurplus, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { parents: 0, interior: X1(Parachain(2001)) }, - }, - ]); - assert_ok!(pallet_xcm::Pallet::::send_xcm(Here, MultiLocation::parent(), msg)); - }); - - Kusama::execute_with(|| { - use kusama_runtime::{RuntimeEvent, System}; - - System::events().iter().for_each(|r| println!("KusamaNet >>> {:?}", r.event)); - assert!(System::events().iter().any(|r| matches!( - &r.event, - RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { - id: _, - origin: _, - weight_used: _, - success: true - }) - ))); - }); - - BifrostKusama::execute_with(|| { - System::events().iter().for_each(|r| println!("Bifrost >>> {:?}", r.event)); - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::VtokenVoting(bifrost_vtoken_voting::Event::ResponseReceived { - responder: MultiLocation { parents: 1, interior: Here }, - query_id: 0, - response: Response::DispatchResult(MaybeErrorCode::Success) - }) - ))); - }); -} - -pub fn aye(amount: Balance, conviction: u8) -> AccountVote { - let vote = Vote { aye: true, conviction: conviction.try_into().unwrap() }; - AccountVote::Standard { vote, balance: amount } -} diff --git a/integration-tests/bifrost-kusama/src/vtoken_minting.rs b/integration-tests/bifrost-kusama/src/vtoken_minting.rs deleted file mode 100644 index 9f4684d84..000000000 --- a/integration-tests/bifrost-kusama/src/vtoken_minting.rs +++ /dev/null @@ -1,186 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use bifrost_asset_registry::AssetIdMaps; -use bifrost_kusama_runtime::{ - Currencies, MultiCurrency, Runtime, SlpEntrancePalletId, VtokenMinting, VtokenMintingOperator, -}; -use bifrost_primitives::{CurrencyIdRegister, TimeUnit, TokenSymbol, KSM, VKSM}; -use frame_support::{assert_ok, dispatch::RawOrigin}; -use integration_tests_common::{BifrostKusama, BifrostKusamaAlice}; -use sp_runtime::{traits::AccountIdConversion, BoundedVec, Permill}; -use xcm_emulator::TestExt; - -#[test] -fn set_unlock_duration_should_work() { - BifrostKusama::execute_with(|| { - assert_ok!(VtokenMinting::set_unlock_duration( - RawOrigin::Root.into(), - KSM, - TimeUnit::Era(28), - )); - assert_eq!(VtokenMinting::unlock_duration(KSM), Some(TimeUnit::Era(28))); - }); -} - -#[test] -fn set_minimum_mint_should_work() { - BifrostKusama::execute_with(|| { - assert_ok!(VtokenMinting::set_minimum_mint(RawOrigin::Root.into(), KSM, 50_000_000_000,)); - assert_eq!(VtokenMinting::minimum_mint(KSM), 50_000_000_000); - assert_eq!(AssetIdMaps::::check_vtoken_registered(TokenSymbol::KSM), true); - assert_eq!(AssetIdMaps::::check_token_registered(TokenSymbol::KSM), true); - }); -} - -#[test] -fn set_minimum_redeem_should_work() { - BifrostKusama::execute_with(|| { - assert_ok!(VtokenMinting::set_minimum_redeem(RawOrigin::Root.into(), KSM, 10_000,)); - assert_eq!(VtokenMinting::minimum_redeem(KSM), 10_000); - }); -} - -#[test] -fn add_support_rebond_token_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(VtokenMinting::token_to_rebond(KSM), None); - assert_ok!(VtokenMinting::add_support_rebond_token(RawOrigin::Root.into(), KSM,)); - assert_eq!(VtokenMinting::token_to_rebond(KSM), Some(0)); - }); -} - -#[test] -fn remove_support_rebond_token_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(VtokenMinting::token_to_rebond(KSM), None); - assert_ok!(VtokenMinting::add_support_rebond_token(RawOrigin::Root.into(), KSM,)); - assert_eq!(VtokenMinting::token_to_rebond(KSM), Some(0)); - assert_ok!(VtokenMinting::remove_support_rebond_token(RawOrigin::Root.into(), KSM,)); - assert_eq!(VtokenMinting::token_to_rebond(KSM), None); - }); -} - -#[test] -fn set_fees_should_work() { - BifrostKusama::execute_with(|| { - assert_ok!(VtokenMinting::set_fees( - RawOrigin::Root.into(), - Permill::from_perthousand(0), - Permill::from_perthousand(1), - )); - assert_eq!( - VtokenMinting::fees(), - (Permill::from_perthousand(0), Permill::from_perthousand(1)) - ); - println!("{:#?}", Permill::from_perthousand(1)); - }); -} - -#[test] -fn set_hook_iteration_limit_should_work() { - BifrostKusama::execute_with(|| { - assert_ok!(VtokenMinting::set_hook_iteration_limit(RawOrigin::Root.into(), 10)); - assert_eq!(VtokenMinting::hook_iteration_limit(), 10); - }); -} - -#[test] -fn set_unlocking_total_should_work() { - BifrostKusama::execute_with(|| { - assert_ok!( - VtokenMinting::set_unlocking_total(RawOrigin::Root.into(), KSM, 10_000_000_000,) - ); - assert_eq!(VtokenMinting::unlocking_total(KSM), 10_000_000_000); - }); -} - -#[test] -fn set_min_time_unit_should_work() { - BifrostKusama::execute_with(|| { - assert_ok!(VtokenMinting::set_min_time_unit( - RawOrigin::Root.into(), - KSM, - TimeUnit::Era(4362), - )); - assert_eq!(VtokenMinting::min_time_unit(KSM), TimeUnit::Era(4362)); - }); -} - -#[test] -fn mint_should_work() { - BifrostKusama::execute_with(|| { - assert_eq!(VtokenMinting::token_pool(KSM), 0); - assert_eq!(Currencies::total_issuance(VKSM), 0); - assert_eq!( - VtokenMinting::fees(), - (Permill::from_perthousand(0), Permill::from_perthousand(0)) - ); - - assert_ok!(VtokenMinting::mint( - RawOrigin::Signed(BifrostKusamaAlice::get()).into(), - KSM, - 5_000_000_000_000, - BoundedVec::default(), - None - )); - - //check balance - let entrance_account = SlpEntrancePalletId::get().into_account_truncating(); - assert_eq!(Currencies::free_balance(VKSM, &BifrostKusamaAlice::get()), 5_000_000_000_000); - assert_eq!(Currencies::free_balance(KSM, &entrance_account), 5_000_000_000_000); - assert_eq!(VtokenMinting::token_pool(KSM), 5_000_000_000_000); - }); -} - -#[test] -fn redeem_should_work() { - BifrostKusama::execute_with(|| { - pub const FEE: Permill = Permill::from_percent(2); - assert_ok!(VtokenMinting::set_fees(RawOrigin::Root.into(), FEE, FEE)); - assert_ok!(VtokenMinting::set_unlock_duration( - RawOrigin::Root.into(), - KSM, - TimeUnit::Era(1) - )); - assert_ok!(VtokenMinting::update_ongoing_time_unit(KSM, TimeUnit::Era(1))); - assert_ok!(VtokenMinting::set_minimum_redeem( - RawOrigin::Root.into(), - KSM, - 2 * 1_000_000_000_000 - )); - assert_ok!(VtokenMinting::mint( - RawOrigin::Signed(BifrostKusamaAlice::get()).into(), - KSM, - 5 * 1_000_000_000_000, - BoundedVec::default(), - None - )); - assert_eq!(VtokenMinting::token_pool(KSM), 5 * 1_000_000_000_000 - 5 * 20_000_000_000); // 1000 + 980 - 98 - 196 - - assert_ok!(VtokenMinting::redeem( - RawOrigin::Signed(BifrostKusamaAlice::get()).into(), - VKSM, - 1 * 1_000_000_000_000 - )); - assert_eq!( - VtokenMinting::token_pool(KSM), - 5 * 1_000_000_000_000 - 5 * 20_000_000_000 - 1_000_000_000_000 + 20_000_000_000 - ); - }); -} diff --git a/integration-tests/bifrost-kusama/src/vtoken_voting.rs b/integration-tests/bifrost-kusama/src/vtoken_voting.rs deleted file mode 100644 index 68a4653c7..000000000 --- a/integration-tests/bifrost-kusama/src/vtoken_voting.rs +++ /dev/null @@ -1,275 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use bifrost_kusama_runtime::{ - Runtime, RuntimeOrigin, Slp, XcmDestWeightAndFeeHandler, XcmInterface, -}; -use bifrost_primitives::{ - currency::VKSM, Balance, CurrencyId, VTokenSupplyProvider, XcmOperationType as XcmOperation, - KSM, -}; -use bifrost_slp::{Ledger, MinimumsMaximums, SubstrateLedger}; -use bifrost_vtoken_voting::{AccountVote, TallyOf}; -use frame_support::{ - assert_ok, - dispatch::RawOrigin, - traits::{schedule::DispatchTime, StorePreimage}, - weights::Weight, -}; -use integration_tests_common::{BifrostKusama, BifrostKusamaAlice, Kusama, KusamaAlice}; -use pallet_conviction_voting::Vote; -use sp_runtime::Perbill; -use xcm::v3::Parent; -use xcm_emulator::{Parachain, RelayChain, TestExt}; - -#[test] -fn vote_works() { - let vtoken = VKSM; - let poll_index = 0; - - Kusama::execute_with(|| { - use kusama_runtime::{Balances, Referenda, RuntimeEvent, RuntimeOrigin, System, Utility}; - - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - Kusama::sovereign_account_id_of_child_para(BifrostKusama::para_id()).into(), - 1_000_000_000_000_000u128 - )); - assert_ok!(Balances::force_set_balance( - RuntimeOrigin::root(), - Utility::derivative_account_id( - Kusama::sovereign_account_id_of_child_para(BifrostKusama::para_id()).into(), - 5 - ) - .into(), - 1_000_000_000_000_000u128 - )); - assert_ok!(Referenda::submit( - RuntimeOrigin::signed(BifrostKusamaAlice::get()), - Box::new(RawOrigin::Root.into()), - set_balance_proposal_bounded(1), - DispatchTime::At(10), - )); - System::events().iter().for_each(|r| log::debug!("Kusama >>> {:?}", r.event)); - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::Referenda(pallet_referenda::Event::Submitted { - index: 0, - track: 0, - proposal: _, - }) - ))); - System::reset_events(); - }); - - BifrostKusama::execute_with(|| { - use bifrost_kusama_runtime::{ - RuntimeEvent, RuntimeOrigin, System, VtokenMinting, VtokenVoting, - }; - - assert_ok!(VtokenMinting::mint( - RuntimeOrigin::signed(BifrostKusamaAlice::get()), - KSM, - 1_000_000_000_000, - Default::default(), - None - )); - assert_eq!( - ::VTokenSupplyProvider::get_token_supply(KSM), - Some(1_000_000_000_000) - ); - assert_eq!( - ::VTokenSupplyProvider::get_vtoken_supply( - VKSM - ), - Some(1_000_000_000_000) - ); - let token = CurrencyId::to_token(&vtoken).unwrap(); - assert_ok!(XcmInterface::set_xcm_dest_weight_and_fee( - token, - XcmOperation::Vote, - Some((Weight::from_parts(4000000000, 100000), 4000000000u32.into())), - )); - assert_ok!(XcmInterface::set_xcm_dest_weight_and_fee( - token, - XcmOperation::RemoveVote, - Some((Weight::from_parts(4000000000, 100000), 4000000000u32.into())), - )); - assert_ok!(Slp::set_minimums_and_maximums( - RuntimeOrigin::root(), - token, - Some(MinimumsMaximums { - delegator_bonded_minimum: 0u32.into(), - bond_extra_minimum: 0u32.into(), - unbond_minimum: 0u32.into(), - rebond_minimum: 0u32.into(), - unbond_record_maximum: 0u32, - validators_back_maximum: 0u32, - delegator_active_staking_maximum: 0u32.into(), - validators_reward_maximum: 0u32, - delegation_amount_minimum: 0u32.into(), - delegators_maximum: u16::MAX, - validators_maximum: 0u16, - }) - )); - assert_ok!(Slp::add_delegator(RuntimeOrigin::root(), token, 5, Box::new(Parent.into()))); - assert_ok!(Slp::set_delegator_ledger( - RuntimeOrigin::root(), - token, - Box::new(Parent.into()), - Box::new(Some(Ledger::Substrate(SubstrateLedger { - account: Parent.into(), - total: 1_000_000_000_000u128, - active: 1_000_000_000_000u128, - unlocking: vec![], - }))) - )); - - assert_ok!(VtokenVoting::set_vote_cap_ratio( - RuntimeOrigin::root(), - vtoken, - Perbill::from_percent(90) - )); - assert_ok!(VtokenVoting::add_delegator(RuntimeOrigin::root(), vtoken, 5)); - assert_ok!(VtokenVoting::set_vote_locking_period(RuntimeOrigin::root(), vtoken, 0)); - assert_ok!(VtokenVoting::set_undeciding_timeout(RuntimeOrigin::root(), vtoken, 100)); - - assert_ok!(VtokenVoting::vote( - RuntimeOrigin::signed(BifrostKusamaAlice::get()), - vtoken, - poll_index, - aye(1_000_000_000_000u128, 5) - )); - - assert_eq!( - tally(vtoken, poll_index), - TallyOf::::from_parts(5_000_000_000_000, 0, 1_000_000_000_000) - ); - - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::VtokenVoting(bifrost_vtoken_voting::Event::Voted { - who: _, - vtoken: VKSM, - poll_index: 0, - token_vote: _, - delegator_vote: _, - }) - ))); - System::reset_events(); - }); - - Kusama::execute_with(|| { - use kusama_runtime::System; - - System::events().iter().for_each(|r| log::debug!("Kusama >>> {:?}", r.event)); - assert!(System::events().iter().any(|r| matches!( - r.event, - kusama_runtime::RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { - id: _, - origin: _, - weight_used: _, - success: true - }) - ))); - System::reset_events(); - }); - - BifrostKusama::execute_with(|| { - use bifrost_kusama_runtime::{RuntimeEvent, System, VtokenVoting}; - - System::events() - .iter() - .for_each(|r| log::debug!("BifrostKusama >>> {:?}", r.event)); - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::VtokenVoting(bifrost_vtoken_voting::Event::VoteNotified { - vtoken: VKSM, - poll_index: 0, - success: true, - }) - ))); - assert_ok!(VtokenVoting::set_referendum_status( - RuntimeOrigin::root(), - VKSM, - 0, - bifrost_vtoken_voting::ReferendumInfoOf::::Completed(1), - )); - assert_ok!(VtokenVoting::remove_delegator_vote( - RuntimeOrigin::signed(BifrostKusamaAlice::get()), - VKSM, - 0, - 5, - )); - System::reset_events(); - }); - - Kusama::execute_with(|| { - use kusama_runtime::{RuntimeEvent, System}; - - System::events().iter().for_each(|r| log::debug!("Kusama >>> {:?}", r.event)); - assert!(System::events().iter().any(|r| matches!( - &r.event, - RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { - id: _, - origin: _, - weight_used: _, - success: true - }) - ))); - }); - - BifrostKusama::execute_with(|| { - use bifrost_kusama_runtime::{RuntimeEvent, System}; - - System::events() - .iter() - .for_each(|r| log::debug!("BifrostKusama >>> {:?}", r.event)); - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::VtokenVoting( - bifrost_vtoken_voting::Event::DelegatorVoteRemovedNotified { - vtoken: VKSM, - poll_index: 0, - success: true, - } - ) - ))); - }); -} - -pub fn set_balance_proposal_bounded( - value: Balance, -) -> pallet_referenda::BoundedCallOf { - let c = kusama_runtime::RuntimeCall::Balances(pallet_balances::Call::force_set_balance { - who: KusamaAlice::get().into(), - new_free: value, - }); - ::bound(c).unwrap() -} - -pub fn aye(amount: Balance, conviction: u8) -> AccountVote { - let vote = Vote { aye: true, conviction: conviction.try_into().unwrap() }; - AccountVote::Standard { vote, balance: amount } -} - -fn tally(vtoken: CurrencyId, poll_index: u32) -> TallyOf { - bifrost_kusama_runtime::VtokenVoting::ensure_referendum_ongoing(vtoken, poll_index) - .expect("No poll") - .tally -} diff --git a/integration-tests/bifrost-kusama/src/xcm_interface.rs b/integration-tests/bifrost-kusama/src/xcm_interface.rs deleted file mode 100644 index 0a88d6493..000000000 --- a/integration-tests/bifrost-kusama/src/xcm_interface.rs +++ /dev/null @@ -1,174 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use bifrost_asset_registry::AssetMetadata; -use bifrost_kusama_runtime::{ - AssetRegistry, RelayCurrencyId, RuntimeEvent, RuntimeOrigin, System, - XcmDestWeightAndFeeHandler, XcmInterface, -}; -use bifrost_primitives::{CurrencyId, XcmOperationType as XcmOperation}; -use frame_support::{assert_ok, traits::Currency}; -use integration_tests_common::{ - impls::Outcome::Complete, AssetHubKusama, AssetHubKusamaAlice, BifrostKusama, - BifrostKusamaAlice, -}; -use polkadot_parachain_primitives::primitives::Sibling; -use sp_runtime::{traits::AccountIdConversion, MultiAddress}; -use xcm::{ - v3::{prelude::*, Weight}, - VersionedMultiAssets, VersionedMultiLocation, -}; -use xcm_emulator::{bx, Parachain, TestExt}; - -const USDT: u128 = 1_000_000; - -#[test] -fn cross_usdt() { - BifrostKusama::execute_with(|| { - let metadata = AssetMetadata { - name: b"USDT".to_vec(), - symbol: b"USDT".to_vec(), - decimals: 6, - minimal_balance: 10, - }; - - assert_ok!(AssetRegistry::register_token_metadata( - RuntimeOrigin::root(), - bx!(metadata.clone()) - )); - - let location = VersionedMultiLocation::V3(MultiLocation { - parents: 1, - interior: X3(Parachain(1000), PalletInstance(50), GeneralIndex(1984)), - }); - - assert_ok!(AssetRegistry::register_multilocation( - RuntimeOrigin::root(), - CurrencyId::Token2(0), - bx!(location.clone()), - Weight::zero() - )); - }); - - AssetHubKusama::execute_with(|| { - use asset_hub_kusama_runtime::{ - Assets, Balances, Runtime, RuntimeEvent, RuntimeOrigin, System, - }; - - let sibling_account = Sibling::from(2001).into_account_truncating(); - - // need to have some KSM to be able to receive user assets - Balances::make_free_balance_be(&sibling_account, 10 * 1_000_000_000_000u128); - - assert_ok!(Assets::create( - RuntimeOrigin::signed(AssetHubKusamaAlice::get()), - codec::Compact(1984), - MultiAddress::Id(AssetHubKusamaAlice::get()), - 10 - )); - - assert_ok!(Assets::set_metadata( - RuntimeOrigin::signed(AssetHubKusamaAlice::get()), - codec::Compact(1984), - b"USDT".to_vec(), - b"USDT".to_vec(), - 6 - )); - - assert_ok!(Assets::mint( - RuntimeOrigin::signed(AssetHubKusamaAlice::get()), - codec::Compact(1984), - MultiAddress::Id(AssetHubKusamaAlice::get()), - 100 * USDT - )); - assert_eq!(Assets::balance(1984, AssetHubKusamaAlice::get()), 100 * USDT); - - let assets = MultiAssets::from(vec![MultiAsset::from(( - Concrete(MultiLocation::new(0, X2(PalletInstance(50), GeneralIndex(1984)))), - Fungibility::from(10 * USDT), - ))]); - - assert_ok!(pallet_xcm::Pallet::::limited_reserve_transfer_assets( - RuntimeOrigin::signed(AssetHubKusamaAlice::get()), - bx!(AssetHubKusama::sibling_location_of(BifrostKusama::para_id()).into()), - bx!(AccountId32 { network: None, id: BifrostKusamaAlice::get().into() }.into()), - Box::new(VersionedMultiAssets::V3(assets)), - 0, - WeightLimit::Unlimited, - )); - assert!(System::events().iter().any(|r| matches!( - r.event, - RuntimeEvent::Assets(pallet_assets::Event::Transferred { - asset_id: 1984, - from: _, - to: _, - amount: 10_000_000 - }) - ))); - assert!(System::events().iter().any(|r| matches!( - &r.event, - RuntimeEvent::PolkadotXcm(pallet_xcm::Event::Attempted { outcome: Complete(_) }) - ))); - System::reset_events(); - }); - - BifrostKusama::execute_with(|| { - System::events().iter().for_each(|r| println!("Bifrost >>> {:?}", r.event)); - assert!(System::events().iter().any(|r| matches!( - &r.event, - RuntimeEvent::Tokens(orml_tokens::Event::Deposited { - currency_id: CurrencyId::Token2(0), - who: _, - amount: 10_000_000 - }) - ))); - - System::reset_events(); - - assert_ok!(XcmInterface::set_xcm_dest_weight_and_fee( - RelayCurrencyId::get(), - XcmOperation::StatemineTransfer, - Some((Weight::from_parts(400_000_000_000, 10_000), 4_000_000_000)), - )); - - // Alice transfers 5 statemine asset to Bob - // TODO: Failed to process XCMP-XCM message, caused by Barrier - // assert_ok!(XcmInterface::transfer_statemine_assets( - // RuntimeOrigin::signed(BifrostKusamaAlice::get()), - // 5 * USDT, - // 1984, - // Some(BifrostKusamaBob::get()) - // )); - }); - - // AsserHubKusama::execute_with(|| { - // use statemine_runtime::*; - // println!("{:?}", System::events()); - // - // // assert Bob has 5 statemine asset - // assert_eq!(Assets::balance(1984, AccountId::from(BOB)), 5 * USDT); - // - // assert!(System::events().iter().any(|r| matches!( - // r.event, - // RuntimeEvent::XcmpQueue(cumulus_pallet_xcmp_queue::Event::Success { - // message_hash: _, - // weight: _ - // }) - // ))); - // }); -} diff --git a/integration-tests/bifrost-polkadot/Cargo.toml b/integration-tests/bifrost-polkadot/Cargo.toml deleted file mode 100644 index e6d46f80c..000000000 --- a/integration-tests/bifrost-polkadot/Cargo.toml +++ /dev/null @@ -1,32 +0,0 @@ -[package] -name = "bifrost-polkadot-integration-tests" -version = "0.8.0" -authors = ["Ron Yang "] -edition = "2021" - -[dependencies] -parity-scale-codec = { workspace = true } - -# Substrate -sp-runtime = { workspace = true } -sp-io = { workspace = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -pallet-balances = { workspace = true } - -# Polkadot -polkadot-parachain-primitives = { workspace = true } -polkadot-runtime-parachains = { workspace = true } -polkadot-runtime = { workspace = true } -xcm = { workspace = true } -pallet-xcm = { workspace = true } - -# Cumulus -parachains-common = { workspace = true } -xcm-emulator = { workspace = true } - -# Local -integration-tests-common = { path = "../common", default-features = false} -bifrost-primitives = { workspace = true } -bifrost-asset-registry = { workspace = true } -bifrost-polkadot-runtime = { workspace = true } diff --git a/integration-tests/common/Cargo.toml b/integration-tests/common/Cargo.toml deleted file mode 100644 index 47e5d94f5..000000000 --- a/integration-tests/common/Cargo.toml +++ /dev/null @@ -1,56 +0,0 @@ -[package] -name = "integration-tests-common" -version = "0.8.0" -authors = ["hqwangningbo <2536935847@qq.com>"] -edition = "2021" - -[dependencies] -parity-scale-codec = { workspace = true } -paste = { workspace = true } - -# Substrate -sc-consensus-grandpa = { workspace = true } -sp-authority-discovery = { workspace = true } -sp-runtime = { workspace = true } -frame-support = { workspace = true } -sp-core = { workspace = true } -sp-consensus-babe = { workspace = true } -pallet-assets = { workspace = true } -pallet-staking = { workspace = true } -pallet-message-queue = { workspace = true } -pallet-im-online = { workspace = true } - -# Polkadot -polkadot-core-primitives = { workspace = true } -polkadot-parachain-primitives = { workspace = true } -polkadot-service = { workspace = true } -polkadot-primitives = { workspace = true } -polkadot-runtime-parachains = { workspace = true } -polkadot-runtime = { workspace = true } -polkadot-runtime-constants = { workspace = true } -kusama-runtime = { workspace = true } -kusama-runtime-constants = { workspace = true } -xcm = { workspace = true } -pallet-xcm = { workspace = true } - -# Cumulus -parachains-common = { workspace = true } -cumulus-primitives-core = { workspace = true } -xcm-emulator = { workspace = true } -cumulus-pallet-dmp-queue = { workspace = true } -cumulus-pallet-xcmp-queue = { workspace = true } -cumulus-pallet-parachain-system = { workspace = true } - -bifrost-polkadot-runtime = { workspace = true } -bifrost-kusama-runtime = { workspace = true } -asset-hub-polkadot-runtime = { workspace = true } -asset-hub-kusama-runtime = { workspace = true } -bridge-hub-polkadot-runtime = { workspace = true } -bridge-hub-kusama-runtime = { workspace = true } -bifrost-parachain-staking = { workspace = true } -bifrost-primitives = { workspace = true } -beefy-primitives = { workspace = true } -grandpa-primitives = { workspace = true } -bp-messages = { workspace = true } -pallet-bridge-messages = { workspace = true } -bridge-runtime-common = { workspace = true } diff --git a/integration-tests/common/src/constants.rs b/integration-tests/common/src/constants.rs deleted file mode 100644 index 3e988504f..000000000 --- a/integration-tests/common/src/constants.rs +++ /dev/null @@ -1,794 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -// Substrate -use beefy_primitives::ecdsa_crypto::AuthorityId as BeefyId; -use grandpa_primitives::AuthorityId as GrandpaId; -use pallet_im_online::sr25519::AuthorityId as ImOnlineId; -use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; -use sp_consensus_babe::AuthorityId as BabeId; -use sp_core::{sr25519, storage::Storage, Pair, Public}; -use sp_runtime::{ - traits::{IdentifyAccount, Verify}, - BuildStorage, MultiSignature, Perbill, -}; - -// Cumulus -use parachains_common::{AccountId, AssetHubPolkadotAuraId, AuraId, Balance, BlockNumber}; -use polkadot_parachain_primitives::primitives::{HeadData, ValidationCode}; -use polkadot_primitives::{AssignmentId, ValidatorId}; -use polkadot_runtime_parachains::{ - configuration::HostConfiguration, - paras::{ParaGenesisArgs, ParaKind}, -}; -use xcm; - -pub const XCM_V2: u32 = 3; -pub const XCM_V3: u32 = 2; -pub const REF_TIME_THRESHOLD: u64 = 33; -pub const PROOF_SIZE_THRESHOLD: u64 = 33; - -type AccountPublic = ::Signer; - -/// Helper function to generate a crypto pair from seed -fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() -} - -/// Helper function to generate an account ID from seed. -fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} - -pub mod accounts { - use super::*; - use sp_runtime::traits::AccountIdConversion; - pub const ALICE: &str = "Alice"; - pub const BOB: &str = "Bob"; - pub const CHARLIE: &str = "Charlie"; - pub const DAVE: &str = "Dave"; - pub const EVE: &str = "Eve"; - pub const FERDIE: &str = "Ferdei"; - pub const ALICE_STASH: &str = "Alice//stash"; - pub const BOB_STASH: &str = "Bob//stash"; - - pub fn init_balances() -> Vec { - vec![ - get_account_id_from_seed::(ALICE), - get_account_id_from_seed::(BOB), - get_account_id_from_seed::(CHARLIE), - get_account_id_from_seed::(DAVE), - get_account_id_from_seed::(EVE), - get_account_id_from_seed::(ALICE_STASH), - get_account_id_from_seed::(BOB_STASH), - bifrost_kusama_runtime::TreasuryPalletId::get().into_account_truncating(), - ] - } -} - -pub mod collators { - use super::*; - - pub fn invulnerables_asset_hub_polkadot() -> Vec<(AccountId, AssetHubPolkadotAuraId)> { - vec![ - ( - get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_from_seed::("Bob"), - ), - ] - } - - pub fn invulnerables() -> Vec<(AccountId, AuraId)> { - vec![ - ( - get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), - ), - (get_account_id_from_seed::("Bob"), get_from_seed::("Bob")), - ] - } -} - -pub mod validators { - use super::*; - - pub fn initial_authorities() -> Vec<( - AccountId, - AccountId, - BabeId, - GrandpaId, - ImOnlineId, - ValidatorId, - AssignmentId, - AuthorityDiscoveryId, - BeefyId, - )> { - let seed = "Alice"; - vec![( - get_account_id_from_seed::(&format!("{}//stash", seed)), - get_account_id_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - )] - } -} - -/// The default XCM version to set in genesis config. -const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION; - -// Polkadot -pub mod polkadot { - use super::*; - pub const ED: Balance = polkadot_runtime_constants::currency::EXISTENTIAL_DEPOSIT; - const STASH: u128 = 100 * polkadot_runtime_constants::currency::UNITS; - - pub fn get_host_config() -> HostConfiguration { - HostConfiguration { - max_upward_queue_count: 10, - max_upward_queue_size: 51200, - max_upward_message_size: 51200, - max_upward_message_num_per_candidate: 10, - max_downward_message_size: 51200, - hrmp_sender_deposit: 100_000_000_000, - hrmp_recipient_deposit: 100_000_000_000, - hrmp_channel_max_capacity: 1000, - hrmp_channel_max_message_size: 102400, - hrmp_channel_max_total_size: 102400, - hrmp_max_parachain_outbound_channels: 30, - hrmp_max_parachain_inbound_channels: 30, - ..Default::default() - } - } - - fn session_keys( - babe: BabeId, - grandpa: GrandpaId, - im_online: ImOnlineId, - para_validator: ValidatorId, - para_assignment: AssignmentId, - authority_discovery: AuthorityDiscoveryId, - beefy: BeefyId, - ) -> polkadot_runtime::SessionKeys { - polkadot_runtime::SessionKeys { - babe, - grandpa, - im_online, - para_validator, - para_assignment, - authority_discovery, - beefy, - } - } - - pub fn genesis() -> Storage { - let genesis_config = polkadot_runtime::RuntimeGenesisConfig { - system: polkadot_runtime::SystemConfig { - code: polkadot_runtime::WASM_BINARY.unwrap().to_vec(), - ..Default::default() - }, - balances: polkadot_runtime::BalancesConfig { - balances: accounts::init_balances() - .iter() - .cloned() - .map(|k| (k, ED * 4096)) - .collect(), - }, - session: polkadot_runtime::SessionConfig { - keys: validators::initial_authorities() - .iter() - .map(|x| { - ( - x.0.clone(), - x.0.clone(), - polkadot::session_keys( - x.2.clone(), - x.3.clone(), - x.4.clone(), - x.5.clone(), - x.6.clone(), - x.7.clone(), - x.8.clone(), - ), - ) - }) - .collect::>(), - }, - staking: polkadot_runtime::StakingConfig { - validator_count: validators::initial_authorities().len() as u32, - minimum_validator_count: 1, - stakers: validators::initial_authorities() - .iter() - .map(|x| { - (x.0.clone(), x.1.clone(), STASH, polkadot_runtime::StakerStatus::Validator) - }) - .collect(), - invulnerables: validators::initial_authorities() - .iter() - .map(|x| x.0.clone()) - .collect(), - force_era: pallet_staking::Forcing::ForceNone, - slash_reward_fraction: Perbill::from_percent(10), - ..Default::default() - }, - babe: polkadot_runtime::BabeConfig { - authorities: Default::default(), - epoch_config: Some(polkadot_runtime::BABE_GENESIS_EPOCH_CONFIG), - ..Default::default() - }, - configuration: polkadot_runtime::ConfigurationConfig { config: get_host_config() }, - paras: polkadot_runtime::ParasConfig { - paras: vec![ - ( - asset_hub_polkadot::PARA_ID.into(), - ParaGenesisArgs { - genesis_head: HeadData::default(), - validation_code: ValidationCode( - asset_hub_polkadot_runtime::WASM_BINARY.unwrap().to_vec(), - ), - para_kind: ParaKind::Parachain, - }, - ), - ( - bridge_hub_polkadot::PARA_ID.into(), - ParaGenesisArgs { - genesis_head: HeadData::default(), - validation_code: ValidationCode( - bridge_hub_polkadot_runtime::WASM_BINARY.unwrap().to_vec(), - ), - para_kind: ParaKind::Parachain, - }, - ), - ( - bifrost_polkadot::PARA_ID.into(), - ParaGenesisArgs { - genesis_head: HeadData::default(), - validation_code: ValidationCode( - bifrost_polkadot_runtime::WASM_BINARY.unwrap().to_vec(), - ), - para_kind: ParaKind::Parachain, - }, - ), - ], - ..Default::default() - }, - ..Default::default() - }; - - genesis_config.build_storage().unwrap() - } -} - -// Kusama -pub mod kusama { - use super::*; - pub const ED: Balance = kusama_runtime_constants::currency::EXISTENTIAL_DEPOSIT; - use kusama_runtime_constants::currency::UNITS as KSM; - const ENDOWMENT: u128 = 1_000_000 * KSM; - const STASH: u128 = 100 * KSM; - - pub fn get_host_config() -> HostConfiguration { - HostConfiguration { - max_upward_queue_count: 10, - max_upward_queue_size: 51200, - max_upward_message_size: 51200, - max_upward_message_num_per_candidate: 10, - max_downward_message_size: 51200, - hrmp_sender_deposit: 5_000_000_000_000, - hrmp_recipient_deposit: 5_000_000_000_000, - hrmp_channel_max_capacity: 1000, - hrmp_channel_max_message_size: 102400, - hrmp_channel_max_total_size: 102400, - hrmp_max_parachain_outbound_channels: 30, - hrmp_max_parachain_inbound_channels: 30, - ..Default::default() - } - } - - fn session_keys( - babe: BabeId, - grandpa: GrandpaId, - im_online: ImOnlineId, - para_validator: ValidatorId, - para_assignment: AssignmentId, - authority_discovery: AuthorityDiscoveryId, - beefy: BeefyId, - ) -> kusama_runtime::SessionKeys { - kusama_runtime::SessionKeys { - babe, - grandpa, - im_online, - para_validator, - para_assignment, - authority_discovery, - beefy, - } - } - - pub fn genesis() -> Storage { - let genesis_config = kusama_runtime::RuntimeGenesisConfig { - system: kusama_runtime::SystemConfig { - code: kusama_runtime::WASM_BINARY.unwrap().to_vec(), - ..Default::default() - }, - balances: kusama_runtime::BalancesConfig { - balances: accounts::init_balances() - .iter() - .map(|k: &AccountId| (k.clone(), ENDOWMENT)) - .collect(), - }, - session: kusama_runtime::SessionConfig { - keys: validators::initial_authorities() - .iter() - .map(|x| { - ( - x.0.clone(), - x.0.clone(), - kusama::session_keys( - x.2.clone(), - x.3.clone(), - x.4.clone(), - x.5.clone(), - x.6.clone(), - x.7.clone(), - x.8.clone(), - ), - ) - }) - .collect::>(), - }, - staking: kusama_runtime::StakingConfig { - validator_count: validators::initial_authorities().len() as u32, - minimum_validator_count: 1, - stakers: validators::initial_authorities() - .iter() - .map(|x| { - (x.0.clone(), x.1.clone(), STASH, kusama_runtime::StakerStatus::Validator) - }) - .collect(), - invulnerables: validators::initial_authorities() - .iter() - .map(|x| x.0.clone()) - .collect(), - force_era: pallet_staking::Forcing::NotForcing, - slash_reward_fraction: Perbill::from_percent(10), - ..Default::default() - }, - babe: kusama_runtime::BabeConfig { - authorities: Default::default(), - epoch_config: Some(kusama_runtime::BABE_GENESIS_EPOCH_CONFIG), - ..Default::default() - }, - configuration: kusama_runtime::ConfigurationConfig { config: get_host_config() }, - paras: kusama_runtime::ParasConfig { - paras: vec![ - ( - asset_hub_kusama::PARA_ID.into(), - ParaGenesisArgs { - genesis_head: HeadData::default(), - validation_code: ValidationCode( - asset_hub_kusama_runtime::WASM_BINARY.unwrap().to_vec(), - ), - para_kind: ParaKind::Parachain, - }, - ), - ( - bridge_hub_kusama::PARA_ID.into(), - ParaGenesisArgs { - genesis_head: HeadData::default(), - validation_code: ValidationCode( - bridge_hub_kusama_runtime::WASM_BINARY.unwrap().to_vec(), - ), - para_kind: ParaKind::Parachain, - }, - ), - ( - bifrost_kusama::PARA_ID.into(), - ParaGenesisArgs { - genesis_head: HeadData::default(), - validation_code: ValidationCode( - bifrost_kusama_runtime::WASM_BINARY.unwrap().to_vec(), - ), - para_kind: ParaKind::Parachain, - }, - ), - ], - ..Default::default() - }, - ..Default::default() - }; - - genesis_config.build_storage().unwrap() - } -} - -// Asset Hub Polkadot -pub mod asset_hub_polkadot { - use super::*; - pub const PARA_ID: u32 = 1000; - pub const ED: Balance = parachains_common::polkadot::currency::EXISTENTIAL_DEPOSIT; - - pub fn genesis() -> Storage { - let genesis_config = asset_hub_polkadot_runtime::RuntimeGenesisConfig { - system: asset_hub_polkadot_runtime::SystemConfig { - code: asset_hub_polkadot_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - ..Default::default() - }, - balances: asset_hub_polkadot_runtime::BalancesConfig { - balances: accounts::init_balances() - .iter() - .cloned() - .map(|k| (k, ED * 4096)) - .collect(), - }, - parachain_info: asset_hub_polkadot_runtime::ParachainInfoConfig { - parachain_id: PARA_ID.into(), - ..Default::default() - }, - collator_selection: asset_hub_polkadot_runtime::CollatorSelectionConfig { - invulnerables: collators::invulnerables_asset_hub_polkadot() - .iter() - .cloned() - .map(|(acc, _)| acc) - .collect(), - candidacy_bond: ED * 16, - ..Default::default() - }, - session: asset_hub_polkadot_runtime::SessionConfig { - keys: collators::invulnerables_asset_hub_polkadot() - .into_iter() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - asset_hub_polkadot_runtime::SessionKeys { aura }, // session keys - ) - }) - .collect(), - }, - polkadot_xcm: asset_hub_polkadot_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - ..Default::default() - }; - - genesis_config.build_storage().unwrap() - } -} - -// Asset Hub Kusama -pub mod asset_hub_kusama { - use super::*; - pub const PARA_ID: u32 = 1000; - pub const ED: Balance = parachains_common::kusama::currency::EXISTENTIAL_DEPOSIT; - - pub fn genesis() -> Storage { - let genesis_config = asset_hub_kusama_runtime::RuntimeGenesisConfig { - system: asset_hub_kusama_runtime::SystemConfig { - code: asset_hub_kusama_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - ..Default::default() - }, - balances: asset_hub_kusama_runtime::BalancesConfig { - balances: accounts::init_balances() - .iter() - .cloned() - .map(|k| (k, ED * 4096)) - .collect(), - }, - parachain_info: asset_hub_kusama_runtime::ParachainInfoConfig { - parachain_id: PARA_ID.into(), - ..Default::default() - }, - collator_selection: asset_hub_kusama_runtime::CollatorSelectionConfig { - invulnerables: collators::invulnerables() - .iter() - .cloned() - .map(|(acc, _)| acc) - .collect(), - candidacy_bond: ED * 16, - ..Default::default() - }, - session: asset_hub_kusama_runtime::SessionConfig { - keys: collators::invulnerables() - .into_iter() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - asset_hub_kusama_runtime::SessionKeys { aura }, // session keys - ) - }) - .collect(), - }, - polkadot_xcm: asset_hub_kusama_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - ..Default::default() - }; - - genesis_config.build_storage().unwrap() - } -} - -// Bridge Hub Polkadot -pub mod bridge_hub_polkadot { - use super::*; - pub const PARA_ID: u32 = 1002; - pub const ED: Balance = parachains_common::polkadot::currency::EXISTENTIAL_DEPOSIT; - - pub fn genesis() -> Storage { - let genesis_config = bridge_hub_polkadot_runtime::RuntimeGenesisConfig { - system: bridge_hub_polkadot_runtime::SystemConfig { - code: bridge_hub_polkadot_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - ..Default::default() - }, - balances: bridge_hub_polkadot_runtime::BalancesConfig { - balances: accounts::init_balances() - .iter() - .cloned() - .map(|k| (k, ED * 4096)) - .collect(), - }, - parachain_info: bridge_hub_polkadot_runtime::ParachainInfoConfig { - parachain_id: PARA_ID.into(), - ..Default::default() - }, - collator_selection: bridge_hub_polkadot_runtime::CollatorSelectionConfig { - invulnerables: collators::invulnerables() - .iter() - .cloned() - .map(|(acc, _)| acc) - .collect(), - candidacy_bond: ED * 16, - ..Default::default() - }, - session: bridge_hub_polkadot_runtime::SessionConfig { - keys: collators::invulnerables() - .into_iter() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - bridge_hub_polkadot_runtime::SessionKeys { aura }, // session keys - ) - }) - .collect(), - }, - polkadot_xcm: bridge_hub_polkadot_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - ..Default::default() - }; - - genesis_config.build_storage().unwrap() - } -} - -// Bridge Hub Kusama -pub mod bridge_hub_kusama { - use super::*; - pub const PARA_ID: u32 = 1002; - pub const ED: Balance = parachains_common::kusama::currency::EXISTENTIAL_DEPOSIT; - - pub fn genesis() -> Storage { - let genesis_config = bridge_hub_kusama_runtime::RuntimeGenesisConfig { - system: bridge_hub_kusama_runtime::SystemConfig { - code: bridge_hub_kusama_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - ..Default::default() - }, - balances: bridge_hub_kusama_runtime::BalancesConfig { - balances: accounts::init_balances() - .iter() - .cloned() - .map(|k| (k, ED * 4096)) - .collect(), - }, - parachain_info: bridge_hub_kusama_runtime::ParachainInfoConfig { - parachain_id: PARA_ID.into(), - ..Default::default() - }, - collator_selection: bridge_hub_kusama_runtime::CollatorSelectionConfig { - invulnerables: collators::invulnerables() - .iter() - .cloned() - .map(|(acc, _)| acc) - .collect(), - candidacy_bond: ED * 16, - ..Default::default() - }, - session: bridge_hub_kusama_runtime::SessionConfig { - keys: collators::invulnerables() - .into_iter() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - bridge_hub_kusama_runtime::SessionKeys { aura }, // session keys - ) - }) - .collect(), - }, - polkadot_xcm: bridge_hub_kusama_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - ..Default::default() - }; - - genesis_config.build_storage().unwrap() - } -} - -// Asset Hub Polkadot -pub mod bifrost_polkadot { - use super::*; - use crate::BOB; - use bifrost_primitives::DOT; - pub const PARA_ID: u32 = 2030; - pub const ED: Balance = 10_000_000_000; - - pub fn genesis() -> Storage { - let genesis_config = bifrost_polkadot_runtime::RuntimeGenesisConfig { - system: bifrost_polkadot_runtime::SystemConfig { - code: bifrost_polkadot_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - ..Default::default() - }, - balances: bifrost_polkadot_runtime::BalancesConfig { - balances: accounts::init_balances() - .iter() - .cloned() - .map(|k| (k, ED * 4096)) - .collect(), - }, - parachain_info: bifrost_polkadot_runtime::ParachainInfoConfig { - parachain_id: PARA_ID.into(), - ..Default::default() - }, - collator_selection: bifrost_polkadot_runtime::CollatorSelectionConfig { - invulnerables: collators::invulnerables_asset_hub_polkadot() - .iter() - .cloned() - .map(|(acc, _)| acc) - .collect(), - candidacy_bond: ED * 16, - ..Default::default() - }, - session: bifrost_polkadot_runtime::SessionConfig { - keys: collators::invulnerables() - .into_iter() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - bifrost_polkadot_runtime::SessionKeys { aura }, // session keys - ) - }) - .collect(), - }, - polkadot_xcm: bifrost_polkadot_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - tokens: bifrost_polkadot_runtime::TokensConfig { - balances: vec![( - get_account_id_from_seed::(BOB), - DOT, - 10 * 10_000_000_000u128, - )], - }, - ..Default::default() - }; - - genesis_config.build_storage().unwrap() - } -} - -// Asset Hub Polkadot -pub mod bifrost_kusama { - use super::*; - use crate::ALICE; - use bifrost_primitives::KSM; - - pub const PARA_ID: u32 = 2001; - pub const ED: Balance = 1_000_000_000_000; - - pub fn genesis() -> Storage { - let genesis_config = bifrost_kusama_runtime::RuntimeGenesisConfig { - system: bifrost_kusama_runtime::SystemConfig { - code: bifrost_kusama_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - ..Default::default() - }, - balances: bifrost_kusama_runtime::BalancesConfig { - balances: accounts::init_balances() - .iter() - .cloned() - .map(|k| (k, ED * 10_000_000)) - .collect(), - }, - parachain_info: bifrost_kusama_runtime::ParachainInfoConfig { - parachain_id: PARA_ID.into(), - ..Default::default() - }, - session: bifrost_kusama_runtime::SessionConfig { - keys: collators::invulnerables() - .into_iter() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - bifrost_kusama_runtime::SessionKeys { aura }, // session keys - ) - }) - .collect(), - }, - // bifrost_parachain_staking: bifrost_kusama_runtime::ParachainStakingConfig { - // candidates: collators::candidates(), - // delegations: collators::delegations(), - // inflation_config: collators::inflation_config(), - // }, - polkadot_xcm: bifrost_kusama_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - tokens: bifrost_kusama_runtime::TokensConfig { - balances: vec![( - get_account_id_from_seed::(ALICE), - KSM, - 10 * 1_000_000_000_000u128, - )], - }, - asset_registry: bifrost_kusama_runtime::AssetRegistryConfig { - currency: vec![(KSM, 10_000_000, None)], - vcurrency: vec![], - vsbond: vec![], - phantom: Default::default(), - }, - ..Default::default() - }; - - genesis_config.build_storage().unwrap() - } -} diff --git a/integration-tests/common/src/impls.rs b/integration-tests/common/src/impls.rs deleted file mode 100644 index 2eafefd9e..000000000 --- a/integration-tests/common/src/impls.rs +++ /dev/null @@ -1,662 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub use parity_scale_codec::{Decode, Encode}; -pub use paste; - -pub use crate::{ - constants::{PROOF_SIZE_THRESHOLD, REF_TIME_THRESHOLD}, - xcm_helpers::xcm_transact_unpaid_execution, -}; - -// Substrate -pub use frame_support::{assert_ok, traits::fungibles::Inspect}; -pub use pallet_assets; -pub use pallet_message_queue; -use sp_core::Get; - -// Cumulus -use bp_messages::{ - target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch}, - LaneId, MessageKey, OutboundLaneData, -}; -use bridge_runtime_common::messages_xcm_extension::XcmBlobMessageDispatchResult; -pub use cumulus_pallet_dmp_queue; -pub use cumulus_pallet_parachain_system; -pub use cumulus_pallet_xcmp_queue; -pub use cumulus_primitives_core::{ - relay_chain::HrmpChannelId, DmpMessageHandler, ParaId, XcmpMessageHandler, -}; -use pallet_bridge_messages::{Config, Instance1, OutboundLanes, Pallet}; -pub use parachains_common::{AccountId, Balance}; -pub use xcm_emulator::{ - assert_expected_events, bx, helpers::weight_within_threshold, BridgeMessage, - BridgeMessageDispatchError, BridgeMessageHandler, Chain, Parachain, RelayChain, TestExt, -}; - -// Polkadot -pub use pallet_xcm; -pub use polkadot_runtime_parachains::{ - dmp, hrmp, - inclusion::{AggregateMessageOrigin, UmpQueueId}, -}; -pub use xcm::{ - prelude::{OriginKind, Outcome, VersionedXcm, Weight}, - v3::Error, - DoubleEncoded, -}; - -pub struct BridgeHubMessageHandler { - _marker: std::marker::PhantomData<(S, T, I)>, -} - -struct LaneIdWrapper(LaneId); - -impl From for u32 { - fn from(lane_id: LaneIdWrapper) -> u32 { - u32::from_be_bytes(lane_id.0 .0) - } -} - -impl From for LaneIdWrapper { - fn from(id: u32) -> LaneIdWrapper { - LaneIdWrapper(LaneId(id.to_be_bytes())) - } -} - -// TODO: uncomment when https://github.com/polkadot-fellows/runtimes/pull/108 is merged -// type BridgeHubPolkadotRuntime = ::Runtime; -// type BridgeHubKusamaRuntime = ::Runtime; - -// TODO: uncomment when https://github.com/polkadot-fellows/runtimes/pull/108 is merged -// pub type PolkadotKusamaMessageHandler -// = BridgeHubMessageHandler; -// pub type KusamaPolkadotMessageHandler -// = BridgeHubMessageHandler; - -impl BridgeMessageHandler for BridgeHubMessageHandler -where - S: Config, - T: Config, - I: 'static, - >::InboundPayload: From>, - >::MessageDispatch: - MessageDispatch, -{ - fn get_source_outbound_messages() -> Vec { - // get the source active outbound lanes - let active_lanes = S::ActiveOutboundLanes::get(); - - let mut messages: Vec = Default::default(); - - // collect messages from `OutboundMessages` for each active outbound lane in the source - for lane in active_lanes { - let latest_generated_nonce = - OutboundLanes::::get(lane).latest_generated_nonce; - let latest_received_nonce = - OutboundLanes::::get(lane).latest_received_nonce; - - (latest_received_nonce + 1..=latest_generated_nonce).for_each(|nonce| { - let encoded_payload: Vec = - Pallet::::outbound_message_data(*lane, nonce) - .expect("Bridge message does not exist") - .into(); - let payload = Vec::::decode(&mut &encoded_payload[..]) - .expect("Decodign XCM message failed"); - let id: u32 = LaneIdWrapper(*lane).into(); - let message = BridgeMessage { id, nonce, payload }; - - messages.push(message); - }); - } - messages - } - - fn dispatch_target_inbound_message( - message: BridgeMessage, - ) -> Result<(), BridgeMessageDispatchError> { - type TargetMessageDispatch = >::MessageDispatch; - type InboundPayload = >::InboundPayload; - - let lane_id = LaneIdWrapper::from(message.id).0; - let nonce = message.nonce; - let payload = Ok(From::from(message.payload)); - - // Directly dispatch outbound messages assuming everything is correct - // and bypassing the `Relayers` and `InboundLane` logic - let dispatch_result = TargetMessageDispatch::::dispatch(DispatchMessage { - key: MessageKey { lane_id, nonce }, - data: DispatchMessageData::> { payload }, - }); - - let result = match dispatch_result.dispatch_level_result { - XcmBlobMessageDispatchResult::Dispatched => Ok(()), - XcmBlobMessageDispatchResult::InvalidPayload => Err(BridgeMessageDispatchError( - Box::new(XcmBlobMessageDispatchResult::InvalidPayload), - )), - XcmBlobMessageDispatchResult::NotDispatched(e) => Err(BridgeMessageDispatchError( - Box::new(XcmBlobMessageDispatchResult::NotDispatched(e)), - )), - }; - result - } - - fn notify_source_message_delivery(lane_id: u32) { - let data = OutboundLanes::::get(LaneIdWrapper::from(lane_id).0); - let new_data = OutboundLaneData { - oldest_unpruned_nonce: data.oldest_unpruned_nonce + 1, - latest_received_nonce: data.latest_received_nonce + 1, - ..data - }; - - OutboundLanes::::insert(LaneIdWrapper::from(lane_id).0, new_data); - } -} - -#[macro_export] -macro_rules! impl_test_accounts_helpers_for_chain { - ( $( $chain:ident),+ ) => { - xcm_emulator::paste::paste! { - xcm_emulator::parameter_types! { - $( - pub [<$chain Alice>]: parachains_common::AccountId = <$chain as xcm_emulator::Chain>::account_id_of(constants::accounts::ALICE); - pub [<$chain Bob>]: parachains_common::AccountId = <$chain as xcm_emulator::Chain>::account_id_of(constants::accounts::BOB); - pub [<$chain Charlie>]: parachains_common::AccountId = <$chain as xcm_emulator::Chain>::account_id_of(constants::accounts::CHARLIE); - pub [<$chain Dave>]: parachains_common::AccountId = <$chain as xcm_emulator::Chain>::account_id_of(constants::accounts::DAVE); - pub [<$chain Treasury>]: parachains_common::AccountId = bifrost_kusama_runtime::TreasuryPalletId::get().into_account_truncating(); - )+ - } - } - }; -} - -#[macro_export] -macro_rules! impl_accounts_helpers_for_relay_chain { - ( $chain:ident ) => { - $crate::impls::paste::paste! { - impl $chain { - /// Fund a set of accounts with a balance - pub fn fund_accounts(accounts: Vec<($crate::impls::AccountId, $crate::impls::Balance)>) { - ::execute_with(|| { - for account in accounts { - $crate::impls::assert_ok!(]>::Balances::force_set_balance( - ::RuntimeOrigin::root(), - account.0.into(), - account.1, - )); - } - }); - } - /// Fund a sovereign account based on its Parachain Id - pub fn fund_para_sovereign(amount: $crate::impls::Balance, para_id: $crate::impls::ParaId) -> sp_runtime::AccountId32 { - let sovereign_account = ::sovereign_account_id_of_child_para(para_id); - Self::fund_accounts(vec![(sovereign_account.clone(), amount)]); - sovereign_account - } - } - } - }; -} - -#[macro_export] -macro_rules! impl_assert_events_helpers_for_relay_chain { - ( $chain:ident ) => { - $crate::impls::paste::paste! { - type [<$chain RuntimeEvent>] = <$chain as $crate::impls::Chain>::RuntimeEvent; - - impl $chain { - /// Asserts a dispatchable is completely executed and XCM sent - pub fn assert_xcm_pallet_attempted_complete(expected_weight: Option<$crate::impls::Weight>) { - $crate::impls::assert_expected_events!( - Self, - vec![ - [<$chain RuntimeEvent>]::XcmPallet( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Complete(weight) } - ) => { - weight: $crate::impls::weight_within_threshold( - ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), - expected_weight.unwrap_or(*weight), - *weight - ), - }, - ] - ); - } - - /// Asserts a dispatchable is incompletely executed and XCM sent - pub fn assert_xcm_pallet_attempted_incomplete( - expected_weight: Option<$crate::impls::Weight>, - expected_error: Option<$crate::impls::Error>, - ) { - $crate::impls::assert_expected_events!( - Self, - vec![ - // Dispatchable is properly executed and XCM message sent - [<$chain RuntimeEvent>]::XcmPallet( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Incomplete(weight, error) } - ) => { - weight: $crate::impls::weight_within_threshold( - ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), - expected_weight.unwrap_or(*weight), - *weight - ), - error: *error == expected_error.unwrap_or(*error), - }, - ] - ); - } - - /// Asserts a XCM message is sent - pub fn assert_xcm_pallet_sent() { - $crate::impls::assert_expected_events!( - Self, - vec![ - [<$chain RuntimeEvent>]::XcmPallet($crate::impls::pallet_xcm::Event::Sent { .. }) => {}, - ] - ); - } - - /// Asserts a XCM from System Parachain is succesfully received and proccessed - pub fn assert_ump_queue_processed( - expected_success: bool, - expected_id: Option<$crate::impls::ParaId>, - expected_weight: Option<$crate::impls::Weight>, - ) { - $crate::impls::assert_expected_events!( - Self, - vec![ - // XCM is succesfully received and proccessed - [<$chain RuntimeEvent>]::MessageQueue($crate::impls::pallet_message_queue::Event::Processed { - origin: $crate::impls::AggregateMessageOrigin::Ump($crate::impls::UmpQueueId::Para(id)), - weight_used, - success, - .. - }) => { - id: *id == expected_id.unwrap_or(*id), - weight_used: $crate::impls::weight_within_threshold( - ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), - expected_weight.unwrap_or(*weight_used), - *weight_used - ), - success: *success == expected_success, - }, - ] - ); - } - } - } - }; -} - -#[macro_export] -macro_rules! impl_hrmp_channels_helpers_for_relay_chain { - ( $chain:ident ) => { - $crate::impls::paste::paste! { - impl $chain { - /// Init open channel request with another Parachain - pub fn init_open_channel_call( - recipient_para_id: $crate::impls::ParaId, - max_capacity: u32, - max_message_size: u32, - ) -> $crate::impls::DoubleEncoded<()> { - use $crate::impls::Encode; - - ::RuntimeCall::Hrmp($crate::impls::hrmp::Call::< - ::Runtime, - >::hrmp_init_open_channel { - recipient: recipient_para_id, - proposed_max_capacity: max_capacity, - proposed_max_message_size: max_message_size, - }) - .encode() - .into() - } - /// Recipient Parachain accept the open request from another Parachain - pub fn accept_open_channel_call(sender_para_id: $crate::impls::ParaId) -> $crate::impls::DoubleEncoded<()> { - use $crate::impls::Encode; - - ::RuntimeCall::Hrmp($crate::impls::hrmp::Call::< - ::Runtime, - >::hrmp_accept_open_channel { - sender: sender_para_id, - }) - .encode() - .into() - } - - /// A root origin force to open a channel between two Parachains - pub fn force_process_hrmp_open(sender: $crate::impls::ParaId, recipient: $crate::impls::ParaId) { - use $crate::impls::Chain; - - ::execute_with(|| { - let relay_root_origin = ::RuntimeOrigin::root(); - - // Force process HRMP open channel requests without waiting for the next session - $crate::impls::assert_ok!(]>::Hrmp::force_process_hrmp_open( - relay_root_origin, - u32::MAX, - )); - - let channel_id = $crate::impls::HrmpChannelId { sender, recipient }; - - let hrmp_channel_exist = $crate::impls::hrmp::HrmpChannels::< - ::Runtime, - >::contains_key(&channel_id); - - // Check the HRMP channel has been successfully registrered - assert!(hrmp_channel_exist) - }); - } - } - } - }; -} - -#[macro_export] -macro_rules! impl_accounts_helpers_for_parachain { - ( $chain:ident ) => { - $crate::impls::paste::paste! { - impl $chain { - /// Fund a set of accounts with a balance - pub fn fund_accounts(accounts: Vec<($crate::impls::AccountId, $crate::impls::Balance)>) { - ::execute_with(|| { - for account in accounts { - $crate::impls::assert_ok!(]>::Balances::force_set_balance( - ::RuntimeOrigin::root(), - account.0.into(), - account.1, - )); - } - }); - } - } - } - }; -} - -#[macro_export] -macro_rules! impl_assert_events_helpers_for_parachain { - ( $chain:ident ) => { - $crate::impls::paste::paste! { - type [<$chain RuntimeEvent>] = <$chain as $crate::impls::Chain>::RuntimeEvent; - - impl $chain { - /// Asserts a dispatchable is completely executed and XCM sent - pub fn assert_xcm_pallet_attempted_complete(expected_weight: Option<$crate::impls::Weight>) { - $crate::impls::assert_expected_events!( - Self, - vec![ - [<$chain RuntimeEvent>]::PolkadotXcm( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Complete(weight) } - ) => { - weight: $crate::impls::weight_within_threshold( - ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), - expected_weight.unwrap_or(*weight), - *weight - ), - }, - ] - ); - } - - /// Asserts a dispatchable is incompletely executed and XCM sent - pub fn assert_xcm_pallet_attempted_incomplete( - expected_weight: Option<$crate::impls::Weight>, - expected_error: Option<$crate::impls::Error>, - ) { - $crate::impls::assert_expected_events!( - Self, - vec![ - // Dispatchable is properly executed and XCM message sent - [<$chain RuntimeEvent>]::PolkadotXcm( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Incomplete(weight, error) } - ) => { - weight: $crate::impls::weight_within_threshold( - ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), - expected_weight.unwrap_or(*weight), - *weight - ), - error: *error == expected_error.unwrap_or(*error), - }, - ] - ); - } - - /// Asserts a dispatchable throws and error when trying to be sent - pub fn assert_xcm_pallet_attempted_error(expected_error: Option<$crate::impls::Error>) { - $crate::impls::assert_expected_events!( - Self, - vec![ - // Execution fails in the origin with `Barrier` - [<$chain RuntimeEvent>]::PolkadotXcm( - $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Error(error) } - ) => { - error: *error == expected_error.unwrap_or(*error), - }, - ] - ); - } - - /// Asserts a XCM message is sent - pub fn assert_xcm_pallet_sent() { - $crate::impls::assert_expected_events!( - Self, - vec![ - [<$chain RuntimeEvent>]::PolkadotXcm($crate::impls::pallet_xcm::Event::Sent { .. }) => {}, - ] - ); - } - - /// Asserts a XCM message is sent to Relay Chain - pub fn assert_parachain_system_ump_sent() { - $crate::impls::assert_expected_events!( - Self, - vec![ - [<$chain RuntimeEvent>]::ParachainSystem( - $crate::impls::cumulus_pallet_parachain_system::Event::UpwardMessageSent { .. } - ) => {}, - ] - ); - } - - /// Asserts a XCM from Relay Chain is completely executed - pub fn assert_dmp_queue_complete(expected_weight: Option<$crate::impls::Weight>) { - $crate::impls::assert_expected_events!( - Self, - vec![ - [<$chain RuntimeEvent>]::DmpQueue($crate::impls::cumulus_pallet_dmp_queue::Event::ExecutedDownward { - outcome: $crate::impls::Outcome::Complete(weight), .. - }) => { - weight: $crate::impls::weight_within_threshold( - ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), - expected_weight.unwrap_or(*weight), - *weight - ), - }, - ] - ); - } - - /// Asserts a XCM from Relay Chain is incompletely executed - pub fn assert_dmp_queue_incomplete( - expected_weight: Option<$crate::impls::Weight>, - expected_error: Option<$crate::impls::Error>, - ) { - $crate::impls::assert_expected_events!( - Self, - vec![ - [<$chain RuntimeEvent>]::DmpQueue($crate::impls::cumulus_pallet_dmp_queue::Event::ExecutedDownward { - outcome: $crate::impls::Outcome::Incomplete(weight, error), .. - }) => { - weight: $crate::impls::weight_within_threshold( - ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), - expected_weight.unwrap_or(*weight), - *weight - ), - error: *error == expected_error.unwrap_or(*error), - }, - ] - ); - } - - /// Asserts a XCM from another Parachain is completely executed - pub fn assert_xcmp_queue_success(expected_weight: Option<$crate::impls::Weight>) { - $crate::impls::assert_expected_events!( - Self, - vec![ - [<$chain RuntimeEvent>]::XcmpQueue( - $crate::impls::cumulus_pallet_xcmp_queue::Event::Success { weight, .. } - ) => { - weight: $crate::impls::weight_within_threshold( - ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), - expected_weight.unwrap_or(*weight), - *weight - ), - }, - ] - ); - } - } - } - }; -} - -#[macro_export] -macro_rules! impl_assets_helpers_for_parachain { - ( $chain:ident, $relay_chain:ident ) => { - $crate::impls::paste::paste! { - impl $chain { - /// Returns the encoded call for `force_create` from the assets pallet - pub fn force_create_asset_call( - asset_id: u32, - owner: $crate::impls::AccountId, - is_sufficient: bool, - min_balance: $crate::impls::Balance, - ) -> $crate::impls::DoubleEncoded<()> { - use $crate::impls::{Chain, Encode}; - - ::RuntimeCall::Assets($crate::impls::pallet_assets::Call::< - ::Runtime, - $crate::impls::pallet_assets::Instance1, - >::force_create { - id: asset_id.into(), - owner: owner.into(), - is_sufficient, - min_balance, - }) - .encode() - .into() - } - - /// Returns a `VersionedXcm` for `force_create` from the assets pallet - pub fn force_create_asset_xcm( - origin_kind: $crate::impls::OriginKind, - asset_id: u32, - owner: $crate::impls::AccountId, - is_sufficient: bool, - min_balance: $crate::impls::Balance, - ) -> $crate::impls::VersionedXcm<()> { - let call = Self::force_create_asset_call(asset_id, owner, is_sufficient, min_balance); - $crate::impls::xcm_transact_unpaid_execution(call, origin_kind) - } - - /// Mint assets making use of the assets pallet - pub fn mint_asset( - signed_origin: ::RuntimeOrigin, - id: u32, - beneficiary: $crate::impls::AccountId, - amount_to_mint: u128, - ) { - ::execute_with(|| { - $crate::impls::assert_ok!(]>::Assets::mint( - signed_origin, - id.into(), - beneficiary.clone().into(), - amount_to_mint - )); - - type RuntimeEvent = <$chain as $crate::impls::Chain>::RuntimeEvent; - - $crate::impls::assert_expected_events!( - Self, - vec![ - RuntimeEvent::Assets($crate::impls::pallet_assets::Event::Issued { asset_id, owner, amount }) => { - asset_id: *asset_id == id, - owner: *owner == beneficiary.clone().into(), - amount: *amount == amount_to_mint, - }, - ] - ); - }); - } - - /// Force create and mint assets making use of the assets pallet - pub fn force_create_and_mint_asset( - id: u32, - min_balance: u128, - is_sufficient: bool, - asset_owner: $crate::impls::AccountId, - amount_to_mint: u128, - ) { - use $crate::impls::{bx, Chain, RelayChain, Parachain, Inspect, TestExt}; - // Init values for Relay Chain - let root_origin = <$relay_chain as Chain>::RuntimeOrigin::root(); - let destination = <$relay_chain>::child_location_of(<$chain>::para_id()); - let xcm = Self::force_create_asset_xcm( - $crate::impls::OriginKind::Superuser, - id, - asset_owner.clone(), - is_sufficient, - min_balance, - ); - - <$relay_chain>::execute_with(|| { - $crate::impls::assert_ok!(<$relay_chain as [<$relay_chain Pallet>]>::XcmPallet::send( - root_origin, - bx!(destination.into()), - bx!(xcm), - )); - - <$relay_chain>::assert_xcm_pallet_sent(); - }); - - Self::execute_with(|| { - Self::assert_dmp_queue_complete(Some($crate::impls::Weight::from_parts(1_020_000_000, 200_000))); - - type RuntimeEvent = <$chain as $crate::impls::Chain>::RuntimeEvent; - - $crate::impls::assert_expected_events!( - Self, - vec![ - // Asset has been created - RuntimeEvent::Assets($crate::impls::pallet_assets::Event::ForceCreated { asset_id, owner }) => { - asset_id: *asset_id == id, - owner: *owner == asset_owner.clone(), - }, - ] - ); - - assert!(]>::Assets::asset_exists(id.into())); - }); - - let signed_origin = ::RuntimeOrigin::signed(asset_owner.clone()); - - // Mint asset for System Parachain's sender - Self::mint_asset(signed_origin, id, asset_owner, amount_to_mint); - } - } - } - }; -} diff --git a/integration-tests/common/src/lib.rs b/integration-tests/common/src/lib.rs deleted file mode 100644 index d2e1c5faf..000000000 --- a/integration-tests/common/src/lib.rs +++ /dev/null @@ -1,248 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -pub mod constants; -pub mod impls; -pub mod xcm_helpers; - -pub use constants::{ - accounts::{ALICE, BOB}, - bifrost_kusama, bifrost_polkadot, kusama, polkadot, -}; - -// Substrate -use frame_support::traits::OnInitialize; - -// Cumulus -use crate::constants::{ - asset_hub_kusama, asset_hub_polkadot, bridge_hub_kusama, bridge_hub_polkadot, -}; -use polkadot_primitives::runtime_api::runtime_decl_for_parachain_host::ParachainHostV7; -use sp_runtime::traits::AccountIdConversion; -use xcm_emulator::{ - decl_test_networks, decl_test_parachains, decl_test_relay_chains, DefaultMessageProcessor, -}; - -decl_test_relay_chains! { - #[api_version(5)] - pub struct Polkadot { - genesis = polkadot::genesis(), - on_init = (), - runtime = polkadot_runtime, - core = { - MessageProcessor: DefaultMessageProcessor, - SovereignAccountOf: polkadot_runtime::xcm_config::SovereignAccountOf, - }, - pallets = { - System: polkadot_runtime::System, - XcmPallet: polkadot_runtime::XcmPallet, - Balances: polkadot_runtime::Balances, - Hrmp: polkadot_runtime::Hrmp, - } - }, - #[api_version(5)] - pub struct Kusama { - genesis = kusama::genesis(), - on_init = (), - runtime = kusama_runtime, - core = { - MessageProcessor: DefaultMessageProcessor, - SovereignAccountOf: kusama_runtime::xcm_config::SovereignAccountOf, - }, - pallets = { - System: kusama_runtime::System, - XcmPallet: kusama_runtime::XcmPallet, - Balances: kusama_runtime::Balances, - Hrmp: kusama_runtime::Hrmp, - Referenda: kusama_runtime::Referenda, - } - } -} - -decl_test_parachains! { - // Polkadot Parachains - pub struct BifrostPolkadot { - genesis = bifrost_polkadot::genesis(), - on_init = { - bifrost_polkadot_runtime::AuraExt::on_initialize(1); - }, - runtime = bifrost_polkadot_runtime, - core = { - XcmpMessageHandler: bifrost_polkadot_runtime::XcmpQueue, - DmpMessageHandler: bifrost_polkadot_runtime::DmpQueue, - LocationToAccountId: bifrost_polkadot_runtime::xcm_config::LocationToAccountId, - ParachainInfo: bifrost_polkadot_runtime::ParachainInfo, - }, - pallets = { - System: bifrost_polkadot_runtime::System, - PolkadotXcm: bifrost_polkadot_runtime::PolkadotXcm, - Tokens: bifrost_polkadot_runtime::Tokens, - XTokens: bifrost_polkadot_runtime::XTokens, - Balances: bifrost_polkadot_runtime::Balances, - } - }, - pub struct AssetHubPolkadot { - genesis = asset_hub_polkadot::genesis(), - on_init = { - asset_hub_polkadot_runtime::AuraExt::on_initialize(1); - }, - runtime = asset_hub_polkadot_runtime, - core = { - XcmpMessageHandler: asset_hub_polkadot_runtime::XcmpQueue, - DmpMessageHandler: asset_hub_polkadot_runtime::DmpQueue, - LocationToAccountId: asset_hub_polkadot_runtime::xcm_config::LocationToAccountId, - ParachainInfo: asset_hub_polkadot_runtime::ParachainInfo, - }, - pallets = { - PolkadotXcm: asset_hub_polkadot_runtime::PolkadotXcm, - Assets: asset_hub_polkadot_runtime::Assets, - Balances: asset_hub_polkadot_runtime::Balances, - } - }, - pub struct BridgeHubPolkadot { - genesis = bridge_hub_polkadot::genesis(), - on_init = { - bridge_hub_polkadot_runtime::AuraExt::on_initialize(1); - }, - runtime = bridge_hub_polkadot_runtime, - core = { - XcmpMessageHandler: bridge_hub_polkadot_runtime::XcmpQueue, - DmpMessageHandler: bridge_hub_polkadot_runtime::DmpQueue, - LocationToAccountId: bridge_hub_polkadot_runtime::xcm_config::LocationToAccountId, - ParachainInfo: bridge_hub_polkadot_runtime::ParachainInfo, - }, - pallets = { - PolkadotXcm: bridge_hub_polkadot_runtime::PolkadotXcm, - } - }, - // Kusama Parachains - pub struct BifrostKusama { - genesis = bifrost_kusama::genesis(), - on_init = { - bifrost_kusama_runtime::AuraExt::on_initialize(1); - }, - runtime = bifrost_kusama_runtime, - core = { - XcmpMessageHandler: bifrost_kusama_runtime::XcmpQueue, - DmpMessageHandler: bifrost_kusama_runtime::DmpQueue, - LocationToAccountId: bifrost_kusama_runtime::xcm_config::LocationToAccountId, - ParachainInfo: bifrost_kusama_runtime::ParachainInfo, - }, - pallets = { - System: bifrost_kusama_runtime::System, - PolkadotXcm: bifrost_kusama_runtime::PolkadotXcm, - Tokens: bifrost_kusama_runtime::Tokens, - XTokens: bifrost_kusama_runtime::XTokens, - Balances: bifrost_kusama_runtime::Balances, - } - }, - pub struct AssetHubKusama { - genesis = asset_hub_kusama::genesis(), - on_init = { - asset_hub_kusama_runtime::AuraExt::on_initialize(1); - }, - runtime = asset_hub_kusama_runtime, - core = { - XcmpMessageHandler: asset_hub_kusama_runtime::XcmpQueue, - DmpMessageHandler: asset_hub_kusama_runtime::DmpQueue, - LocationToAccountId: asset_hub_kusama_runtime::xcm_config::LocationToAccountId, - ParachainInfo: asset_hub_kusama_runtime::ParachainInfo, - }, - pallets = { - PolkadotXcm: asset_hub_kusama_runtime::PolkadotXcm, - Assets: asset_hub_kusama_runtime::Assets, - ForeignAssets: asset_hub_kusama_runtime::ForeignAssets, - PoolAssets: asset_hub_kusama_runtime::PoolAssets, - AssetConversion: asset_hub_kusama_runtime::AssetConversion, - Balances: asset_hub_kusama_runtime::Balances, - } - }, - pub struct BridgeHubKusama { - genesis = bridge_hub_kusama::genesis(), - on_init = { - bridge_hub_kusama_runtime::AuraExt::on_initialize(1); - }, - runtime = bridge_hub_kusama_runtime, - core = { - XcmpMessageHandler: bridge_hub_kusama_runtime::XcmpQueue, - DmpMessageHandler: bridge_hub_kusama_runtime::DmpQueue, - LocationToAccountId: bridge_hub_kusama_runtime::xcm_config::LocationToAccountId, - ParachainInfo: bridge_hub_kusama_runtime::ParachainInfo, - }, - pallets = { - PolkadotXcm: bridge_hub_kusama_runtime::PolkadotXcm, - } - }, -} - -decl_test_networks! { - pub struct PolkadotMockNet { - relay_chain = Polkadot, - parachains = vec![ - BifrostPolkadot, - AssetHubPolkadot, - BridgeHubPolkadot, - ], - // TODO: uncomment when https://github.com/paritytech/cumulus/pull/2528 is merged - // bridge = PolkadotKusamaMockBridge - bridge = () - }, - pub struct KusamaMockNet { - relay_chain = Kusama, - parachains = vec![ - BifrostKusama, - AssetHubKusama, - BridgeHubKusama, - ], - // TODO: uncomment when https://github.com/paritytech/cumulus/pull/2528 is merged - // bridge = KusamaPolkadotMockBridge - bridge = () - }, -} - -// Polkadot implementation -impl_accounts_helpers_for_relay_chain!(Polkadot); -impl_assert_events_helpers_for_relay_chain!(Polkadot); -impl_hrmp_channels_helpers_for_relay_chain!(Polkadot); - -// Kusama implementation -impl_accounts_helpers_for_relay_chain!(Kusama); -impl_assert_events_helpers_for_relay_chain!(Kusama); -impl_hrmp_channels_helpers_for_relay_chain!(Kusama); - -// BifrostPolkadot implementation -impl_accounts_helpers_for_parachain!(BifrostPolkadot); -impl_assert_events_helpers_for_parachain!(BifrostPolkadot); - -// BifrostKusama implementation -impl_accounts_helpers_for_parachain!(BifrostKusama); -impl_assert_events_helpers_for_parachain!(BifrostKusama); - -// AssetHubPolkadot implementation -impl_accounts_helpers_for_parachain!(AssetHubPolkadot); -impl_assets_helpers_for_parachain!(AssetHubPolkadot, Polkadot); -impl_assert_events_helpers_for_parachain!(AssetHubPolkadot); - -// AssetHubKusama implementation -impl_accounts_helpers_for_parachain!(AssetHubKusama); -impl_assets_helpers_for_parachain!(AssetHubKusama, Kusama); -impl_assert_events_helpers_for_parachain!(AssetHubKusama); - -impl_test_accounts_helpers_for_chain! { - Polkadot, Kusama, BifrostPolkadot, BifrostKusama -} diff --git a/integration-tests/common/src/xcm_helpers.rs b/integration-tests/common/src/xcm_helpers.rs deleted file mode 100644 index cd5fe1a98..000000000 --- a/integration-tests/common/src/xcm_helpers.rs +++ /dev/null @@ -1,68 +0,0 @@ -// This file is part of Bifrost. - -// Copyright (C) Liebi Technologies PTE. LTD. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use parachains_common::AccountId; -use xcm::{ - prelude::{ - AccountId32, All, BuyExecution, DepositAsset, MultiAsset, MultiAssets, MultiLocation, - OriginKind, RefundSurplus, Transact, UnpaidExecution, VersionedXcm, Weight, WeightLimit, - WithdrawAsset, Xcm, X1, - }, - DoubleEncoded, -}; - -/// Helper method to build a XCM with a `Transact` instruction and paying for its execution -pub fn xcm_transact_paid_execution( - call: DoubleEncoded<()>, - origin_kind: OriginKind, - native_asset: MultiAsset, - beneficiary: AccountId, -) -> VersionedXcm<()> { - let weight_limit = WeightLimit::Unlimited; - let require_weight_at_most = Weight::from_parts(1000000000, 200000); - let native_assets: MultiAssets = native_asset.clone().into(); - - VersionedXcm::from(Xcm(vec![ - WithdrawAsset(native_assets), - BuyExecution { fees: native_asset, weight_limit }, - Transact { require_weight_at_most, origin_kind, call }, - RefundSurplus, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: X1(AccountId32 { network: None, id: beneficiary.into() }), - }, - }, - ])) -} - -/// Helper method to build a XCM with a `Transact` instruction without paying for its execution -pub fn xcm_transact_unpaid_execution( - call: DoubleEncoded<()>, - origin_kind: OriginKind, -) -> VersionedXcm<()> { - let weight_limit = WeightLimit::Unlimited; - let require_weight_at_most = Weight::from_parts(1000000000, 200000); - let check_origin = None; - - VersionedXcm::from(Xcm(vec![ - UnpaidExecution { weight_limit, check_origin }, - Transact { require_weight_at_most, origin_kind, call }, - ])) -} diff --git a/integration-tests/bifrost-polkadot/src/lib.rs b/integration-tests/src/lib.rs similarity index 97% rename from integration-tests/bifrost-polkadot/src/lib.rs rename to integration-tests/src/lib.rs index 122d5b2fd..99ac59f58 100644 --- a/integration-tests/bifrost-polkadot/src/lib.rs +++ b/integration-tests/src/lib.rs @@ -17,3 +17,6 @@ // along with this program. If not, see . #![cfg(test)] + +mod mock; +mod tests; diff --git a/integration-tests/src/mock/bifrost.rs b/integration-tests/src/mock/bifrost.rs new file mode 100644 index 000000000..669809d20 --- /dev/null +++ b/integration-tests/src/mock/bifrost.rs @@ -0,0 +1,336 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +use frame_support::{ + construct_runtime, derive_impl, parameter_types, + traits::{ConstU32, Everything, Nothing}, + weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, +}; +use frame_system::EnsureRoot; +use orml_traits::{location::RelativeReserveProvider, parameter_type_with_key}; +use sp_runtime::{traits::IdentityLookup, AccountId32}; +use sp_std::prelude::*; + +use crate::mock::{mock_message_queue, Amount}; +use bifrost_asset_registry::AssetIdMaps; +use bifrost_polkadot_runtime::{ + xcm_config::{ + BaseXcmWeight, BifrostAccountIdToLocation, BifrostAssetTransactor, MaxAssetsForTransfer, + ParachainMinFee, SelfRelativeLocation, UniversalLocation, + }, + BifrostCurrencyIdConvert, BifrostTreasuryAccount, MaxLengthLimit, MaxRefundPerBlock, + MaxTypeEntryPerBlock, NativeCurrencyId, OnRefund, SelfParaChainId, Slpx, + SubAccountIndexMultiLocationConvertor, VtokenMinting, XcmInterface, +}; +use bifrost_primitives::CurrencyId; +use bifrost_slp::QueryResponseManager; +use pallet_xcm::{QueryStatus, XcmPassthrough}; +use polkadot_parachain_primitives::primitives::Sibling; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowUnpaidExecutionFrom, EnsureXcmOrigin, FixedRateOfFungible, + FixedWeightBounds, FrameTransactionalProcessor, NativeAsset, ParentIsPreset, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, +}; +use xcm_executor::{traits::QueryHandler, Config, XcmExecutor}; + +pub type AccountId = AccountId32; +pub type Balance = u128; +pub type BlockNumber = u64; + +parameter_types! { + pub const BlockHashCount: u64 = 250; +} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Block = Block; + type AccountData = pallet_balances::AccountData; +} + +parameter_types! { + pub ExistentialDeposit: Balance = 1; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; +} + +impl pallet_balances::Config for Runtime { + type MaxLocks = MaxLocks; + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; + type FreezeIdentifier = (); + type MaxFreezes = ConstU32<0>; +} + +impl parachain_info::Config for Runtime {} + +parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: CurrencyId| -> Balance { + Default::default() + }; +} + +impl orml_tokens::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = CurrencyId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type CurrencyHooks = (); + type MaxLocks = ConstU32<50>; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type DustRemovalWhitelist = Everything; +} + +parameter_types! { + pub const XtokensRateLimiterId: u8 = 0; +} + +impl orml_xtokens::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type CurrencyId = CurrencyId; + type CurrencyIdConvert = BifrostCurrencyIdConvert; + type AccountIdToLocation = BifrostAccountIdToLocation; + type SelfLocation = SelfRelativeLocation; + type LocationsFilter = Everything; + type MinXcmFee = ParachainMinFee; + type XcmExecutor = XcmExecutor; + type Weigher = FixedWeightBounds; + type BaseXcmWeight = BaseXcmWeight; + type UniversalLocation = UniversalLocation; + type MaxAssetsForTransfer = MaxAssetsForTransfer; + type ReserveProvider = RelativeReserveProvider; + type RateLimiter = (); + type RateLimiterId = (); +} + +parameter_types! { + pub const ReservedXcmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0); + pub const ReservedDmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0); +} + +parameter_types! { + pub const KsmLocation: Location = Location::parent(); + pub const RelayNetwork: NetworkId = NetworkId::Kusama; +} + +pub type LocationToAccountId = ( + ParentIsPreset, + SiblingParachainConvertsVia, + AccountId32Aliases, +); + +pub type XcmOriginToCallOrigin = ( + SovereignSignedViaLocation, + SignedAccountId32AsNative, + XcmPassthrough, +); + +parameter_types! { + pub const UnitWeightCost: Weight = Weight::from_parts(1, 1); + pub KsmPerSecondPerByte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1, 1); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; +} + +pub type XcmRouter = super::ParachainXcmRouter; +pub type Barrier = AllowUnpaidExecutionFrom; + +pub struct XcmConfig; +impl Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = BifrostAssetTransactor; + type OriginConverter = XcmOriginToCallOrigin; + type IsReserve = NativeAsset; + type IsTeleporter = (); + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = FixedRateOfFungible; + type ResponseHandler = (); + type AssetTrap = (); + type AssetLocker = (); + type AssetExchanger = (); + type AssetClaims = (); + type SubscriptionService = (); + type PalletInstancesInfo = (); + type FeeManager = (); + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; + type Aliasers = Nothing; + type TransactionalProcessor = FrameTransactionalProcessor; +} + +impl mock_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} + +pub type LocalOriginToLocation = SignedToAccountId32; + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + type ExecuteXcmOrigin = EnsureXcmOrigin; + type XcmExecuteFilter = Everything; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Nothing; + type XcmReserveTransferFilter = Everything; + type Weigher = FixedWeightBounds; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = (); + type TrustedLockers = (); + type SovereignAccountOf = LocationToAccountId; + type MaxLockers = ConstU32<8>; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); + type WeightInfo = pallet_xcm::TestWeightInfo; + type AdminOrigin = EnsureRoot; +} + +impl bifrost_currencies::Config for Runtime { + type GetNativeCurrencyId = NativeCurrencyId; + type MultiCurrency = Tokens; + type NativeCurrency = + bifrost_currencies::BasicCurrencyAdapter; + type WeightInfo = (); +} + +// impl bifrost_xcm_interface::Config for Runtime { +// type RuntimeEvent = RuntimeEvent; +// type UpdateOrigin = EnsureRoot; +// type MultiCurrency = Currencies; +// type RelayNetwork = bifrost_polkadot_runtime::xcm_config::RelayNetwork; +// type RelaychainCurrencyId = RelayCurrencyId; +// type ParachainSovereignAccount = ParachainAccount; +// type XcmExecutor = XcmExecutor; +// type AccountIdToLocation = BifrostAccountIdToLocation; +// type SalpHelper = Salp; +// type ParachainId = SelfParaChainId; +// type CallBackTimeOut = ConstU32<10>; +// type CurrencyIdConvert = AssetIdMaps; +// } + +pub struct SubstrateResponseManager; +impl QueryResponseManager + for SubstrateResponseManager +{ + fn get_query_response_record(query_id: QueryId) -> bool { + if let Some(QueryStatus::Ready { .. }) = PolkadotXcm::query(query_id) { + true + } else { + false + } + } + + fn create_query_record( + responder: Location, + call_back: Option, + timeout: BlockNumber, + ) -> u64 { + if let Some(call_back) = call_back { + PolkadotXcm::new_notify_query(responder.clone(), call_back, timeout, Here) + } else { + PolkadotXcm::new_query(responder, timeout, Here) + } + } + + fn remove_query_record(query_id: bifrost_slp::QueryId) -> bool { + // Temporarily banned. Querries from pallet_xcm cannot be removed unless it is in ready + // status. And we are not allowed to mannually change query status. + // So in the manual mode, it is not possible to remove the query at all. + // PolkadotXcm::take_response(query_id).is_some() + + PolkadotXcm::take_response(query_id); + true + } +} + +impl bifrost_slp::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type MultiCurrency = Currencies; + type ControlOrigin = EnsureRoot; + type WeightInfo = (); + type VtokenMinting = VtokenMinting; + type BifrostSlpx = Slpx; + type AccountConverter = SubAccountIndexMultiLocationConvertor; + type ParachainId = SelfParaChainId; + type SubstrateResponseManager = SubstrateResponseManager; + type MaxTypeEntryPerBlock = MaxTypeEntryPerBlock; + type MaxRefundPerBlock = MaxRefundPerBlock; + type OnRefund = OnRefund; + type ParachainStaking = (); + type XcmTransfer = XTokens; + type MaxLengthLimit = MaxLengthLimit; + type XcmWeightAndFeeHandler = XcmInterface; + type ChannelCommission = (); + type StablePoolHandler = (); + type AssetIdMaps = AssetIdMaps; + type TreasuryAccount = BifrostTreasuryAccount; +} + +impl bifrost_asset_registry::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type RegisterOrigin = EnsureRoot; + type WeightInfo = (); +} + +type Block = frame_system::mocking::MockBlock; + +construct_runtime!( + pub enum Runtime + { + System: frame_system, + ParachainInfo: parachain_info, + Balances: pallet_balances, + MessageQueue: mock_message_queue, + PolkadotXcm: pallet_xcm, + Tokens: orml_tokens, + XTokens: orml_xtokens, + Currencies: bifrost_currencies, + Slp: bifrost_slp, + AssetRegistry: bifrost_asset_registry + } +); diff --git a/integration-tests/src/mock/mock_message_queue/mod.rs b/integration-tests/src/mock/mock_message_queue/mod.rs new file mode 100644 index 000000000..d209c1074 --- /dev/null +++ b/integration-tests/src/mock/mock_message_queue/mod.rs @@ -0,0 +1,184 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +use cumulus_primitives_core::{ParaId, XcmpMessageFormat, XcmpMessageHandler}; +use frame_support::pallet_prelude::*; +use parity_scale_codec::{Decode, Encode}; +use polkadot_parachain_primitives::primitives::DmpMessageHandler; +use sp_std::prelude::*; +use xcm::{ + v4::{prelude::*, Weight}, + VersionedXcm, +}; + +pub use module::*; + +#[frame_support::pallet] +pub mod module { + use super::*; + + type RelayBlockNumber = u32; + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + type XcmExecutor: ExecuteXcm; + } + + #[pallet::call] + impl Pallet {} + + #[pallet::pallet] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::storage] + #[pallet::getter(fn parachain_id)] + pub(super) type ParachainId = StorageValue<_, ParaId, ValueQuery>; + + #[pallet::storage] + #[pallet::getter(fn received_dmp)] + /// A queue of received DMP messages + pub(super) type ReceivedDmp = StorageValue<_, Vec>, ValueQuery>; + + impl Get for Pallet { + fn get() -> ParaId { + Self::parachain_id() + } + } + + pub type MessageId = [u8; 32]; + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + // XCMP + /// Some XCM was executed OK. + Success(Option), + /// Some XCM failed. + Fail(Option, XcmError), + /// Bad XCM version used. + BadVersion(Option), + /// Bad XCM format used. + BadFormat(Option), + + // DMP + /// Downward message is invalid XCM. + InvalidFormat(MessageId), + /// Downward message is unsupported version of XCM. + UnsupportedVersion(MessageId), + /// Downward message executed with the given outcome. + ExecutedDownward(MessageId, Outcome), + } + + impl Pallet { + pub fn set_para_id(para_id: ParaId) { + ParachainId::::put(para_id); + } + + fn handle_xcmp_message( + sender: ParaId, + _sent_at: RelayBlockNumber, + xcm: VersionedXcm, + max_weight: Weight, + ) -> Result { + use sp_runtime::traits::Hash; + let hash = Encode::using_encoded(&xcm, T::Hashing::hash); + let mut message_hash = Encode::using_encoded(&xcm, sp_io::hashing::blake2_256); + let (result, event) = match Xcm::::try_from(xcm) { + Ok(xcm) => { + let location = (Parent, Parachain(sender.into())); + match T::XcmExecutor::prepare_and_execute( + location, + xcm, + &mut message_hash, + max_weight, + Weight::zero(), + ) { + Outcome::Error { error } => (Err(error), Event::Fail(Some(hash), error)), + Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))), + // As far as the caller is concerned, this was dispatched without error, so + // we just report the weight used. + Outcome::Incomplete { used, error } => + (Ok(used), Event::Fail(Some(hash), error)), + } + }, + Err(()) => (Err(XcmError::UnhandledXcmVersion), Event::BadVersion(Some(hash))), + }; + Self::deposit_event(event); + result + } + } + + impl XcmpMessageHandler for Pallet { + fn handle_xcmp_messages<'a, I: Iterator>( + iter: I, + max_weight: Weight, + ) -> Weight { + for (sender, sent_at, data) in iter { + let mut data_ref = data; + let _ = XcmpMessageFormat::decode(&mut data_ref) + .expect("Simulator encodes with versioned xcm format; qed"); + + let mut remaining_fragments = data_ref; + while !remaining_fragments.is_empty() { + if let Ok(xcm) = + VersionedXcm::::decode(&mut remaining_fragments) + { + let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight); + } else { + debug_assert!(false, "Invalid incoming XCMP message data"); + } + } + } + max_weight + } + } + + impl DmpMessageHandler for Pallet { + fn handle_dmp_messages( + iter: impl Iterator)>, + limit: Weight, + ) -> Weight { + for (_sent_at, data) in iter { + let mut id = sp_io::hashing::blake2_256(&data[..]); + let maybe_versioned = VersionedXcm::::decode(&mut &data[..]); + match maybe_versioned { + Err(_) => { + Self::deposit_event(Event::InvalidFormat(id)); + }, + Ok(versioned) => match Xcm::try_from(versioned) { + Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), + Ok(x) => { + let outcome = T::XcmExecutor::prepare_and_execute( + Parent, + x.clone(), + &mut id, + limit, + Weight::zero(), + ); + >::append(x); + Self::deposit_event(Event::ExecutedDownward(id, outcome)); + }, + }, + } + } + limit + } + } +} diff --git a/integration-tests/src/mock/mod.rs b/integration-tests/src/mock/mod.rs new file mode 100644 index 000000000..d7423adf0 --- /dev/null +++ b/integration-tests/src/mock/mod.rs @@ -0,0 +1,101 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +pub mod bifrost; +mod mock_message_queue; +pub mod relaychain; + +use bifrost_primitives::CurrencyId; +use sp_io::TestExternalities; +use sp_runtime::{AccountId32, BuildStorage}; +use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, TestExt}; + +pub const ALICE: AccountId32 = AccountId32::new([0u8; 32]); +pub const BOB: AccountId32 = AccountId32::new([1u8; 32]); +pub type Amount = i128; + +decl_test_parachain! { + pub struct Bifrost { + Runtime = bifrost::Runtime, + XcmpMessageHandler = bifrost::MessageQueue, + DmpMessageHandler = bifrost::MessageQueue, + new_ext = para_ext(2030), + } +} + +decl_test_relay_chain! { + pub struct Relay { + Runtime = relaychain::Runtime, + RuntimeCall = relaychain::RuntimeCall, + RuntimeEvent = relaychain::RuntimeEvent, + XcmConfig = relaychain::XcmConfig, + MessageQueue = relaychain::MessageQueue, + System = relaychain::System, + new_ext = relay_ext(), + } +} + +decl_test_network! { + pub struct TestNet { + relay_chain = Relay, + parachains = vec![ + (2030, Bifrost), + ], + } +} + +pub type BifrostTokens = orml_tokens::Pallet; +pub type BifrostXTokens = orml_xtokens::Pallet; +pub type BifrostSlp = bifrost_slp::Pallet; + +pub type RelayBalances = pallet_balances::Pallet; +pub type RelaySystem = frame_system::Pallet; +pub type RelayXcmPallet = pallet_xcm::Pallet; + +pub fn para_ext(para_id: u32) -> TestExternalities { + use bifrost::{MessageQueue, Runtime, System}; + + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + + orml_tokens::GenesisConfig:: { + balances: vec![(ALICE, CurrencyId::Token2(0), 100_000_000_000)], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = TestExternalities::new(t); + ext.execute_with(|| { + System::set_block_number(1); + MessageQueue::set_para_id(para_id.into()); + }); + ext +} + +pub fn relay_ext() -> TestExternalities { + use relaychain::{Runtime, System}; + + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + + pallet_balances::GenesisConfig:: { balances: vec![(ALICE, 100_000_000_000)] } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} diff --git a/integration-tests/src/mock/relaychain.rs b/integration-tests/src/mock/relaychain.rs new file mode 100644 index 000000000..6772a2580 --- /dev/null +++ b/integration-tests/src/mock/relaychain.rs @@ -0,0 +1,222 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +use cumulus_primitives_core::ParaId; +use frame_support::{ + construct_runtime, derive_impl, parameter_types, + traits::{ConstU128, ConstU32, Everything, Nothing, ProcessMessage, ProcessMessageError}, + weights::{IdentityFee, WeightMeter}, +}; +use frame_system::EnsureRoot; +use polkadot_runtime_parachains::{ + configuration, + inclusion::{AggregateMessageOrigin, UmpQueueId}, + origin, shared, +}; +use sp_runtime::{traits::IdentityLookup, AccountId32}; +use xcm::v4::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, + ChildParachainConvertsVia, FixedWeightBounds, FungibleAdapter, IsConcrete, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + UsingComponents, +}; +use xcm_executor::{Config, XcmExecutor}; + +pub type AccountId = AccountId32; +pub type Balance = u128; + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Block = Block; + type AccountData = pallet_balances::AccountData; +} + +impl pallet_balances::Config for Runtime { + type MaxLocks = ConstU32<50>; + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ConstU128<1>; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; + type FreezeIdentifier = [u8; 8]; + type MaxFreezes = (); +} + +impl shared::Config for Runtime { + type DisabledValidators = (); +} + +impl configuration::Config for Runtime { + type WeightInfo = configuration::TestWeightInfo; +} + +parameter_types! { + pub DotLocation: Location = Here.into(); + pub const PolkadotNetwork: NetworkId = NetworkId::Polkadot; + pub UniversalLocation: InteriorLocation = [GlobalConsensus(PolkadotNetwork::get())].into(); +} + +pub type SovereignAccountOf = + (ChildParachainConvertsVia, AccountId32Aliases); + +pub type LocalAssetTransactor = + FungibleAdapter, SovereignAccountOf, AccountId, ()>; + +type LocalOriginConverter = ( + SovereignSignedViaLocation, + ChildParachainAsNative, + SignedAccountId32AsNative, +); + +pub type XcmRouter = super::RelayChainXcmRouter; +pub type Barrier = (TakeWeightCredit, AllowTopLevelPaidExecutionFrom); + +parameter_types! { + pub Polkadot: AssetFilter = Wild(AllOf { fun: WildFungible, id: AssetId(DotLocation::get()) }); + pub Statemine: Location = Parachain(3).into(); + pub PolkadotForStatemine: (AssetFilter, Location) = (Polkadot::get(), Statemine::get()); +} + +pub type TrustedTeleporters = xcm_builder::Case; + +parameter_types! { + pub const UnitWeightCost: Weight = Weight::from_parts(10, 10); + pub const BaseXcmWeight: Weight = Weight::from_parts(100_000_000, 100_000_000); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; +} + +pub struct XcmConfig; +impl Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = (); + type IsTeleporter = TrustedTeleporters; + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = UsingComponents, DotLocation, AccountId, Balances, ()>; + type ResponseHandler = (); + type AssetTrap = (); + type AssetClaims = (); + type SubscriptionService = XcmPallet; + type AssetLocker = XcmPallet; + type AssetExchanger = (); + type PalletInstancesInfo = (); + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type FeeManager = (); + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; + type Aliasers = (); + type TransactionalProcessor = (); +} + +pub type LocalOriginToLocation = SignedToAccountId32; + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type SendXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmRouter = XcmRouter; + // Anyone can execute XCM messages locally... + type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmExecuteFilter = Everything; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Everything; + type Weigher = FixedWeightBounds; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = (); + type TrustedLockers = (); + type SovereignAccountOf = (); + type MaxLockers = ConstU32<8>; + type WeightInfo = pallet_xcm::TestWeightInfo; + type AdminOrigin = EnsureRoot; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); +} + +impl origin::Config for Runtime {} + +type Block = frame_system::mocking::MockBlock; + +parameter_types! { + pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000); + pub const MessageQueueHeapSize: u32 = 65_536; + pub const MessageQueueMaxStale: u32 = 16; +} + +pub struct MessageProcessor; +impl ProcessMessage for MessageProcessor { + type Origin = AggregateMessageOrigin; + + fn process_message( + message: &[u8], + origin: Self::Origin, + meter: &mut WeightMeter, + id: &mut [u8; 32], + ) -> Result { + let para = match origin { + AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para, + }; + xcm_builder::ProcessXcmMessage::, RuntimeCall>::process_message( + message, + Junction::Parachain(para.into()), + meter, + id, + ) + } +} + +impl pallet_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Size = u32; + type HeapSize = MessageQueueHeapSize; + type MaxStale = MessageQueueMaxStale; + type ServiceWeight = MessageQueueServiceWeight; + type MessageProcessor = MessageProcessor; + type QueueChangeHandler = (); + type QueuePausedQuery = (); + type WeightInfo = (); +} + +construct_runtime!( + pub enum Runtime { + System: frame_system, + Balances: pallet_balances, + ParasOrigin: origin, + MessageQueue: pallet_message_queue, + XcmPallet: pallet_xcm, + } +); diff --git a/integration-tests/bifrost-kusama/src/lib.rs b/integration-tests/src/tests/mod.rs similarity index 84% rename from integration-tests/bifrost-kusama/src/lib.rs rename to integration-tests/src/tests/mod.rs index a96e16acb..2639991d6 100644 --- a/integration-tests/bifrost-kusama/src/lib.rs +++ b/integration-tests/src/tests/mod.rs @@ -16,13 +16,5 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -#![cfg(test)] -mod account_id; -mod dollor_tests; -mod general_key; -mod transact; -// mod salp; +mod send_relay_chain_asset; mod slp; -mod total_issuance; -mod vtoken_minting; -mod vtoken_voting; diff --git a/integration-tests/src/tests/send_relay_chain_asset.rs b/integration-tests/src/tests/send_relay_chain_asset.rs new file mode 100644 index 000000000..86e14aaf3 --- /dev/null +++ b/integration-tests/src/tests/send_relay_chain_asset.rs @@ -0,0 +1,63 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +use crate::mock::{ + Bifrost, BifrostTokens, BifrostXTokens, Relay, RelayBalances, RelaySystem, TestNet, ALICE, BOB, +}; +use bifrost_primitives::CurrencyId; +use cumulus_primitives_core::ParaId; +use frame_support::{assert_ok, traits::Currency}; +use orml_traits::MultiCurrency; +use sp_runtime::traits::AccountIdConversion; +use xcm::v4::{Junction, Location, WeightLimit}; +use xcm_simulator::TestExt; + +#[test] +fn send_relay_chain_asset_to_relay_chain() { + TestNet::reset(); + + Relay::execute_with(|| { + let _ = RelayBalances::deposit_creating( + &ParaId::from(2030).into_account_truncating(), + 100_000_000_000, + ); + }); + + Bifrost::execute_with(|| { + assert_ok!(BifrostXTokens::transfer( + Some(ALICE).into(), + CurrencyId::Token2(0), + 50_000_000_000, + Box::new( + Location::new(1, [Junction::AccountId32 { network: None, id: BOB.into() }]).into() + ), + WeightLimit::Unlimited + )); + assert_eq!(BifrostTokens::free_balance(CurrencyId::Token2(0), &ALICE), 50_000_000_000); + }); + + Relay::execute_with(|| { + println!("{:?}", RelaySystem::events()); + + assert_eq!( + RelayBalances::free_balance(&ParaId::from(2030).into_account_truncating()), + 50_000_000_000 + ); + assert_eq!(RelayBalances::free_balance(&BOB), 49999999960); + }); +} diff --git a/integration-tests/src/tests/slp.rs b/integration-tests/src/tests/slp.rs new file mode 100644 index 000000000..433a18dea --- /dev/null +++ b/integration-tests/src/tests/slp.rs @@ -0,0 +1,137 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +use crate::mock::{bifrost, Bifrost, BifrostSlp, Relay, RelayBalances, RelayXcmPallet}; +use bifrost_polkadot_runtime::xcm_config::ParaId; +use bifrost_primitives::CurrencyId; +use bifrost_slp::MinimumsMaximums; +use frame_support::{assert_ok, traits::Currency}; +use sp_runtime::{ + traits::{AccountIdConversion, Convert}, + AccountId32, +}; +use std::convert::Into; +use xcm::{v3::MultiLocation, v4::prelude::*, VersionedAssets, VersionedLocation}; +use xcm_simulator::TestExt; + +const ENTRANCE_ACCOUNT: [u8; 32] = + hex_literal::hex!["6d6f646c62662f76746b696e0000000000000000000000000000000000000000"]; +const BIFROST_TREASURY_ACCOUNT: [u8; 32] = + hex_literal::hex!["6d6f646c62662f74727372790000000000000000000000000000000000000000"]; +const BIFROST_TREASURY_MULTILOCATION: MultiLocation = MultiLocation { + parents: 0, + interior: xcm::v3::Junctions::X1(xcm::v3::Junction::AccountId32 { + network: None, + id: BIFROST_TREASURY_ACCOUNT, + }), +}; +pub const KUSAMA_ALICE_STASH_ACCOUNT: [u8; 32] = + hex_literal::hex!["be5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f"]; +const KUSAMA_ALICE_STASH_MULTILOCATION: MultiLocation = MultiLocation { + parents: 1, + interior: xcm::v3::Junctions::X1(xcm::v3::Junction::AccountId32 { + network: None, + id: KUSAMA_ALICE_STASH_ACCOUNT, + }), +}; + +const DOT_DECIMALS: u128 = 10_000_000_000; + +fn cross_dot_to_bifrost(to: AccountId32, amount: u128) { + Relay::execute_with(|| { + let _ = RelayBalances::deposit_creating( + &ParaId::from(2030).into_account_truncating(), + 100_000_000_000, + ); + let _ = RelayBalances::deposit_creating(&to, amount); + assert_ok!(RelayXcmPallet::reserve_transfer_assets( + Some(to.clone()).into(), + Box::new(VersionedLocation::V4(Parachain(2030).into())), + Box::new(VersionedLocation::V4( + Junction::AccountId32 { id: to.into(), network: None }.into() + )), + Box::new(VersionedAssets::V4((Here, amount / 10).into())), + 0, + )); + }); +} + +fn slp_setup() { + cross_dot_to_bifrost(BIFROST_TREASURY_ACCOUNT.into(), 10000 * DOT_DECIMALS); + cross_dot_to_bifrost(ENTRANCE_ACCOUNT.into(), 10000 * DOT_DECIMALS); + + let mins_and_maxs = MinimumsMaximums { + delegator_bonded_minimum: DOT_DECIMALS / 10, + bond_extra_minimum: DOT_DECIMALS / 1000, + unbond_minimum: DOT_DECIMALS / 1000, + rebond_minimum: DOT_DECIMALS / 1000, + unbond_record_maximum: 32, + validators_back_maximum: 24, + delegator_active_staking_maximum: 80000 * DOT_DECIMALS, + validators_reward_maximum: 256, + delegation_amount_minimum: DOT_DECIMALS / 1000, + delegators_maximum: 100, + validators_maximum: 300, + }; + + Bifrost::execute_with(|| { + assert_ok!(BifrostSlp::set_minimums_and_maximums( + bifrost::RuntimeOrigin::root(), + CurrencyId::Token2(0), + Some(mins_and_maxs) + )); + + // set fee_source for ksm to be treasury + assert_ok!(BifrostSlp::set_fee_source( + bifrost::RuntimeOrigin::root(), + CurrencyId::Token2(0), + Some((BIFROST_TREASURY_MULTILOCATION, 1 * DOT_DECIMALS)) + )); + + assert_ok!(BifrostSlp::initialize_delegator( + bifrost::RuntimeOrigin::root(), + CurrencyId::Token2(0), + None + )); + + assert_ok!(BifrostSlp::add_validator( + bifrost::RuntimeOrigin::root(), + CurrencyId::Token2(0), + Box::new(KUSAMA_ALICE_STASH_MULTILOCATION), + )); + }) +} + +#[test] +fn relaychain_staking_bond() { + slp_setup(); + Bifrost::execute_with(|| { + let delegator = bifrost_polkadot_runtime::SubAccountIndexMultiLocationConvertor::convert(( + 0, + CurrencyId::Token2(0), + )); + assert_ok!(BifrostSlp::bond( + bifrost::RuntimeOrigin::root(), + CurrencyId::Token2(0), + Box::new(delegator), + 50 * DOT_DECIMALS, + None, + Some((Weight::from_parts(10000000000u64, 65535u64), 100000000u128)) + )); + }); +} diff --git a/pallets/slp/src/agents/astar_agent/agent.rs b/pallets/slp/src/agents/astar_agent/agent.rs index ce09f0f54..8d54fb8aa 100644 --- a/pallets/slp/src/agents/astar_agent/agent.rs +++ b/pallets/slp/src/agents/astar_agent/agent.rs @@ -152,10 +152,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -254,10 +252,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -400,10 +396,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) diff --git a/pallets/slp/src/agents/common.rs b/pallets/slp/src/agents/common.rs index 9bab67f01..d8973c2ea 100644 --- a/pallets/slp/src/agents/common.rs +++ b/pallets/slp/src/agents/common.rs @@ -301,36 +301,42 @@ impl Pallet { pub(crate) fn inner_construct_xcm_message( currency_id: CurrencyId, extra_fee: BalanceOf, - ) -> Result>, Error> { - let multi = Self::get_currency_local_multilocation(currency_id); + ) -> Result>, Error> { + let remote_fee_location = Self::convert_currency_to_remote_fee_location(currency_id); - let asset = - MultiAsset { id: Concrete(multi), fun: Fungible(extra_fee.unique_saturated_into()) }; + let asset = xcm::v4::Asset { + id: xcm::v4::AssetId(remote_fee_location), + fun: xcm::v4::prelude::Fungible(extra_fee.unique_saturated_into()), + }; - let interior = Self::get_interior_by_currency_id(currency_id); + let refund_receiver = Self::convert_currency_to_refund_receiver(currency_id); Ok(vec![ - WithdrawAsset(asset.clone().into()), - BuyExecution { fees: asset, weight_limit: Unlimited }, - RefundSurplus, - DepositAsset { - assets: AllCounted(8).into(), - beneficiary: Location { parents: 0, interior }, + xcm::v4::prelude::WithdrawAsset(asset.clone().into()), + xcm::v4::prelude::BuyExecution { fees: asset, weight_limit: Unlimited }, + xcm::v4::prelude::RefundSurplus, + xcm::v4::prelude::DepositAsset { + assets: xcm::v4::prelude::AllCounted(8).into(), + beneficiary: xcm::v4::prelude::Location { parents: 0, interior: refund_receiver }, }, ]) } - pub(crate) fn get_interior_by_currency_id(currency_id: CurrencyId) -> Junctions { + pub(crate) fn convert_currency_to_refund_receiver( + currency_id: CurrencyId, + ) -> xcm::v4::Junctions { let interior = match currency_id { - KSM | DOT => X1(Parachain(T::ParachainId::get().into())), - MOVR | GLMR => X1(AccountKey20 { + KSM | DOT => xcm::v4::Junctions::from([xcm::v4::prelude::Parachain( + T::ParachainId::get().into(), + )]), + MOVR | GLMR => xcm::v4::Junctions::from([xcm::v4::prelude::AccountKey20 { network: None, key: Sibling::from(T::ParachainId::get()).into_account_truncating(), - }), - _ => X1(AccountId32 { + }]), + _ => xcm::v4::Junctions::from([xcm::v4::prelude::AccountId32 { network: None, id: Sibling::from(T::ParachainId::get()).into_account_truncating(), - }), + }]), }; return interior; @@ -372,7 +378,7 @@ impl Pallet { who: &MultiLocation, currency_id: CurrencyId, weight_and_fee: Option<(Weight, BalanceOf)>, - ) -> Result<(QueryId, BlockNumberFor, BalanceOf, Xcm<()>), Error> { + ) -> Result<(QueryId, BlockNumberFor, BalanceOf, xcm::v4::Xcm<()>), Error> { // prepare the query_id for reporting back transact status let now = frame_system::Pallet::::block_number(); let timeout = BlockNumberFor::::from(TIMEOUT_BLOCKS).saturating_add(now); @@ -405,10 +411,7 @@ impl Pallet { ) -> Result<(QueryId, Weight), Error> { let now = frame_system::Pallet::::block_number(); let timeout = BlockNumberFor::::from(TIMEOUT_BLOCKS).saturating_add(now); - let responder: xcm::v4::Location = - Self::get_para_multilocation_by_currency_id(currency_id)? - .try_into() - .map_err(|_| Error::::FailToConvert)?; + let responder = Self::convert_currency_to_dest_location(currency_id)?; let (notify_call_weight, callback_option) = match (currency_id, operation) { (DOT, &XcmOperationType::Delegate) | @@ -454,10 +457,8 @@ impl Pallet { None, )?; - let dest = Self::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Self::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(withdraw_fee) @@ -467,13 +468,23 @@ impl Pallet { query_id: QueryId, max_weight: Weight, currency_id: CurrencyId, - ) -> Instruction<()> { + ) -> xcm::v4::Instruction<()> { let dest_location = match currency_id { - DOT | KSM => MultiLocation::from(X1(Parachain(u32::from(T::ParachainId::get())))), - _ => MultiLocation::new(1, X1(Parachain(u32::from(T::ParachainId::get())))), + DOT | KSM => xcm::v4::Location::new( + 0, + [xcm::v4::prelude::Parachain(u32::from(T::ParachainId::get()))], + ), + _ => xcm::v4::Location::new( + 1, + [xcm::v4::prelude::Parachain(u32::from(T::ParachainId::get()))], + ), }; - ReportTransactStatus(QueryResponseInfo { destination: dest_location, query_id, max_weight }) + xcm::v4::prelude::ReportTransactStatus(xcm::v4::prelude::QueryResponseInfo { + destination: dest_location, + query_id, + max_weight, + }) } pub(crate) fn insert_delegator_ledger_update_entry( @@ -565,9 +576,9 @@ impl Pallet { currency_id: CurrencyId, query_id: Option, notify_call_weight: Option, - ) -> Result, Error> { + ) -> Result, Error> { let mut xcm_message = Self::inner_construct_xcm_message(currency_id, extra_fee)?; - let transact = Transact { + let transact = xcm::v4::prelude::Transact { origin_kind: OriginKind::SovereignAccount, require_weight_at_most: transact_weight, call: call.into(), @@ -584,7 +595,7 @@ impl Pallet { }, _ => {}, }; - Ok(Xcm(xcm_message)) + Ok(xcm::v4::Xcm(xcm_message)) } pub(crate) fn get_unlocking_time_unit_from_current( diff --git a/pallets/slp/src/agents/parachain_staking_agent/agent.rs b/pallets/slp/src/agents/parachain_staking_agent/agent.rs index 975fd7bb0..397270029 100644 --- a/pallets/slp/src/agents/parachain_staking_agent/agent.rs +++ b/pallets/slp/src/agents/parachain_staking_agent/agent.rs @@ -307,10 +307,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; query_index = query_id; @@ -458,10 +456,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; query_index = query_id; } @@ -625,10 +621,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; query_index = query_id; } @@ -844,10 +838,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; query_index = query_id; } @@ -995,10 +987,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; query_index = query_id; @@ -1343,10 +1333,8 @@ impl } // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; query_index = query_id; diff --git a/pallets/slp/src/agents/phala_agent/agent.rs b/pallets/slp/src/agents/phala_agent/agent.rs index ccb742436..f6494fa41 100644 --- a/pallets/slp/src/agents/phala_agent/agent.rs +++ b/pallets/slp/src/agents/phala_agent/agent.rs @@ -170,10 +170,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -283,10 +281,8 @@ impl )?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -514,10 +510,8 @@ impl Pallet::::burn_fee_from_source_account(fee, currency_id)?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -597,10 +591,14 @@ impl T::ParachainId::get().into(), )?; - let locat = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + let dest_location = + xcm::v3::Location::try_from(dest_location).map_err(|_| Error::::FailToConvert)?; // Prepare parameter assets. - let asset = - MultiAsset { fun: Fungible(amount.unique_saturated_into()), id: Concrete(locat) }; + let asset = MultiAsset { + fun: Fungible(amount.unique_saturated_into()), + id: Concrete(dest_location), + }; // Construct xcm message. let call: PhalaCall = @@ -699,10 +697,8 @@ impl Pallet::::burn_fee_from_source_account(fee, currency_id)?; // Send out the xcm message. - let dest = Pallet::::get_para_multilocation_by_currency_id(currency_id)?; - let v4_dest = dest.try_into().map_err(|()| Error::::FailToConvert)?; - let v4_message = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(v4_dest, v4_message) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) diff --git a/pallets/slp/src/agents/polkadot_agent/agent.rs b/pallets/slp/src/agents/polkadot_agent/agent.rs index 22f3ece81..8c972d3a9 100644 --- a/pallets/slp/src/agents/polkadot_agent/agent.rs +++ b/pallets/slp/src/agents/polkadot_agent/agent.rs @@ -154,8 +154,8 @@ impl )?; // Send out the xcm message. - let v4_location = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(xcm::v4::Parent.into(), v4_location) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -224,8 +224,8 @@ impl )?; // Send out the xcm message. - let v4_location = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(xcm::v4::Parent.into(), v4_location) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -302,8 +302,8 @@ impl )?; // Send out the xcm message. - let v4_location = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(xcm::v4::Parent.into(), v4_location) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -356,8 +356,8 @@ impl )?; // Send out the xcm message. - let v4_location = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(xcm::v4::Parent.into(), v4_location) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -432,8 +432,8 @@ impl )?; // Send out the xcm message. - let v4_location = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(xcm::v4::Parent.into(), v4_location) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -504,8 +504,8 @@ impl )?; // Send out the xcm message. - let v4_location = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(xcm::v4::Parent.into(), v4_location) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -583,8 +583,8 @@ impl )?; // Send out the xcm message. - let v4_location = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(xcm::v4::Parent.into(), v4_location) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -712,8 +712,8 @@ impl )?; // Send out the xcm message. - let v4_location = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(xcm::v4::Parent.into(), v4_location) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) @@ -777,8 +777,8 @@ impl } // Send out the xcm message. - let v4_location = xcm_message.try_into().map_err(|()| Error::::FailToConvert)?; - xcm::v4::send_xcm::(xcm::v4::Parent.into(), v4_location) + let dest_location = Pallet::::convert_currency_to_dest_location(currency_id)?; + xcm::v4::send_xcm::(dest_location, xcm_message) .map_err(|_e| Error::::XcmFailure)?; Ok(query_id) diff --git a/pallets/slp/src/agents/utils.rs b/pallets/slp/src/agents/utils.rs index 4b6099a27..228d362f4 100644 --- a/pallets/slp/src/agents/utils.rs +++ b/pallets/slp/src/agents/utils.rs @@ -315,20 +315,25 @@ impl Pallet { H160::from_slice(sub_id.as_slice()) } - pub fn get_para_multilocation_by_currency_id( + pub fn convert_currency_to_dest_location( currency_id: CurrencyId, - ) -> Result> { + ) -> Result> { match currency_id { - KSM | DOT => Ok(MultiLocation::parent()), - MOVR => - Ok(MultiLocation { parents: 1, interior: X1(Parachain(parachains::moonriver::ID)) }), - GLMR => - Ok(MultiLocation { parents: 1, interior: X1(Parachain(parachains::moonbeam::ID)) }), + KSM | DOT => Ok(xcm::v4::Location::parent()), + MOVR => Ok(xcm::v4::Location::new( + 1, + [xcm::v4::prelude::Parachain(parachains::moonriver::ID)], + )), + GLMR => Ok(xcm::v4::Location::new( + 1, + [xcm::v4::prelude::Parachain(parachains::moonbeam::ID)], + )), ASTR => - Ok(MultiLocation { parents: 1, interior: X1(Parachain(parachains::astar::ID)) }), + Ok(xcm::v4::Location::new(1, [xcm::v4::prelude::Parachain(parachains::astar::ID)])), MANTA => - Ok(MultiLocation { parents: 1, interior: X1(Parachain(parachains::manta::ID)) }), - PHA => Ok(MultiLocation { parents: 1, interior: X1(Parachain(parachains::phala::ID)) }), + Ok(xcm::v4::Location::new(1, [xcm::v4::prelude::Parachain(parachains::manta::ID)])), + PHA => + Ok(xcm::v4::Location::new(1, [xcm::v4::prelude::Parachain(parachains::phala::ID)])), _ => Err(Error::::NotSupportedCurrencyId), } } @@ -357,18 +362,17 @@ impl Pallet { } } - pub fn get_currency_local_multilocation(currency_id: CurrencyId) -> MultiLocation { + pub fn convert_currency_to_remote_fee_location(currency_id: CurrencyId) -> xcm::v4::Location { match currency_id { - KSM | DOT | PHA | MANTA | ASTR => MultiLocation::here(), - MOVR => MultiLocation { - parents: 0, - interior: X1(PalletInstance(parachains::moonriver::PALLET_ID)), - }, - GLMR => MultiLocation { - parents: 0, - interior: X1(PalletInstance(parachains::moonbeam::PALLET_ID)), - }, - _ => MultiLocation::here(), + MOVR => xcm::v4::Location::new( + 0, + [xcm::v4::prelude::PalletInstance(parachains::moonriver::PALLET_ID)], + ), + GLMR => xcm::v4::Location::new( + 0, + [xcm::v4::prelude::PalletInstance(parachains::moonbeam::PALLET_ID)], + ), + _ => xcm::v4::Location::here(), } } } diff --git a/pallets/slp/src/tests/kusama_tests.rs b/pallets/slp/src/tests/kusama_tests.rs index 037f18778..9845dd874 100644 --- a/pallets/slp/src/tests/kusama_tests.rs +++ b/pallets/slp/src/tests/kusama_tests.rs @@ -26,7 +26,7 @@ use bifrost_primitives::{ use frame_support::{assert_noop, assert_ok, PalletId}; use orml_traits::MultiCurrency; use sp_runtime::{traits::AccountIdConversion, MultiAddress}; -use xcm::v3::{prelude::*, MultiAsset}; +use xcm::v3::prelude::*; const SUBACCOUNT_0_32: [u8; 32] = hex_literal::hex!["5a53736d8e96f1c007cf0d630acf5209b20611617af23ce924c8e25328eb5d28"]; @@ -682,8 +682,8 @@ fn test_construct_xcm() { register_subaccount_index_0(); // construct_xcm_as_subaccount_with_query_id - let weight = Weight::from_parts(20000000000, 20000000000); - let (_, _, _, messsage) = + let _weight = Weight::from_parts(20000000000, 20000000000); + let (_, _, _, _messsage) = crate::Pallet::::construct_xcm_as_subaccount_with_query_id( XcmOperationType::Bond, sp_std::vec![], @@ -693,27 +693,8 @@ fn test_construct_xcm() { ) .unwrap(); - assert_eq!( - messsage.0[1], - xcm::v3::prelude::BuyExecution { - fees: MultiAsset { - id: Concrete(MultiLocation { parents: 0, interior: xcm::v3::prelude::Here }), - fun: xcm::v3::prelude::Fungible(10000000000) - }, - weight_limit: Unlimited - } - ); - assert_eq!( - messsage.0[2], - xcm::v3::prelude::Transact { - origin_kind: OriginKind::SovereignAccount, - require_weight_at_most: weight, - call: [26, 1, 0, 0].to_vec().into() - } - ); - let weight = Weight::from_parts(100, 100); - let (_, _, _, messsage) = + let (_, _, _, _messsage) = crate::Pallet::::construct_xcm_as_subaccount_with_query_id( XcmOperationType::Bond, sp_std::vec![], @@ -722,24 +703,6 @@ fn test_construct_xcm() { Some((weight, 100u32.into())), ) .unwrap(); - assert_eq!( - messsage.0[1], - xcm::v3::prelude::BuyExecution { - fees: MultiAsset { - id: Concrete(MultiLocation { parents: 0, interior: xcm::v3::prelude::Here }), - fun: xcm::v3::prelude::Fungible(100) - }, - weight_limit: Unlimited - } - ); - assert_eq!( - messsage.0[2], - xcm::v3::prelude::Transact { - origin_kind: OriginKind::SovereignAccount, - require_weight_at_most: weight, - call: [26, 1, 0, 0].to_vec().into() - } - ); // construct_xcm_and_send_as_subaccount_without_query_id let fee = crate::Pallet::::construct_xcm_and_send_as_subaccount_without_query_id( diff --git a/runtime/bifrost-polkadot/src/lib.rs b/runtime/bifrost-polkadot/src/lib.rs index 00484b449..a01c62ff7 100644 --- a/runtime/bifrost-polkadot/src/lib.rs +++ b/runtime/bifrost-polkadot/src/lib.rs @@ -114,7 +114,7 @@ use polkadot_runtime_common::prod_or_fast; use sp_runtime::traits::{IdentityLookup, Verify}; use static_assertions::const_assert; use xcm::{v3::MultiLocation, v4::prelude::*}; -use xcm_config::{ +pub use xcm_config::{ parachains, BifrostCurrencyIdConvert, BifrostTreasuryAccount, MultiCurrency, SelfParaChainId, }; use xcm_executor::{