git.delta.rocks / unique-network / refs/commits / 9b72a3a55cc6

difftreelog

Weight trader removed

Dev2022-08-29parent: #6fb8930.patch.diff
in: master

8 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -65,7 +65,6 @@
 	Unknown(String),
 }
 
-
 #[cfg(not(feature = "unique-runtime"))]
 /// PARA_ID for Opal/Quartz
 const PARA_ID: u32 = 2095;
modifiedpallets/foreing-assets/src/lib.rsdiffbeforeafterboth
--- a/pallets/foreing-assets/src/lib.rs
+++ b/pallets/foreing-assets/src/lib.rs
@@ -458,7 +458,7 @@
 
 use xcm::latest::{Fungibility::Fungible as XcmFungible};
 
-pub struct UsingAnyCurrencyComponents<
+pub struct FreeForAll<
 	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
 	AssetId: Get<MultiLocation>,
 	AccountId,
@@ -476,8 +476,7 @@
 		AccountId,
 		Currency: CurrencyT<AccountId>,
 		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
-	> WeightTrader
-	for UsingAnyCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
+	> WeightTrader for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
 {
 	fn new() -> Self {
 		Self(0, Zero::zero(), PhantomData)
@@ -485,46 +484,7 @@
 
 	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
 		log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);
-
-		let amount: Currency::Balance = (0 as u32).into();
-		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;
-
-		let asset_id = payment
-			.fungible
-			.iter()
-			.next()
-			.map_or(Err(XcmError::TooExpensive), |v| Ok(v.0))?;
-
-		// First fungible pays fee
-		let required = MultiAsset {
-			id: asset_id.clone(),
-			fun: XcmFungible(u128_amount),
-		};
-
-		log::trace!(
-			target: "fassets::weight", "buy_weight payment: {:?}, required: {:?}",
-			payment, required,
-		);
-
-		let unused = payment
-			.checked_sub(required)
-			.map_err(|_| XcmError::TooExpensive)?;
-		self.0 = self.0.saturating_add(weight);
-		self.1 = self.1.saturating_add(amount);
-		Ok(unused)
-	}
-
-	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {
-		let weight = weight.min(self.0);
-		let amount = WeightToFee::weight_to_fee(&weight);
-		self.0 -= weight;
-		self.1 = self.1.saturating_sub(amount);
-		let amount: u128 = amount.saturated_into();
-		if amount > 0 {
-			Some((AssetId::get(), amount).into())
-		} else {
-			None
-		}
+		Ok(payment)
 	}
 }
 impl<
@@ -533,7 +493,7 @@
 		AccountId,
 		Currency: CurrencyT<AccountId>,
 		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
-	> Drop for UsingAnyCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
+	> Drop for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
 {
 	fn drop(&mut self) {
 		OnUnbalanced::on_unbalanced(Currency::issue(self.1));
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -171,10 +171,9 @@
 	/// Foreign collection flag
 	#[pallet::storage]
 	pub type ForeignCollection<T: Config> =
-	StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = bool, QueryKind = ValueQuery>;
+		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = bool, QueryKind = ValueQuery>;
 }
 
-
 /// Wrapper around untyped collection handle, asserting inner collection is of fungible type.
 /// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].
 pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
@@ -340,7 +339,7 @@
 				to: H160::default(),
 				value: amount.into(),
 			}
-				.to_log(collection_id_to_address(collection.id)),
+			.to_log(collection_id_to_address(collection.id)),
 		);
 		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
 			collection.id,
@@ -560,7 +559,7 @@
 					to: *user.as_eth(),
 					value: amount.into(),
 				}
-					.to_log(collection_id_to_address(collection.id)),
+				.to_log(collection_id_to_address(collection.id)),
 			);
 			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
 				collection.id,
modifiedruntime/common/config/pallets/foreign_asset.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/foreign_asset.rs
+++ b/runtime/common/config/pallets/foreign_asset.rs
@@ -2,8 +2,8 @@
 use up_common::types::AccountId;
 
 impl pallet_foreing_assets::Config for Runtime {
-    type Event = Event;
-    type Currency = Balances;
-    type RegisterOrigin = frame_system::EnsureRoot<AccountId>;
-    type WeightInfo = ();
+	type Event = Event;
+	type Currency = Balances;
+	type RegisterOrigin = frame_system::EnsureRoot<AccountId>;
+	type WeightInfo = ();
 }
