From 93e1b44387689e936ecbf282c0c885ef42b34e6e Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Thu, 14 Mar 2024 15:37:13 +0100 Subject: [PATCH] Revert "393 use fee per second from asset metadata in xcm config" (#431) Revert "393 use fee per second from asset metadata in xcm config (#410)" This reverts commit a402b6204cbcb8cac5bb4d2801628f8a91bae683. --- Cargo.lock | 3 - node/src/chain_spec.rs | 3 +- node/src/constants/foucoco.rs | 1 - package-lock.json | 6 - runtime/amplitude/src/xcm_config.rs | 83 ++++++-- runtime/common/src/asset_registry.rs | 25 +-- .../src/benchmarking/orml_asset_registry.rs | 2 - runtime/common/src/lib.rs | 28 ++- runtime/foucoco/src/xcm_config.rs | 43 ++-- runtime/integration-tests/Cargo.toml | 1 - .../integration-tests/src/amplitude_tests.rs | 7 +- runtime/integration-tests/src/mock.rs | 196 +----------------- .../integration-tests/src/pendulum_tests.rs | 9 +- runtime/integration-tests/src/test_macros.rs | 5 +- runtime/pendulum/src/xcm_config.rs | 93 +++++++-- 15 files changed, 205 insertions(+), 300 deletions(-) delete mode 100644 package-lock.json diff --git a/Cargo.lock b/Cargo.lock index fd7aa35e6..34141777b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -191,7 +191,6 @@ version = "0.1.0" dependencies = [ "bifrost-farming", "bifrost-farming-rpc-runtime-api", - "cfg-if", "clients-info", "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", @@ -285,7 +284,6 @@ dependencies = [ "staking", "stellar-relay", "substrate-wasm-builder", - "treasury-buyout-extension", "vault-registry", "vesting-manager", "xcm", @@ -10122,7 +10120,6 @@ dependencies = [ "frame-support", "frame-system", "kusama-runtime", - "orml-asset-registry", "orml-tokens", "orml-traits", "orml-xcm", diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index 0f4dcc292..3761542df 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -537,9 +537,8 @@ fn foucoco_genesis( let token_balances = balances .iter() - .flat_map(|k| vec![(k.0.clone(), XCM(0), 10*u128::pow(10, 18)), (k.0.clone(), XCM(6), 10*u128::pow(10, 18)), (k.0.clone(), CurrencyId::StellarNative, 10*u128::pow(10, 18))]) + .flat_map(|k| vec![(k.0.clone(), XCM(0), u128::pow(10, 18))]) .collect(); - let stakers: Vec<_> = invulnerables .iter() diff --git a/node/src/constants/foucoco.rs b/node/src/constants/foucoco.rs index 7ff9041fc..e349b20ac 100644 --- a/node/src/constants/foucoco.rs +++ b/node/src/constants/foucoco.rs @@ -10,7 +10,6 @@ pub const COLLATOR_ADDITIONAL: Balance = 10 * UNIT; pub const OFF_CHAIN_WORKER_ADDRESS: &str = "6m69vWMouLarYCbJGJisVaDDpfNGETkD5hsDWf2T7osW4Cn1"; - pub const TOKEN_DECIMALS: u32 = 12; pub const INITIAL_SUDO_SIGNATORIES: [&str; 5] = [ diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 7cb28afda..000000000 --- a/package-lock.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "pendulum", - "lockfileVersion": 3, - "requires": true, - "packages": {} -} diff --git a/runtime/amplitude/src/xcm_config.rs b/runtime/amplitude/src/xcm_config.rs index bc82e8dbc..98fcad2ce 100644 --- a/runtime/amplitude/src/xcm_config.rs +++ b/runtime/amplitude/src/xcm_config.rs @@ -3,8 +3,8 @@ use core::marker::PhantomData; use frame_support::{ log, match_types, parameter_types, traits::{ContainsPair, Everything, Nothing}, + weights::{Weight, WeightToFee as WeightToFeeTrait}, }; -use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{ location::{RelativeReserveProvider, Reserve}, parameter_type_with_key, @@ -16,15 +16,21 @@ use sp_runtime::traits::Convert; use xcm::latest::{prelude::*, Weight as XCMWeight}; use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, EnsureXcmOrigin, FixedWeightBounds, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, + FixedWeightBounds, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, +}; +use xcm_executor::{ + traits::{JustTry, ShouldExecute}, + XcmExecutor, }; -use xcm_executor::{traits::ShouldExecute, XcmExecutor}; -use runtime_common::{parachains::kusama::asset_hub, asset_registry::FixedConversionRateProvider}; +use runtime_common::{parachains::kusama::asset_hub, RelativeValue}; -use cumulus_primitives_utility::XcmFeesTo32ByteAccount; +use cumulus_primitives_utility::{ + ChargeWeightInFungibles, TakeFirstAssetTrader, XcmFeesTo32ByteAccount, +}; use crate::{ assets::{ @@ -35,9 +41,9 @@ use crate::{ }; use super::{ - AccountId, AmplitudeTreasuryAccount, AssetRegistry, Balance, Balances, Currencies, CurrencyId, - ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - XcmpQueue, + AccountId, AmplitudeTreasuryAccount, Balance, Balances, Currencies, CurrencyId, ParachainInfo, + ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, + WeightToFee, XcmpQueue, }; parameter_types! { @@ -107,6 +113,23 @@ impl Convert> for CurrencyIdConvert { } } +type RelativeValueOf = RelativeValue; + +pub struct RelayRelativeValue; +impl RelayRelativeValue { + fn get_relative_value(id: CurrencyId) -> Option { + match id { + CurrencyId::XCM(index) => match index { + xcm_assets::RELAY_KSM => Some(RelativeValueOf { num: 100, denominator: 1 }), + xcm_assets::ASSETHUB_USDT => Some(RelativeValueOf { num: 20, denominator: 4 }), + _ => None, + }, + CurrencyId::Native => Some(RelativeValueOf { num: 1, denominator: 1 }), + _ => Some(RelativeValueOf { num: 1, denominator: 1 }), + } + } +} + /// Convert an incoming `MultiLocation` into a `CurrencyId` if possible. /// Here we need to know the canonical representation of all the tokens we handle in order to /// correctly convert their `MultiLocation` representation into our internal `CurrencyId` type. @@ -177,6 +200,13 @@ parameter_types! { pub const MaxAssetsForTransfer: usize = 2; } +match_types! { + pub type ParentOrParentsExecutivePlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } + }; +} + //TODO: move DenyThenTry to polkadot's xcm module. /// Deny executing the xcm message if it matches any of the Deny filter regardless of anything else. /// If it passes the Deny, and matches one of the Allow cases then it is let through. @@ -258,10 +288,35 @@ pub type Barrier = ( AllowSubscriptionsFrom, ); -pub type Traders = AssetRegistryTrader< - FixedRateAssetRegistryTrader>, - XcmFeesTo32ByteAccount, ->; +pub struct ChargeWeightInFungiblesImplementation; +impl ChargeWeightInFungibles for ChargeWeightInFungiblesImplementation { + fn charge_weight_in_fungibles( + asset_id: CurrencyId, + weight: Weight, + ) -> Result { + let amount = ::weight_to_fee(&weight); + + if let Some(relative_value) = RelayRelativeValue::get_relative_value(asset_id) { + let adjusted_amount = + RelativeValue::::divide_by_relative_value(amount, relative_value); + log::info!("amount to be charged: {:?} in asset: {:?}", adjusted_amount, asset_id); + return Ok(adjusted_amount) + } else { + log::info!("amount to be charged: {:?} in asset: {:?}", amount, asset_id); + return Ok(amount) + } + } +} + +pub type Traders = ( + TakeFirstAssetTrader< + AccountId, + ChargeWeightInFungiblesImplementation, + ConvertedConcreteId, + Tokens, + XcmFeesTo32ByteAccount, + >, +); pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { diff --git a/runtime/common/src/asset_registry.rs b/runtime/common/src/asset_registry.rs index 14e35cc05..4ffd1dd94 100644 --- a/runtime/common/src/asset_registry.rs +++ b/runtime/common/src/asset_registry.rs @@ -1,18 +1,16 @@ use crate::*; use frame_support::traits::AsEnsureOriginWithArg; use frame_system::EnsureRoot; -use orml_traits::{FixedConversionRateProvider as FixedConversionRateProviderTrait, - asset_registry::{AssetMetadata, AssetProcessor, Inspect}}; +use orml_traits::asset_registry::{AssetMetadata, AssetProcessor}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_core::Get; -use sp_runtime::{BoundedVec, DispatchError, traits::PhantomData}; +use sp_runtime::{BoundedVec, DispatchError}; use sp_std::fmt::Debug; use spacewalk_primitives::CurrencyId; -use xcm::opaque::v3::MultiLocation; #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct StringLimit; +pub struct StringLimit; impl Get for StringLimit { fn get() -> u32 { 50 @@ -56,20 +54,3 @@ impl AssetProcessor> for Cust } pub type AssetAuthority = AsEnsureOriginWithArg>; - - -pub struct FixedConversionRateProvider(PhantomData); - -impl< - OrmlAssetRegistry: Inspect< - AssetId = CurrencyId, - Balance = Balance, - CustomMetadata = asset_registry::CustomMetadata, - >, - > FixedConversionRateProviderTrait for FixedConversionRateProvider -{ - fn get_fee_per_second(location: &MultiLocation) -> Option { - let metadata = OrmlAssetRegistry::metadata_by_location(location)?; - Some(metadata.additional.fee_per_second) - } -} \ No newline at end of file diff --git a/runtime/common/src/benchmarking/orml_asset_registry.rs b/runtime/common/src/benchmarking/orml_asset_registry.rs index a6ee85563..2f18594a4 100644 --- a/runtime/common/src/benchmarking/orml_asset_registry.rs +++ b/runtime/common/src/benchmarking/orml_asset_registry.rs @@ -1,9 +1,7 @@ -use crate::asset_registry::{CustomMetadata, DiaKeys}; use frame_benchmarking::v2::benchmarks; use frame_support::assert_ok; use frame_system::RawOrigin; use orml_asset_registry::AssetMetadata; -use sp_runtime::BoundedVec; use sp_std::{vec, vec::Vec}; use crate::asset_registry::{CustomMetadata, DiaKeys}; use spacewalk_primitives::CurrencyId; diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 627003f96..0de451eab 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -2,7 +2,7 @@ #![allow(non_snake_case)] use sp_runtime::{ - traits::{IdentifyAccount, Verify}, + traits::{CheckedDiv, IdentifyAccount, Saturating, Verify}, DispatchError, MultiSignature, }; @@ -70,6 +70,29 @@ pub mod opaque { pub type BlockId = generic::BlockId; } +pub struct RelativeValue { + pub num: Amount, + pub denominator: Amount, +} + +impl + Saturating + Clone> RelativeValue { + pub fn divide_by_relative_value( + amount: Amount, + relative_value: RelativeValue, + ) -> Amount { + // Calculate the adjusted amount + if let Some(adjusted_amount) = amount + .clone() + .saturating_mul(relative_value.denominator) + .checked_div(&relative_value.num) + { + return adjusted_amount + } + // We should never specify a numerator of 0, but just to be safe + return amount + } +} + #[macro_use] pub mod parachains { @@ -167,8 +190,7 @@ pub mod parachains { // The address of the BRZ token on Moonbeam `0x3225edCe8aD30Ae282e62fa32e7418E4b9cf197b` as byte array pub const BRZ_ASSET_ACCOUNT_IN_BYTES: [u8; 20] = [ - 50, 37, 237, 206, 138, 211, 10, 226, 130, 230, 47, 163, 46, 116, 24, 228, 185, 207, - 25, 123, + 50, 37, 237, 206, 138, 211, 10, 226, 130, 230, 47, 163, 46, 116, 24, 228, 185, 207, 25, 123 ]; parachain_asset_location!( diff --git a/runtime/foucoco/src/xcm_config.rs b/runtime/foucoco/src/xcm_config.rs index 39c0dbcbb..2bce518ef 100644 --- a/runtime/foucoco/src/xcm_config.rs +++ b/runtime/foucoco/src/xcm_config.rs @@ -4,7 +4,6 @@ use frame_support::{ log, match_types, parameter_types, traits::{ConstU32, ContainsPair, Everything, Nothing}, }; -use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{ location::{RelativeReserveProvider, Reserve}, parameter_type_with_key, @@ -16,14 +15,13 @@ use polkadot_runtime_common::impls::ToAuthor; use sp_runtime::traits::Convert; use xcm::latest::{prelude::*, Weight as XCMWeight}; use xcm_builder::{ - AccountId32Aliases, AllowUnpaidExecutionFrom, AllowSubscriptionsFrom,AllowTopLevelPaidExecutionFrom, AllowKnownQueryResponses, EnsureXcmOrigin, FixedWeightBounds, + AccountId32Aliases, AllowUnpaidExecutionFrom, EnsureXcmOrigin, FixedWeightBounds, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, UsingComponents, }; use xcm_executor::{traits::ShouldExecute, XcmExecutor}; -use cumulus_primitives_utility::XcmFeesTo32ByteAccount; -use runtime_common::{parachains::moonbase_alpha_relay::moonbase_alpha, asset_registry::FixedConversionRateProvider}; +use runtime_common::parachains::moonbase_alpha_relay::moonbase_alpha; use crate::assets::{ native_locations::{native_location_external_pov, native_location_local_pov}, @@ -31,7 +29,7 @@ use crate::assets::{ }; use super::{ - AccountId, AssetRegistry, Balance, Balances, Currencies, CurrencyId, FoucocoTreasuryAccount, ParachainInfo, + AccountId, Balance, Balances, Currencies, CurrencyId, FoucocoTreasuryAccount, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue, }; @@ -172,6 +170,13 @@ parameter_types! { pub const MaxAssetsForTransfer: usize = 2; } +match_types! { + pub type ParentOrParentsExecutivePlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } + }; +} + //TODO: move DenyThenTry to polkadot's xcm module. /// Deny executing the xcm message if it matches any of the Deny filter regardless of anything else. /// If it passes the Deny, and matches one of the Allow cases then it is let through. @@ -235,28 +240,7 @@ impl ShouldExecute for DenyReserveTransferToRelayChain { } } -match_types! { - pub type ParentOrParentsPlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { .. }) } - }; -} - -pub type Barrier = ( - TakeWeightCredit, - AllowTopLevelPaidExecutionFrom, - // Parent and its plurality get free execution - AllowUnpaidExecutionFrom, - // Expected responses are OK. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, -); - -pub type Traders = AssetRegistryTrader< - FixedRateAssetRegistryTrader>, - XcmFeesTo32ByteAccount, ->; +pub type Barrier = AllowUnpaidExecutionFrom; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { @@ -271,7 +255,8 @@ impl xcm_executor::Config for XcmConfig { type UniversalLocation = UniversalLocation; type Barrier = Barrier; type Weigher = FixedWeightBounds; - type Trader = Traders; + type Trader = + UsingComponents>; type ResponseHandler = PolkadotXcm; type AssetTrap = PolkadotXcm; type AssetLocker = (); diff --git a/runtime/integration-tests/Cargo.toml b/runtime/integration-tests/Cargo.toml index 4c39f0d3d..d82c07f94 100644 --- a/runtime/integration-tests/Cargo.toml +++ b/runtime/integration-tests/Cargo.toml @@ -48,7 +48,6 @@ parachain-info = { git = "https://github.com/paritytech/cumulus", branch = "polk statemint-runtime = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.40" } statemine-runtime = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.40" } -orml-asset-registry = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", branch = "polkadot-v0.9.40" } orml-xcm = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", branch = "polkadot-v0.9.40" } orml-xcm-support = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", branch = "polkadot-v0.9.40" } orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library.git", branch = "polkadot-v0.9.40" } diff --git a/runtime/integration-tests/src/amplitude_tests.rs b/runtime/integration-tests/src/amplitude_tests.rs index 67c2341c8..972eeb290 100644 --- a/runtime/integration-tests/src/amplitude_tests.rs +++ b/runtime/integration-tests/src/amplitude_tests.rs @@ -16,10 +16,9 @@ use statemine_runtime as kusama_asset_hub_runtime; use xcm::latest::NetworkId; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, TestExt}; -// Native fee expected for each token according to the `fee_per_second` values defined in the mock -const NATIVE_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 4000000000; -const KSM_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = NATIVE_FEE_WHEN_TRANSFER_TO_PARACHAIN / 20; -const USDT_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = NATIVE_FEE_WHEN_TRANSFER_TO_PARACHAIN / 10; +const KSM_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 32000000; +const USDT_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 640000000; +const NATIVE_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 3200000000; decl_test_relay_chain! { pub struct KusamaRelay { diff --git a/runtime/integration-tests/src/mock.rs b/runtime/integration-tests/src/mock.rs index 445d93f6a..eb6a36b6b 100644 --- a/runtime/integration-tests/src/mock.rs +++ b/runtime/integration-tests/src/mock.rs @@ -1,5 +1,4 @@ use crate::{sibling, AMPLITUDE_ID, ASSETHUB_ID, PENDULUM_ID, SIBLING_ID}; -use amplitude_runtime::CurrencyId as AmplitudeCurrencyId; use frame_support::traits::GenesisBuild; use pendulum_runtime::CurrencyId as PendulumCurrencyId; use polkadot_core_primitives::{AccountId, Balance, BlockNumber}; @@ -11,18 +10,7 @@ use sp_io::TestExternalities; use sp_runtime::traits::AccountIdConversion; use xcm_emulator::Weight; -use codec::Encode; -use frame_support::BoundedVec; -use runtime_common::asset_registry::{CustomMetadata, DiaKeys, StringLimit}; - -use xcm::{ - v3::{Junction::PalletInstance, Junctions::X1, MultiLocation}, - VersionedMultiLocation, -}; - -use runtime_common::parachains::polkadot::{ - asset_hub, moonbeam, moonbeam::PARA_ID as MOONBEAM_PARA_ID, -}; +use runtime_common::parachains::polkadot::moonbeam::PARA_ID as MOONBEAM_PARA_ID; use statemine_runtime as kusama_asset_hub_runtime; use statemint_runtime as polkadot_asset_hub_runtime; @@ -96,36 +84,6 @@ macro_rules! build_parachain_with_orml { }}; } -macro_rules! build_parachain_with_orml_and_asset_registry { - ($self:ident, $runtime:ty, $system:tt, $balance:tt, $orml_balance:tt, $currency_id_type:ty, $registry_assets:tt) => {{ - let mut t = frame_system::GenesisConfig::default().build_storage::<$runtime>().unwrap(); - pallet_balances::GenesisConfig::<$runtime> { - balances: vec![(AccountId::from(ALICE), $balance), (AccountId::from(BOB), $balance)], - } - .assimilate_storage(&mut t) - .unwrap(); - - type CurrencyId = $currency_id_type; - orml_tokens::GenesisConfig::<$runtime> { - balances: vec![ - (AccountId::from(BOB), CurrencyId::XCM(0), units($orml_balance)), - (AccountId::from(ALICE), CurrencyId::XCM(0), units($orml_balance)), - ], - } - .assimilate_storage(&mut t) - .unwrap(); - - orml_asset_registry::GenesisConfig::<$runtime> { - assets: $registry_assets, - last_asset_id: CurrencyId::Native, - } - .assimilate_storage(&mut t) - .unwrap(); - - build_parachain!($self, $runtime, $system, t) - }}; -} - macro_rules! build_parachain { ($self:ident, $runtime:ty, $system:tt) => {{ let mut t = frame_system::GenesisConfig::default().build_storage::<$runtime>().unwrap(); @@ -222,147 +180,7 @@ fn default_parachains_host_configuration() -> HostConfiguration { ..Default::default() } } -fn assets_metadata_for_registry_pendulum() -> Vec<(PendulumCurrencyId, Vec)> { - vec![ - ( - PendulumCurrencyId::Native, - orml_asset_registry::AssetMetadata { - decimals: 12u32, - name: "Pendulum".as_bytes().to_vec(), - symbol: "PEN".as_bytes().to_vec(), - existential_deposit: 1_000u128, - location: Some(VersionedMultiLocation::V3(MultiLocation::new( - 0, - X1(PalletInstance(10)), - ))), - additional: CustomMetadata { - dia_keys: DiaKeys:: { - blockchain: BoundedVec::truncate_from(vec![1, 2, 3]), - symbol: BoundedVec::truncate_from(vec![1, 2, 3]), - }, - fee_per_second: UNIT, - }, - } - .encode(), - ), - ( - PendulumCurrencyId::XCM(1), - orml_asset_registry::AssetMetadata { - decimals: 12u32, - name: "USDT Assethub".as_bytes().to_vec(), - symbol: "USDT".as_bytes().to_vec(), - existential_deposit: 1_000u128, - location: Some(VersionedMultiLocation::V3(asset_hub::USDT_location())), - additional: CustomMetadata { - dia_keys: DiaKeys:: { - blockchain: BoundedVec::truncate_from(vec![1, 2, 3]), - symbol: BoundedVec::truncate_from(vec![1, 2, 3]), - }, - fee_per_second: UNIT/2, - }, - } - .encode(), - ), - ( - PendulumCurrencyId::XCM(0), - orml_asset_registry::AssetMetadata { - decimals: 12u32, - name: "Polkadot".as_bytes().to_vec(), - symbol: "DOT".as_bytes().to_vec(), - existential_deposit: 1_000u128, - location: Some(VersionedMultiLocation::V3(MultiLocation::parent())), - additional: CustomMetadata { - dia_keys: DiaKeys:: { - blockchain: BoundedVec::truncate_from(vec![1, 2, 3]), - symbol: BoundedVec::truncate_from(vec![1, 2, 3]), - }, - fee_per_second: UNIT/4, - }, - } - .encode(), - ), - ( - PendulumCurrencyId::XCM(6), - orml_asset_registry::AssetMetadata { - decimals: 12u32, - name: "Moonbeam BRZ".as_bytes().to_vec(), - symbol: "BRZ".as_bytes().to_vec(), - existential_deposit: 1_000u128, - location: Some(xcm::VersionedMultiLocation::V3(moonbeam::BRZ_location())), - additional: CustomMetadata { - dia_keys: DiaKeys:: { - blockchain: BoundedVec::truncate_from(vec![1, 2, 3]), - symbol: BoundedVec::truncate_from(vec![1, 2, 3]), - }, - fee_per_second: 2*UNIT, - }, - } - .encode(), - ), - ] -} -fn assets_metadata_for_registry_amplitude() -> Vec<(AmplitudeCurrencyId, Vec)> { - vec![ - ( - AmplitudeCurrencyId::Native, - orml_asset_registry::AssetMetadata { - decimals: 12u32, - name: "Amplitude".as_bytes().to_vec(), - symbol: "AMPE".as_bytes().to_vec(), - existential_deposit: 1_000u128, - location: Some(VersionedMultiLocation::V3(MultiLocation::new( - 0, - X1(PalletInstance(10)), - ))), - additional: CustomMetadata { - dia_keys: DiaKeys:: { - blockchain: BoundedVec::truncate_from(vec![1, 2, 3]), - symbol: BoundedVec::truncate_from(vec![1, 2, 3]), - }, - fee_per_second: UNIT, - }, - } - .encode(), - ), - ( - AmplitudeCurrencyId::XCM(1), - orml_asset_registry::AssetMetadata { - decimals: 12u32, - name: "USDT Assethub".as_bytes().to_vec(), - symbol: "USDT".as_bytes().to_vec(), - existential_deposit: 1_000u128, - location: Some(VersionedMultiLocation::V3(asset_hub::USDT_location())), - additional: CustomMetadata { - dia_keys: DiaKeys:: { - blockchain: BoundedVec::truncate_from(vec![1, 2, 3]), - symbol: BoundedVec::truncate_from(vec![1, 2, 3]), - }, - fee_per_second: UNIT/10, - }, - } - .encode(), - ), - ( - AmplitudeCurrencyId::XCM(0), - orml_asset_registry::AssetMetadata { - decimals: 12u32, - name: "Kusama".as_bytes().to_vec(), - symbol: "KSM".as_bytes().to_vec(), - existential_deposit: 1_000u128, - location: Some(VersionedMultiLocation::V3(MultiLocation::parent())), - additional: CustomMetadata { - dia_keys: DiaKeys:: { - blockchain: BoundedVec::truncate_from(vec![1, 2, 3]), - symbol: BoundedVec::truncate_from(vec![1, 2, 3]), - }, - fee_per_second: UNIT/20, - }, - } - .encode(), - ), - ] -} pub fn para_ext(chain: ParachainType) -> sp_io::TestExternalities { match chain { ParachainType::PolkadotAssetHub => @@ -408,31 +226,27 @@ impl Builder for ExtBuilderParachain { } fn build(self) -> TestExternalities { - let assets_metadata_pendulum = assets_metadata_for_registry_pendulum(); - let assets_metadata_amplitude = assets_metadata_for_registry_amplitude(); match self.chain { ParachainType::Pendulum => { use pendulum_runtime::{Runtime, System}; - build_parachain_with_orml_and_asset_registry!( + build_parachain_with_orml!( self, Runtime, System, NATIVE_INITIAL_BALANCE, ORML_INITIAL_BALANCE, - PendulumCurrencyId, - assets_metadata_pendulum + PendulumCurrencyId ) }, ParachainType::Amplitude => { use amplitude_runtime::{Runtime, System}; - build_parachain_with_orml_and_asset_registry!( + build_parachain_with_orml!( self, Runtime, System, NATIVE_INITIAL_BALANCE, ORML_INITIAL_BALANCE, - AmplitudeCurrencyId, - assets_metadata_amplitude + PendulumCurrencyId ) }, _ => panic!("cannot use this chain to build"), diff --git a/runtime/integration-tests/src/pendulum_tests.rs b/runtime/integration-tests/src/pendulum_tests.rs index 80df82ece..9e317eb35 100644 --- a/runtime/integration-tests/src/pendulum_tests.rs +++ b/runtime/integration-tests/src/pendulum_tests.rs @@ -18,11 +18,10 @@ use statemint_runtime as polkadot_asset_hub_runtime; use xcm::latest::NetworkId; use xcm_emulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, TestExt}; -// Native fee expected for each token according to the `fee_per_second` values defined in the mock -const NATIVE_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 4000000000; -const DOT_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = NATIVE_FEE_WHEN_TRANSFER_TO_PARACHAIN /4; -const MOONBEAM_BRZ_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 2*NATIVE_FEE_WHEN_TRANSFER_TO_PARACHAIN; -const USDT_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = NATIVE_FEE_WHEN_TRANSFER_TO_PARACHAIN /2; +const DOT_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 32653061; //The fees that relay chain will charge when transfer DOT to parachain. sovereign account of some parachain will receive transfer_amount - DOT_FEE +const MOONBEAM_BRZ_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 1391304347; //Fees that we will charge in incoming Moonbeam's BRZ. Depends on the RelativeValue struct implementation. +const USDT_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 266666666; +const NATIVE_FEE_WHEN_TRANSFER_TO_PARACHAIN: polkadot_core_primitives::Balance = 3200000000; decl_test_relay_chain! { pub struct PolkadotRelay { diff --git a/runtime/integration-tests/src/test_macros.rs b/runtime/integration-tests/src/test_macros.rs index 0ee5f11cc..1eed61c4c 100644 --- a/runtime/integration-tests/src/test_macros.rs +++ b/runtime/integration-tests/src/test_macros.rs @@ -236,13 +236,12 @@ macro_rules! parachain1_transfer_incorrect_asset_to_parachain2_should_fail { $parachain2::execute_with(|| { use $para2_runtime::{RuntimeEvent, System}; - //since the asset registry trader cannot find the fee per second for the asset, - //it will return TooExpensive error. + //most likely this is not emitid because buy execution fails assert!(System::events().iter().any(|r| matches!( r.event, RuntimeEvent::XcmpQueue(cumulus_pallet_xcmp_queue::Event::Fail { message_hash: _, - error: xcm::v3::Error::TooExpensive, + error: xcm::v3::Error::AssetNotFound, weight: _ }) ))); diff --git a/runtime/pendulum/src/xcm_config.rs b/runtime/pendulum/src/xcm_config.rs index eaff224ef..f5d057057 100644 --- a/runtime/pendulum/src/xcm_config.rs +++ b/runtime/pendulum/src/xcm_config.rs @@ -1,11 +1,13 @@ use core::marker::PhantomData; -use cumulus_primitives_utility::XcmFeesTo32ByteAccount; +use cumulus_primitives_utility::{ + ChargeWeightInFungibles, TakeFirstAssetTrader, XcmFeesTo32ByteAccount, +}; use frame_support::{ log, match_types, parameter_types, traits::{ContainsPair, Everything, Nothing}, + weights::{Weight, WeightToFee as WeightToFeeTrait}, }; -use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{ location::{RelativeReserveProvider, Reserve}, parameter_type_with_key, @@ -17,16 +19,20 @@ use sp_runtime::traits::Convert; use xcm::latest::{prelude::*, Weight as XCMWeight}; use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, EnsureXcmOrigin, FixedWeightBounds, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, + FixedWeightBounds, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, +}; +use xcm_executor::{ + traits::{JustTry, ShouldExecute}, + XcmExecutor, }; -use xcm_executor::{traits::ShouldExecute, XcmExecutor}; use runtime_common::{ custom_transactor::{AssetData, AutomationPalletConfig, CustomTransactorInterceptor}, parachains::polkadot::{asset_hub, equilibrium, moonbeam, polkadex}, - asset_registry::FixedConversionRateProvider, + RelativeValue, }; use crate::{ @@ -42,9 +48,9 @@ use crate::{ }; use super::{ - AccountId, AssetRegistry, Balance, Balances, Currencies, CurrencyId, ParachainInfo, - ParachainSystem, PendulumTreasuryAccount, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, - RuntimeOrigin, System, XcmpQueue, + AccountId, Balance, Balances, Currencies, CurrencyId, ParachainInfo, ParachainSystem, + PendulumTreasuryAccount, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, + System, Tokens, WeightToFee, XcmpQueue, }; parameter_types! { @@ -96,6 +102,30 @@ impl Convert> for CurrencyIdConvert { } } +type RelativeValueOf = RelativeValue; + +pub struct RelayRelativeValue; +impl RelayRelativeValue { + fn get_relative_value(id: CurrencyId) -> Option { + match id { + CurrencyId::XCM(f) => match f { + xcm_assets::RELAY_DOT => Some(RelativeValueOf { num: 98, denominator: 1 }), + xcm_assets::ASSETHUB_USDT => Some(RelativeValueOf { num: 12, denominator: 1 }), + xcm_assets::ASSETHUB_USDC => Some(RelativeValueOf { num: 12, denominator: 1 }), + xcm_assets::EQUILIBRIUM_EQD => Some(RelativeValueOf { num: 12, denominator: 1 }), + xcm_assets::MOONBEAM_BRZ => Some(RelativeValueOf { num: 23, denominator: 10 }), + xcm_assets::POLKADEX_PDEX => Some(RelativeValueOf { num: 14, denominator: 1 }), + xcm_assets::MOONBEAM_GLMR => Some(RelativeValueOf { num: 55, denominator: 10 }), + _ => None, + }, + + CurrencyId::Native => Some(RelativeValueOf { num: 1, denominator: 1 }), + assets::tokens::EURC_ID => Some(RelativeValueOf { num: 13, denominator: 1 }), + _ => Some(RelativeValueOf { num: 10, denominator: 1 }), + } + } +} + impl Convert> for CurrencyIdConvert { fn convert(location: MultiLocation) -> Option { match location { @@ -188,6 +218,13 @@ parameter_types! { pub const MaxAssetsForTransfer: usize = 2; } +match_types! { + pub type ParentOrParentsExecutivePlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } + }; +} + //TODO: move DenyThenTry to polkadot's xcm module. /// Deny executing the xcm message if it matches any of the Deny filter regardless of anything else. /// If it passes the Deny, and matches one of the Allow cases then it is let through. @@ -269,10 +306,28 @@ pub type Barrier = ( AllowSubscriptionsFrom, ); -pub type Traders = AssetRegistryTrader< - FixedRateAssetRegistryTrader>, - XcmFeesTo32ByteAccount, ->; +pub struct ChargeWeightInFungiblesImplementation; +impl ChargeWeightInFungibles for ChargeWeightInFungiblesImplementation { + fn charge_weight_in_fungibles( + asset_id: CurrencyId, + weight: Weight, + ) -> Result { + let amount = ::weight_to_fee(&weight); + + // since this is calibrated (in theory) for the native of the relay + // we should just have a multiplier for relative "value" of that token + // and adjust the amount inversily proportional to the value + if let Some(relative_value) = RelayRelativeValue::get_relative_value(asset_id) { + let adjusted_amount = + RelativeValue::::divide_by_relative_value(amount, relative_value); + log::info!("amount to be charged: {:?} in asset: {:?}", adjusted_amount, asset_id); + return Ok(adjusted_amount) + } else { + log::info!("amount to be charged: {:?} in asset: {:?}", amount, asset_id); + return Ok(amount) + } + } +} /// Means for transacting the currencies of this parachain type Transactor = MultiCurrencyAdapter< @@ -286,6 +341,16 @@ type Transactor = MultiCurrencyAdapter< DepositToAlternative, >; +pub type Traders = ( + TakeFirstAssetTrader< + AccountId, + ChargeWeightInFungiblesImplementation, + ConvertedConcreteId, + Tokens, + XcmFeesTo32ByteAccount, + >, +); + // We will allow for BRZ location from moonbeam pub struct AutomationPalletConfigPendulum;