modifiedruntime/common/config/xcm.rsdiffbeforeafterboth
--- a/runtime/common/config/xcm.rs
+++ b/runtime/common/config/xcm.rs
@@ -16,8 +16,8 @@
 
 use frame_support::{
 	traits::{
-		Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get, Everything,
-		fungibles,
+		Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get,
+		Everything, fungibles,
 	},
 	weights::{Weight, WeightToFeePolynomial, WeightToFee},
 	parameter_types, match_types,
@@ -37,21 +37,23 @@
 };
 use xcm_builder::{
 	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,
-	FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser, RelayChainAsNative,
-	SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
-	SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, ParentIsPreset,
-	ConvertedConcreteAssetId
+	FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser,
+	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
+	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
+	ParentIsPreset, ConvertedConcreteAssetId,
 };
 use xcm_executor::{Config, XcmExecutor, Assets};
-use xcm_executor::traits::{Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation};
+use xcm_executor::traits::{
+	Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation,
+};
 use pallet_foreing_assets::{
-	AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,
-	UsingAnyCurrencyComponents, TryAsForeing, ForeignAssetId,
+	AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency, FreeForAll,
+	TryAsForeing, ForeignAssetId,
 };
 use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};
 use crate::{
 	Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,
-	xcm_config::Barrier
+	xcm_config::Barrier,
 };
 #[cfg(feature = "foreign-assets")]
 use crate::ForeingAssets;
@@ -83,8 +85,22 @@
 pub struct OnlySelfCurrency;
 impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {
 	fn matches_fungible(a: &MultiAsset) -> Option<B> {
+		let paraid = Parachain(ParachainInfo::parachain_id().into());
 		match (&a.id, &a.fun) {
-			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),
+			(
+				Concrete(MultiLocation {
+					parents: 1,
+					interior: X1(loc),
+				}),
+				XcmFungible(ref amount),
+			) if paraid == *loc => CheckedConversion::checked_from(*amount),
+			(
+				Concrete(MultiLocation {
+					parents: 0,
+					interior: Here,
+				}),
+				XcmFungible(ref amount),
+			) => CheckedConversion::checked_from(*amount),
 			_ => None,
 		}
 	}
@@ -188,48 +204,7 @@
 	}
 
 	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
-		let amount: Currency::Balance = (0 as u32).into();
-		//let amount = WeightToFee::weight_to_fee(&weight);
-		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;
-
-		// location to this parachain through relay chain
-		let option1: xcm::v1::AssetId = Concrete(MultiLocation {
-			parents: 1,
-			interior: X1(Parachain(ParachainInfo::parachain_id().into())),
-		});
-		// direct location
-		let option2: xcm::v1::AssetId = Concrete(MultiLocation {
-			parents: 0,
-			interior: Here,
-		});
-
-		let required = if payment.fungible.contains_key(&option1) {
-			(option1, u128_amount).into()
-		} else if payment.fungible.contains_key(&option2) {
-			(option2, u128_amount).into()
-		} else {
-			(Concrete(MultiLocation::default()), u128_amount).into()
-		};
-
-		let unused = payment
-			.checked_sub(required)
-			.map_err(|_| XcmError::TooExpensive)?;
-		self.0 = self.0.saturating_add(weight);
-		self.1 = self.1.saturating_add(amount);
-		Ok(unused)
-	}
-
-	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {
-		let weight = weight.min(self.0);
-		let amount = WeightToFee::weight_to_fee(&weight);
-		self.0 -= weight;
-		self.1 = self.1.saturating_sub(amount);
-		let amount: u128 = amount.saturated_into();
-		if amount > 0 {
-			Some((AssetId::get(), amount).into())
-		} else {
-			None
-		}
+		Ok(payment)
 	}
 }
 impl<
@@ -255,9 +230,9 @@
 
 #[cfg(feature = "foreign-assets")]
 impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>
-for NonZeroIssuance<AccountId, ForeingAssets>
-	where
-		ForeingAssets: fungibles::Inspect<AccountId>,
+	for NonZeroIssuance<AccountId, ForeingAssets>
+where
+	ForeingAssets: fungibles::Inspect<AccountId>,
 {
 	fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {
 		!ForeingAssets::total_issuance(*id).is_zero()
@@ -268,11 +243,11 @@
 pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
 #[cfg(feature = "foreign-assets")]
 impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>
-ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>
-	where
-		AssetId: Borrow<AssetId>,
-		AssetId: TryAsForeing<AssetId, ForeignAssetId>,
-		AssetIds: Borrow<AssetId>,
+	ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>
+where
+	AssetId: Borrow<AssetId>,
+	AssetId: TryAsForeing<AssetId, ForeignAssetId>,
+	AssetIds: Borrow<AssetId>,
 {
 	fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {
 		let id = id.borrow();
@@ -377,10 +352,13 @@
 pub type IsReserve = NativeAsset;
 
 #[cfg(feature = "foreign-assets")]
-type Trader<T> =
-	UsingAnyCurrencyComponents<
-		pallet_configuration::WeightToFee<T, Balance>,
-		RelayLocation, AccountId, Balances, ()>;
+type Trader<T> = FreeForAll<
+	pallet_configuration::WeightToFee<T, Balance>,
+	RelayLocation,
+	AccountId,
+	Balances,
+	(),
+>;
 #[cfg(not(feature = "foreign-assets"))]
 type Trader<T> = UsingOnlySelfCurrencyComponents<
 	pallet_configuration::WeightToFee<T, Balance>,
@@ -451,4 +429,3 @@
 	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;
 	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
 }
-
modifiedruntime/opal/src/xcm_config.rsdiffbeforeafterboth
--- a/runtime/opal/src/xcm_config.rs
+++ b/runtime/opal/src/xcm_config.rs
@@ -32,9 +32,9 @@
 	v1::{BodyId, Junction::*, Junctions::*, MultiLocation, NetworkId},
 };
 use xcm_builder::{
-	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
-	EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter, LocationInverter, ParentAsSuperuser,
-	ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
+	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, EnsureXcmOrigin,
+	FixedWeightBounds, FungiblesAdapter, LocationInverter, ParentAsSuperuser, ParentIsPreset,
+	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
 	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
 	ConvertedConcreteAssetId,
 };
@@ -49,8 +49,8 @@
 };
 
 use crate::{
-	Balances, Call, DmpQueue, Event, ForeingAssets, Origin, ParachainInfo,
-	ParachainSystem, PolkadotXcm, Runtime, XcmpQueue,
+	Balances, Call, DmpQueue, Event, ForeingAssets, Origin, ParachainInfo, ParachainSystem,
+	PolkadotXcm, Runtime, XcmpQueue,
 };
 use crate::runtime_common::config::substrate::{TreasuryModuleId, MaxLocks, MaxReserves};
 use crate::runtime_common::config::pallets::TreasuryAccountId;
@@ -58,8 +58,8 @@
 use crate::*;
 
 use pallet_foreing_assets::{
-	AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,
-	UsingAnyCurrencyComponents, TryAsForeing, ForeignAssetId,
+	AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency, FreeForAll,
+	TryAsForeing, ForeignAssetId,
 };
 
 // Signed version of balance
@@ -330,7 +330,7 @@
 	type Barrier = Barrier;
 	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
 	type Trader =
-		UsingAnyCurrencyComponents<LinearFee<Balance>, RelayLocation, AccountId, Balances, ()>;
+		FreeForAll<LinearFee<Balance>, RelayLocation, AccountId, Balances, ()>;
 	type ResponseHandler = (); // Don't handle responses for now.
 	type SubscriptionService = PolkadotXcm;
 	type AssetTrap = PolkadotXcm;
modifiedruntime/quartz/src/xcm_config.rsdiffbeforeafterboth
--- a/runtime/quartz/src/xcm_config.rs
+++ b/runtime/quartz/src/xcm_config.rs
@@ -50,7 +50,7 @@
 };
 use pallet_foreing_assets::{
     AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,
-    UsingAnyCurrencyComponents, TryAsForeing, ForeignAssetId,
+    FreeForAll, TryAsForeing, ForeignAssetId,
 };
 use crate::{
     Balances, Call, DmpQueue, Event, Origin, ParachainInfo,
modifiedruntime/unique/src/xcm_config.rsdiffbeforeafterboth
before · runtime/unique/src/xcm_config.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use cumulus_pallet_xcm;18use frame_support::{19    {match_types, parameter_types, weights::Weight},20    pallet_prelude::Get,21    traits::{Contains, Everything, fungibles},22};23use frame_system::EnsureRoot;24use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key};25use pallet_xcm::XcmPassthrough;26use polkadot_parachain::primitives::Sibling;27use sp_runtime::traits::{AccountIdConversion, CheckedConversion, Convert, Zero};28use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};29use xcm::{30    latest::{MultiAsset, Xcm},31    prelude::{Concrete, Fungible as XcmFungible},32    v1::{BodyId, Junction::*, Junctions::*, MultiLocation, NetworkId},33};34use xcm_builder::{35    AllowKnownQueryResponses, AllowSubscriptionsFrom,36    AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,37    EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter, LocationInverter, ParentAsSuperuser,38    ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,39    SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,40    ConvertedConcreteAssetId,41};42use xcm_executor::{43    {Config, XcmExecutor},44    traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible, ShouldExecute},45};4647use up_common::{48    constants::{MAXIMUM_BLOCK_WEIGHT, UNIQUE},49    types::{AccountId, Balance},50};51use pallet_foreing_assets::{52    AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,53    UsingAnyCurrencyComponents, TryAsForeing, ForeignAssetId,54};55use crate::{56    Balances, Call, DmpQueue, Event, Origin, ParachainInfo,57    ParachainSystem, PolkadotXcm, Runtime, XcmpQueue,58};59use crate::runtime_common::config::substrate::{TreasuryModuleId, MaxLocks, MaxReserves};60use crate::runtime_common::config::pallets::TreasuryAccountId;61use crate::runtime_common::config::xcm::*;62use crate::*;63use xcm::opaque::latest::prelude::{ DepositReserveAsset, DepositAsset, TransferAsset, TransferReserveAsset };6465// Signed version of balance66pub type Amount = i128;676869pub type Barrier = DenyThenTry<70    DenyExchangeWithUnknownLocation,71    (72        TakeWeightCredit,73        AllowTopLevelPaidExecutionFrom<Everything>,74        // Parent and its exec plurality get free execution75        AllowUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,76        // Expected responses are OK.77        AllowKnownQueryResponses<PolkadotXcm>,78        // Subscriptions for version tracking are OK.79        AllowSubscriptionsFrom<ParentOrSiblings>,80    ),81>;8283pub fn get_allowed_locations() -> Vec<MultiLocation> {84    vec![85        // Self location86        MultiLocation { parents: 0, interior: Here },87        // Parent location88        MultiLocation { parents: 1, interior: Here },89        // Karura/Acala location90        MultiLocation { parents: 1, interior: X1(Parachain(2000)) },91        // Self parachain address92        MultiLocation { parents: 1, interior: X1(Parachain(ParachainInfo::get().into())) },93    ]94}9596pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)97    where98        Deny: ShouldExecute,99        Allow: ShouldExecute;100101impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>102    where103        Deny: ShouldExecute,104        Allow: ShouldExecute,105{106    fn should_execute<Call>(107        origin: &MultiLocation,108        message: &mut Xcm<Call>,109        max_weight: Weight,110        weight_credit: &mut Weight,111    ) -> Result<(), ()> {112        Deny::should_execute(origin, message, max_weight, weight_credit)?;113        Allow::should_execute(origin, message, max_weight, weight_credit)114    }115}116117// Allow xcm exchange only with locations in list118pub struct DenyExchangeWithUnknownLocation;119impl ShouldExecute for DenyExchangeWithUnknownLocation {120    fn should_execute<Call>(121        origin: &MultiLocation,122        message: &mut Xcm<Call>,123        _max_weight: Weight,124        _weight_credit: &mut Weight,125    ) -> Result<(), ()> {126127        // Check if deposit or transfer belongs to allowed parachains128        let mut allowed = get_allowed_locations().contains(origin);129130        message.0.iter().for_each(|inst| {131            match inst {132                DepositReserveAsset { dest: dst, .. } => { allowed |= get_allowed_locations().contains(dst); }133                TransferReserveAsset { dest: dst, .. } => { allowed |= get_allowed_locations().contains(dst); }134                _ => {}135            }136        });137138        if allowed {139            return Ok(());140        }141142        log::warn!(143			target: "xcm::barrier",144			"Unexpected deposit or transfer location"145		);146        // Deny147        Err(())148    }149}150151152match_types! {153	pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = {154		MultiLocation { parents: 1, interior: Here } |155		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) }156	};157	pub type ParentOrSiblings: impl Contains<MultiLocation> = {158		MultiLocation { parents: 1, interior: Here } |159		MultiLocation { parents: 1, interior: X1(_) }160	};161}162163pub fn get_all_module_accounts() -> Vec<AccountId> {164    vec![TreasuryModuleId::get().into_account_truncating()]165}166167pub struct DustRemovalWhitelist;168impl Contains<AccountId> for DustRemovalWhitelist {169    fn contains(a: &AccountId) -> bool {170        get_all_module_accounts().contains(a)171    }172}173174parameter_type_with_key! {175	pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance {176		match currency_id {177			CurrencyId::NativeAssetId(symbol) => match symbol {178				NativeCurrency::Here => 0,179				NativeCurrency::Parent=> 0,180			},181			_ => 100_000182		}183	};184}185186impl orml_tokens::Config for Runtime {187    type Event = Event;188    type Balance = Balance;189    type Amount = Amount;190    type CurrencyId = CurrencyId;191    type WeightInfo = ();192    type ExistentialDeposits = ExistentialDeposits;193    type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;194    type MaxLocks = MaxLocks;195    type MaxReserves = MaxReserves;196    // TODO: Add all module accounts197    type DustRemovalWhitelist = DustRemovalWhitelist;198    /// The id type for named reserves.199    type ReserveIdentifier = ();200    type OnNewTokenAccount = ();201    type OnKilledTokenAccount = ();202}203204205parameter_types! {206	pub const BaseXcmWeight: Weight = 100_000_000; // TODO: recheck this207	pub const MaxAssetsForTransfer: usize = 2;208}209210parameter_type_with_key! {211	pub ParachainMinFee: |_location: MultiLocation| -> Option<u128> {212		Some(100_000_000)213	};214}215216217pub struct AccountIdToMultiLocation;218impl Convert<AccountId, MultiLocation> for AccountIdToMultiLocation {219    fn convert(account: AccountId) -> MultiLocation {220        X1(AccountId32 {221            network: NetworkId::Any,222            id: account.into(),223        })224            .into()225    }226}
after · runtime/unique/src/xcm_config.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use cumulus_pallet_xcm;18use frame_support::{19    {match_types, parameter_types, weights::Weight},20    pallet_prelude::Get,21    traits::{Contains, Everything, fungibles},22};23use frame_system::EnsureRoot;24use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key};25use pallet_xcm::XcmPassthrough;26use polkadot_parachain::primitives::Sibling;27use sp_runtime::traits::{AccountIdConversion, CheckedConversion, Convert, Zero};28use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};29use xcm::{30    latest::{MultiAsset, Xcm},31    prelude::{Concrete, Fungible as XcmFungible},32    v1::{BodyId, Junction::*, Junctions::*, MultiLocation, NetworkId},33};34use xcm_builder::{35    AllowKnownQueryResponses, AllowSubscriptionsFrom,36    AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,37    EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter, LocationInverter, ParentAsSuperuser,38    ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,39    SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,40    ConvertedConcreteAssetId,41};42use xcm_executor::{43    {Config, XcmExecutor},44    traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible, ShouldExecute},45};4647use up_common::{48    constants::{MAXIMUM_BLOCK_WEIGHT, UNIQUE},49    types::{AccountId, Balance},50};51use pallet_foreing_assets::{52    AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,53    FreeForAll, TryAsForeing, ForeignAssetId,54};55use crate::{56    Balances, Call, DmpQueue, Event, Origin, ParachainInfo,57    ParachainSystem, PolkadotXcm, Runtime, XcmpQueue,58};59use crate::runtime_common::config::substrate::{TreasuryModuleId, MaxLocks, MaxReserves};60use crate::runtime_common::config::pallets::TreasuryAccountId;61use crate::runtime_common::config::xcm::*;62use crate::*;63use xcm::opaque::latest::prelude::{ DepositReserveAsset, DepositAsset, TransferAsset, TransferReserveAsset };6465// Signed version of balance66pub type Amount = i128;676869pub type Barrier = DenyThenTry<70    DenyExchangeWithUnknownLocation,71    (72        TakeWeightCredit,73        AllowTopLevelPaidExecutionFrom<Everything>,74        // Parent and its exec plurality get free execution75        AllowUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,76        // Expected responses are OK.77        AllowKnownQueryResponses<PolkadotXcm>,78        // Subscriptions for version tracking are OK.79        AllowSubscriptionsFrom<ParentOrSiblings>,80    ),81>;8283pub fn get_allowed_locations() -> Vec<MultiLocation> {84    vec![85        // Self location86        MultiLocation { parents: 0, interior: Here },87        // Parent location88        MultiLocation { parents: 1, interior: Here },89        // Karura/Acala location90        MultiLocation { parents: 1, interior: X1(Parachain(2000)) },91        // Self parachain address92        MultiLocation { parents: 1, interior: X1(Parachain(ParachainInfo::get().into())) },93    ]94}9596pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)97    where98        Deny: ShouldExecute,99        Allow: ShouldExecute;100101impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>102    where103        Deny: ShouldExecute,104        Allow: ShouldExecute,105{106    fn should_execute<Call>(107        origin: &MultiLocation,108        message: &mut Xcm<Call>,109        max_weight: Weight,110        weight_credit: &mut Weight,111    ) -> Result<(), ()> {112        Deny::should_execute(origin, message, max_weight, weight_credit)?;113        Allow::should_execute(origin, message, max_weight, weight_credit)114    }115}116117// Allow xcm exchange only with locations in list118pub struct DenyExchangeWithUnknownLocation;119impl ShouldExecute for DenyExchangeWithUnknownLocation {120    fn should_execute<Call>(121        origin: &MultiLocation,122        message: &mut Xcm<Call>,123        _max_weight: Weight,124        _weight_credit: &mut Weight,125    ) -> Result<(), ()> {126127        // Check if deposit or transfer belongs to allowed parachains128        let mut allowed = get_allowed_locations().contains(origin);129130        message.0.iter().for_each(|inst| {131            match inst {132                DepositReserveAsset { dest: dst, .. } => { allowed |= get_allowed_locations().contains(dst); }133                TransferReserveAsset { dest: dst, .. } => { allowed |= get_allowed_locations().contains(dst); }134                _ => {}135            }136        });137138        if allowed {139            return Ok(());140        }141142        log::warn!(143			target: "xcm::barrier",144			"Unexpected deposit or transfer location"145		);146        // Deny147        Err(())148    }149}150151152match_types! {153	pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = {154		MultiLocation { parents: 1, interior: Here } |155		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) }156	};157	pub type ParentOrSiblings: impl Contains<MultiLocation> = {158		MultiLocation { parents: 1, interior: Here } |159		MultiLocation { parents: 1, interior: X1(_) }160	};161}162163pub fn get_all_module_accounts() -> Vec<AccountId> {164    vec![TreasuryModuleId::get().into_account_truncating()]165}166167pub struct DustRemovalWhitelist;168impl Contains<AccountId> for DustRemovalWhitelist {169    fn contains(a: &AccountId) -> bool {170        get_all_module_accounts().contains(a)171    }172}173174parameter_type_with_key! {175	pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance {176		match currency_id {177			CurrencyId::NativeAssetId(symbol) => match symbol {178				NativeCurrency::Here => 0,179				NativeCurrency::Parent=> 0,180			},181			_ => 100_000182		}183	};184}185186impl orml_tokens::Config for Runtime {187    type Event = Event;188    type Balance = Balance;189    type Amount = Amount;190    type CurrencyId = CurrencyId;191    type WeightInfo = ();192    type ExistentialDeposits = ExistentialDeposits;193    type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;194    type MaxLocks = MaxLocks;195    type MaxReserves = MaxReserves;196    // TODO: Add all module accounts197    type DustRemovalWhitelist = DustRemovalWhitelist;198    /// The id type for named reserves.199    type ReserveIdentifier = ();200    type OnNewTokenAccount = ();201    type OnKilledTokenAccount = ();202}203204205parameter_types! {206	pub const BaseXcmWeight: Weight = 100_000_000; // TODO: recheck this207	pub const MaxAssetsForTransfer: usize = 2;208}209210parameter_type_with_key! {211	pub ParachainMinFee: |_location: MultiLocation| -> Option<u128> {212		Some(100_000_000)213	};214}215216217pub struct AccountIdToMultiLocation;218impl Convert<AccountId, MultiLocation> for AccountIdToMultiLocation {219    fn convert(account: AccountId) -> MultiLocation {220        X1(AccountId32 {221            network: NetworkId::Any,222            id: account.into(),223        })224            .into()225    }226}