difftreelog
wip upd quartz
in: master
4 files changed
runtime/common/config/xcm.rsdiffbeforeafterboth1// 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 frame_support::{18 traits::{19 Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get, Everything,20 fungibles,21 },22 weights::{Weight, WeightToFeePolynomial, WeightToFee},23 parameter_types, match_types,24};25use frame_system::EnsureRoot;26use sp_runtime::{27 traits::{Saturating, CheckedConversion, Zero},28 SaturatedConversion,29};30use pallet_xcm::XcmPassthrough;31use polkadot_parachain::primitives::Sibling;32use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};33use xcm::latest::{34 AssetId::{Concrete},35 Fungibility::Fungible as XcmFungible,36 MultiAsset, Error as XcmError,37};38use xcm_builder::{39 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,40 FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser, RelayChainAsNative,41 SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,42 SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, ParentIsPreset,43 ConvertedConcreteAssetId44};45use xcm_executor::{Config, XcmExecutor, Assets};46use xcm_executor::traits::{Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation};47use pallet_foreing_assets::{48 AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,49 UsingAnyCurrencyComponents, TryAsForeing, ForeignAssetId,50};51use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};52use crate::{53 Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,54 xcm_config::Barrier55};56#[cfg(feature = "foreign-assets")]57use crate::ForeingAssets;5859use up_common::{60 types::{AccountId, Balance},61 constants::*,62};6364parameter_types! {65 pub const RelayLocation: MultiLocation = MultiLocation::parent();66 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;67 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();68 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();69}7071/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used72/// when determining ownership of accounts for asset transacting and when attempting to use XCM73/// `Transact` in order to determine the dispatch Origin.74pub type LocationToAccountId = (75 // The parent (Relay-chain) origin converts to the default `AccountId`.76 ParentIsPreset<AccountId>,77 // Sibling parachain origins convert to AccountId via the `ParaId::into`.78 SiblingParachainConvertsVia<Sibling, AccountId>,79 // Straight up local `AccountId32` origins just alias directly to `AccountId`.80 AccountId32Aliases<RelayNetwork, AccountId>,81);8283pub struct OnlySelfCurrency;84impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {85 fn matches_fungible(a: &MultiAsset) -> Option<B> {86 match (&a.id, &a.fun) {87 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),88 _ => None,89 }90 }91}9293/// Means for transacting assets on this chain.94pub type LocalAssetTransactor = CurrencyAdapter<95 // Use this currency:96 Balances,97 // Use this currency when it is a fungible asset matching the given location or name:98 OnlySelfCurrency,99 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:100 LocationToAccountId,101 // Our chain's account ID type (we can't get away without mentioning it explicitly):102 AccountId,103 // We don't track any teleports.104 (),105>;106107/// No local origins on this chain are allowed to dispatch XCM sends/executions.108pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);109110/// The means for routing XCM messages which are not for local execution into the right message111/// queues.112pub type XcmRouter = (113 // Two routers - use UMP to communicate with the relay chain:114 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,115 // ..and XCMP to communicate with the sibling chains.116 XcmpQueue,117);118119/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,120/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can121/// biases the kind of local `Origin` it will become.122pub type XcmOriginToTransactDispatchOrigin = (123 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location124 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for125 // foreign chains who want to have a local sovereign account on this chain which they control.126 SovereignSignedViaLocation<LocationToAccountId, Origin>,127 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when128 // recognised.129 RelayChainAsNative<RelayOrigin, Origin>,130 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when131 // recognised.132 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,133 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a134 // transaction from the Root origin.135 ParentAsSuperuser<Origin>,136 // Native signed account converter; this just converts an `AccountId32` origin into a normal137 // `Origin::Signed` origin of the same 32-byte value.138 SignedAccountId32AsNative<RelayNetwork, Origin>,139 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.140 XcmPassthrough<Origin>,141);142143parameter_types! {144 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.145 pub UnitWeightCost: Weight = 1_000_000;146 // 1200 UNIQUEs buy 1 second of weight.147 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);148 pub const MaxInstructions: u32 = 100;149}150151match_types! {152 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {153 MultiLocation { parents: 1, interior: Here } |154 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }155 };156}157158/*159pub type Barrier = (160 TakeWeightCredit,161 AllowTopLevelPaidExecutionFrom<Everything>,162 // ^^^ Parent & its unit plurality gets free execution163);164 */165166pub struct UsingOnlySelfCurrencyComponents<167 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,168 AssetId: Get<MultiLocation>,169 AccountId,170 Currency: CurrencyT<AccountId>,171 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,172>(173 Weight,174 Currency::Balance,175 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,176);177impl<178 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,179 AssetId: Get<MultiLocation>,180 AccountId,181 Currency: CurrencyT<AccountId>,182 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,183 > WeightTrader184 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>185{186 fn new() -> Self {187 Self(0, Zero::zero(), PhantomData)188 }189190 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {191 let amount = WeightToFee::weight_to_fee(&weight);192 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;193194 // location to this parachain through relay chain195 let option1: xcm::v1::AssetId = Concrete(MultiLocation {196 parents: 1,197 interior: X1(Parachain(ParachainInfo::parachain_id().into())),198 });199 // direct location200 let option2: xcm::v1::AssetId = Concrete(MultiLocation {201 parents: 0,202 interior: Here,203 });204205 let required = if payment.fungible.contains_key(&option1) {206 (option1, u128_amount).into()207 } else if payment.fungible.contains_key(&option2) {208 (option2, u128_amount).into()209 } else {210 (Concrete(MultiLocation::default()), u128_amount).into()211 };212213 let unused = payment214 .checked_sub(required)215 .map_err(|_| XcmError::TooExpensive)?;216 self.0 = self.0.saturating_add(weight);217 self.1 = self.1.saturating_add(amount);218 Ok(unused)219 }220221 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {222 let weight = weight.min(self.0);223 let amount = WeightToFee::weight_to_fee(&weight);224 self.0 -= weight;225 self.1 = self.1.saturating_sub(amount);226 let amount: u128 = amount.saturated_into();227 if amount > 0 {228 Some((AssetId::get(), amount).into())229 } else {230 None231 }232 }233}234impl<235 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,236 AssetId: Get<MultiLocation>,237 AccountId,238 Currency: CurrencyT<AccountId>,239 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,240 > Drop241 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>242{243 fn drop(&mut self) {244 OnUnbalanced::on_unbalanced(Currency::issue(self.1));245 }246}247248parameter_types! {249 pub CheckingAccount: AccountId = PolkadotXcm::check_account();250}251/// Allow checking in assets that have issuance > 0.252#[cfg(feature = "foreign-assets")]253pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);254255#[cfg(feature = "foreign-assets")]256impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>257for NonZeroIssuance<AccountId, ForeingAssets>258 where259 ForeingAssets: fungibles::Inspect<AccountId>,260{261 fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {262 !ForeingAssets::total_issuance(*id).is_zero()263 }264}265266#[cfg(feature = "foreign-assets")]267pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);268#[cfg(feature = "foreign-assets")]269impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>270ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>271 where272 AssetId: Borrow<AssetId>,273 AssetId: TryAsForeing<AssetId, ForeignAssetId>,274 AssetIds: Borrow<AssetId>,275{276 fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {277 let id = id.borrow();278279 log::trace!(280 target: "xcm::AsInnerId::Convert",281 "AsInnerId {:?}",282 id283 );284285 let parent = MultiLocation::parent();286 let here = MultiLocation::here();287 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));288289 if *id == parent {290 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));291 }292293 if *id == here || *id == self_location {294 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));295 }296297 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {298 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {299 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))300 }301 _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),302 }303 }304305 fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {306 log::trace!(307 target: "xcm::AsInnerId::Reverse",308 "AsInnerId",309 );310311 let asset_id = what.borrow();312313 let parent_id =314 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();315 let here_id =316 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();317318 if asset_id.clone() == parent_id {319 return Ok(MultiLocation::parent());320 }321322 if asset_id.clone() == here_id {323 return Ok(MultiLocation::new(324 1,325 X1(Parachain(ParachainInfo::get().into())),326 ));327 }328329 match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {330 Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {331 Some(location) => Ok(location),332 None => Err(()),333 },334 None => Err(()),335 }336 }337}338339/// Means for transacting assets besides the native currency on this chain.340#[cfg(feature = "foreign-assets")]341pub type FungiblesTransactor = FungiblesAdapter<342 // Use this fungibles implementation:343 ForeingAssets,344 // Use this currency when it is a fungible asset matching the given location or name:345 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,346 // Convert an XCM MultiLocation into a local account id:347 LocationToAccountId,348 // Our chain's account ID type (we can't get away without mentioning it explicitly):349 AccountId,350 // We only want to allow teleports of known assets. We use non-zero issuance as an indication351 // that this asset is known.352 NonZeroIssuance<AccountId, ForeingAssets>,353 // The account to use for tracking teleports.354 CheckingAccount,355>;356357/// Means for transacting assets on this chain.358#[cfg(feature = "foreign-assets")]359pub type AssetTransactors = FungiblesTransactor;360361//#[cfg(not(feature = "foreign-assets"))]362//pub type AssetTransactors = LocalAssetTransactor;363364#[cfg(feature = "foreign-assets")]365pub struct AllAsset;366#[cfg(feature = "foreign-assets")]367impl FilterAssetLocation for AllAsset {368 fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {369 true370 }371}372373#[cfg(feature = "foreign-assets")]374pub type IsReserve = AllAsset;375//#[cfg(not(feature = "foreign-assets"))]376//pub type IsReserve = NativeAsset;377378#[cfg(feature = "foreign-assets")]379type Trader<T> =380 UsingAnyCurrencyComponents<381 pallet_configuration::WeightToFee<T, Balance>,382 RelayLocation, AccountId, Balances, ()>;383/*384#[cfg(not(feature = "foreign-assets"))]385type Trader<T> = UsingOnlySelfCurrencyComponents<386 pallet_configuration::WeightToFee<T, Balance>,387 RelayLocation,388 AccountId,389 Balances,390 (),391>;392*/393394pub struct XcmConfig<T>(PhantomData<T>);395impl<T> Config for XcmConfig<T>396where397 T: pallet_configuration::Config,398{399 type Call = Call;400 type XcmSender = XcmRouter;401 // How to withdraw and deposit an asset.402 type AssetTransactor = AssetTransactors;403 type OriginConverter = XcmOriginToTransactDispatchOrigin;404 type IsReserve = IsReserve;405 type IsTeleporter = (); // Teleportation is disabled406 type LocationInverter = LocationInverter<Ancestry>;407 type Barrier = Barrier;408 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;409 type Trader = Trader<T>;410 type ResponseHandler = (); // Don't handle responses for now.411 type SubscriptionService = PolkadotXcm;412413 type AssetTrap = PolkadotXcm;414 type AssetClaims = PolkadotXcm;415}416417impl pallet_xcm::Config for Runtime {418 type Event = Event;419 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;420 type XcmRouter = XcmRouter;421 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;422 type XcmExecuteFilter = Everything;423 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;424 type XcmTeleportFilter = Everything;425 type XcmReserveTransferFilter = Everything;426 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;427 type LocationInverter = LocationInverter<Ancestry>;428 type Origin = Origin;429 type Call = Call;430 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;431 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;432}433434impl cumulus_pallet_xcm::Config for Runtime {435 type Event = Event;436 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;437}438439impl cumulus_pallet_xcmp_queue::Config for Runtime {440 type WeightInfo = ();441 type Event = Event;442 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;443 type ChannelInfo = ParachainSystem;444 type VersionWrapper = ();445 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;446 type ControllerOrigin = EnsureRoot<AccountId>;447 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;448}449450impl cumulus_pallet_dmp_queue::Config for Runtime {451 type Event = Event;452 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;453 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;454}4551// 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 frame_support::{18 traits::{19 Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get, Everything,20 fungibles,21 },22 weights::{Weight, WeightToFeePolynomial, WeightToFee},23 parameter_types, match_types,24};25use frame_system::EnsureRoot;26use sp_runtime::{27 traits::{Saturating, CheckedConversion, Zero},28 SaturatedConversion,29};30use pallet_xcm::XcmPassthrough;31use polkadot_parachain::primitives::Sibling;32use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};33use xcm::latest::{34 AssetId::{Concrete},35 Fungibility::Fungible as XcmFungible,36 MultiAsset, Error as XcmError,37};38use xcm_builder::{39 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,40 FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser, RelayChainAsNative,41 SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,42 SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, ParentIsPreset,43 ConvertedConcreteAssetId44};45use xcm_executor::{Config, XcmExecutor, Assets};46use xcm_executor::traits::{Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation};47use pallet_foreing_assets::{48 AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency,49 UsingAnyCurrencyComponents, TryAsForeing, ForeignAssetId,50};51use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};52use crate::{53 Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,54 xcm_config::Barrier55};56#[cfg(feature = "foreign-assets")]57use crate::ForeingAssets;5859use up_common::{60 types::{AccountId, Balance},61 constants::*,62};6364parameter_types! {65 pub const RelayLocation: MultiLocation = MultiLocation::parent();66 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;67 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();68 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();69}7071/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used72/// when determining ownership of accounts for asset transacting and when attempting to use XCM73/// `Transact` in order to determine the dispatch Origin.74pub type LocationToAccountId = (75 // The parent (Relay-chain) origin converts to the default `AccountId`.76 ParentIsPreset<AccountId>,77 // Sibling parachain origins convert to AccountId via the `ParaId::into`.78 SiblingParachainConvertsVia<Sibling, AccountId>,79 // Straight up local `AccountId32` origins just alias directly to `AccountId`.80 AccountId32Aliases<RelayNetwork, AccountId>,81);8283pub struct OnlySelfCurrency;84impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {85 fn matches_fungible(a: &MultiAsset) -> Option<B> {86 match (&a.id, &a.fun) {87 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),88 _ => None,89 }90 }91}9293/// Means for transacting assets on this chain.94pub type LocalAssetTransactor = CurrencyAdapter<95 // Use this currency:96 Balances,97 // Use this currency when it is a fungible asset matching the given location or name:98 OnlySelfCurrency,99 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:100 LocationToAccountId,101 // Our chain's account ID type (we can't get away without mentioning it explicitly):102 AccountId,103 // We don't track any teleports.104 (),105>;106107/// No local origins on this chain are allowed to dispatch XCM sends/executions.108pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);109110/// The means for routing XCM messages which are not for local execution into the right message111/// queues.112pub type XcmRouter = (113 // Two routers - use UMP to communicate with the relay chain:114 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,115 // ..and XCMP to communicate with the sibling chains.116 XcmpQueue,117);118119/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,120/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can121/// biases the kind of local `Origin` it will become.122pub type XcmOriginToTransactDispatchOrigin = (123 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location124 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for125 // foreign chains who want to have a local sovereign account on this chain which they control.126 SovereignSignedViaLocation<LocationToAccountId, Origin>,127 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when128 // recognised.129 RelayChainAsNative<RelayOrigin, Origin>,130 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when131 // recognised.132 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,133 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a134 // transaction from the Root origin.135 ParentAsSuperuser<Origin>,136 // Native signed account converter; this just converts an `AccountId32` origin into a normal137 // `Origin::Signed` origin of the same 32-byte value.138 SignedAccountId32AsNative<RelayNetwork, Origin>,139 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.140 XcmPassthrough<Origin>,141);142143parameter_types! {144 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.145 pub UnitWeightCost: Weight = 1_000_000;146 // 1200 UNIQUEs buy 1 second of weight.147 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);148 pub const MaxInstructions: u32 = 100;149}150151match_types! {152 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {153 MultiLocation { parents: 1, interior: Here } |154 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }155 };156}157158/*159pub type Barrier = (160 TakeWeightCredit,161 AllowTopLevelPaidExecutionFrom<Everything>,162 // ^^^ Parent & its unit plurality gets free execution163);164 */165166pub struct UsingOnlySelfCurrencyComponents<167 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,168 AssetId: Get<MultiLocation>,169 AccountId,170 Currency: CurrencyT<AccountId>,171 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,172>(173 Weight,174 Currency::Balance,175 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,176);177impl<178 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,179 AssetId: Get<MultiLocation>,180 AccountId,181 Currency: CurrencyT<AccountId>,182 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,183 > WeightTrader184 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>185{186 fn new() -> Self {187 Self(0, Zero::zero(), PhantomData)188 }189190 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {191 let amount = WeightToFee::weight_to_fee(&weight);192 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;193194 // location to this parachain through relay chain195 let option1: xcm::v1::AssetId = Concrete(MultiLocation {196 parents: 1,197 interior: X1(Parachain(ParachainInfo::parachain_id().into())),198 });199 // direct location200 let option2: xcm::v1::AssetId = Concrete(MultiLocation {201 parents: 0,202 interior: Here,203 });204205 let required = if payment.fungible.contains_key(&option1) {206 (option1, u128_amount).into()207 } else if payment.fungible.contains_key(&option2) {208 (option2, u128_amount).into()209 } else {210 (Concrete(MultiLocation::default()), u128_amount).into()211 };212213 let unused = payment214 .checked_sub(required)215 .map_err(|_| XcmError::TooExpensive)?;216 self.0 = self.0.saturating_add(weight);217 self.1 = self.1.saturating_add(amount);218 Ok(unused)219 }220221 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {222 let weight = weight.min(self.0);223 let amount = WeightToFee::weight_to_fee(&weight);224 self.0 -= weight;225 self.1 = self.1.saturating_sub(amount);226 let amount: u128 = amount.saturated_into();227 if amount > 0 {228 Some((AssetId::get(), amount).into())229 } else {230 None231 }232 }233}234impl<235 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,236 AssetId: Get<MultiLocation>,237 AccountId,238 Currency: CurrencyT<AccountId>,239 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,240 > Drop241 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>242{243 fn drop(&mut self) {244 OnUnbalanced::on_unbalanced(Currency::issue(self.1));245 }246}247248parameter_types! {249 pub CheckingAccount: AccountId = PolkadotXcm::check_account();250}251/// Allow checking in assets that have issuance > 0.252#[cfg(feature = "foreign-assets")]253pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);254255#[cfg(feature = "foreign-assets")]256impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>257for NonZeroIssuance<AccountId, ForeingAssets>258 where259 ForeingAssets: fungibles::Inspect<AccountId>,260{261 fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {262 !ForeingAssets::total_issuance(*id).is_zero()263 }264}265266#[cfg(feature = "foreign-assets")]267pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);268#[cfg(feature = "foreign-assets")]269impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>270ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>271 where272 AssetId: Borrow<AssetId>,273 AssetId: TryAsForeing<AssetId, ForeignAssetId>,274 AssetIds: Borrow<AssetId>,275{276 fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {277 let id = id.borrow();278279 log::trace!(280 target: "xcm::AsInnerId::Convert",281 "AsInnerId {:?}",282 id283 );284285 let parent = MultiLocation::parent();286 let here = MultiLocation::here();287 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));288289 if *id == parent {290 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));291 }292293 if *id == here || *id == self_location {294 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));295 }296297 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {298 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {299 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))300 }301 _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),302 }303 }304305 fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {306 log::trace!(307 target: "xcm::AsInnerId::Reverse",308 "AsInnerId",309 );310311 let asset_id = what.borrow();312313 let parent_id =314 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();315 let here_id =316 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();317318 if asset_id.clone() == parent_id {319 return Ok(MultiLocation::parent());320 }321322 if asset_id.clone() == here_id {323 return Ok(MultiLocation::new(324 1,325 X1(Parachain(ParachainInfo::get().into())),326 ));327 }328329 match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {330 Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {331 Some(location) => Ok(location),332 None => Err(()),333 },334 None => Err(()),335 }336 }337}338339/// Means for transacting assets besides the native currency on this chain.340#[cfg(feature = "foreign-assets")]341pub type FungiblesTransactor = FungiblesAdapter<342 // Use this fungibles implementation:343 ForeingAssets,344 // Use this currency when it is a fungible asset matching the given location or name:345 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,346 // Convert an XCM MultiLocation into a local account id:347 LocationToAccountId,348 // Our chain's account ID type (we can't get away without mentioning it explicitly):349 AccountId,350 // We only want to allow teleports of known assets. We use non-zero issuance as an indication351 // that this asset is known.352 NonZeroIssuance<AccountId, ForeingAssets>,353 // The account to use for tracking teleports.354 CheckingAccount,355>;356357/// Means for transacting assets on this chain.358#[cfg(feature = "foreign-assets")]359pub type AssetTransactors = FungiblesTransactor;360361#[cfg(not(feature = "foreign-assets"))]362pub type AssetTransactors = LocalAssetTransactor;363364#[cfg(feature = "foreign-assets")]365pub struct AllAsset;366#[cfg(feature = "foreign-assets")]367impl FilterAssetLocation for AllAsset {368 fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {369 true370 }371}372373#[cfg(feature = "foreign-assets")]374pub type IsReserve = AllAsset;375#[cfg(not(feature = "foreign-assets"))]376pub type IsReserve = NativeAsset;377378#[cfg(feature = "foreign-assets")]379type Trader<T> =380 UsingAnyCurrencyComponents<381 pallet_configuration::WeightToFee<T, Balance>,382 RelayLocation, AccountId, Balances, ()>;383#[cfg(not(feature = "foreign-assets"))]384type Trader<T> = UsingOnlySelfCurrencyComponents<385 pallet_configuration::WeightToFee<T, Balance>,386 RelayLocation,387 AccountId,388 Balances,389 (),390>;391392pub struct XcmConfig<T>(PhantomData<T>);393impl<T> Config for XcmConfig<T>394where395 T: pallet_configuration::Config,396{397 type Call = Call;398 type XcmSender = XcmRouter;399 // How to withdraw and deposit an asset.400 type AssetTransactor = AssetTransactors;401 type OriginConverter = XcmOriginToTransactDispatchOrigin;402 type IsReserve = IsReserve;403 type IsTeleporter = (); // Teleportation is disabled404 type LocationInverter = LocationInverter<Ancestry>;405 type Barrier = Barrier;406 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;407 type Trader = Trader<T>;408 type ResponseHandler = (); // Don't handle responses for now.409 type SubscriptionService = PolkadotXcm;410411 type AssetTrap = PolkadotXcm;412 type AssetClaims = PolkadotXcm;413}414415impl pallet_xcm::Config for Runtime {416 type Event = Event;417 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;418 type XcmRouter = XcmRouter;419 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;420 type XcmExecuteFilter = Everything;421 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;422 type XcmTeleportFilter = Everything;423 type XcmReserveTransferFilter = Everything;424 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;425 type LocationInverter = LocationInverter<Ancestry>;426 type Origin = Origin;427 type Call = Call;428 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;429 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;430}431432impl cumulus_pallet_xcm::Config for Runtime {433 type Event = Event;434 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;435}436437impl cumulus_pallet_xcmp_queue::Config for Runtime {438 type WeightInfo = ();439 type Event = Event;440 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;441 type ChannelInfo = ParachainSystem;442 type VersionWrapper = ();443 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;444 type ControllerOrigin = EnsureRoot<AccountId>;445 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;446}447448impl cumulus_pallet_dmp_queue::Config for Runtime {449 type Event = Event;450 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;451 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;452}453runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -35,6 +35,8 @@
#[path = "../../common/mod.rs"]
mod runtime_common;
+pub mod xcm_config;
+
pub use runtime_common::*;
pub const RUNTIME_NAME: &str = "quartz";
runtime/quartz/src/xcm_config.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/quartz/src/xcm_config.rs
@@ -0,0 +1,109 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use cumulus_pallet_xcm;
+use frame_support::{
+ {match_types, parameter_types, weights::Weight},
+ pallet_prelude::Get,
+ traits::{Contains, Everything, fungibles},
+};
+use frame_system::EnsureRoot;
+use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key};
+use pallet_xcm::XcmPassthrough;
+use polkadot_parachain::primitives::Sibling;
+use sp_runtime::traits::{AccountIdConversion, CheckedConversion, Convert, Zero};
+use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};
+use xcm::{
+ latest::{MultiAsset, Xcm},
+ prelude::{Concrete, Fungible as XcmFungible},
+ v1::{BodyId, Junction::*, Junctions::*, MultiLocation, NetworkId},
+};
+use xcm_builder::{
+ AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
+ EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter, LocationInverter, ParentAsSuperuser,
+ ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
+ SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
+ ConvertedConcreteAssetId,
+};
+use xcm_executor::{
+ {Config, XcmExecutor},
+ traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible, ShouldExecute},
+};
+
+use up_common::{
+ constants::{MAXIMUM_BLOCK_WEIGHT, UNIQUE},
+ types::{AccountId, Balance},
+};
+
+use crate::{
+ Balances, Call, DmpQueue, Event, Origin, ParachainInfo,
+ ParachainSystem, PolkadotXcm, Runtime, XcmpQueue,
+};
+use crate::runtime_common::config::substrate::{TreasuryModuleId, MaxLocks, MaxReserves};
+use crate::runtime_common::config::pallets::TreasuryAccountId;
+use crate::runtime_common::config::xcm::*;
+use crate::*;
+
+// Signed version of balance
+pub type Amount = i128;
+
+match_types! {
+ pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = {
+ MultiLocation { parents: 1, interior: Here } |
+ MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) }
+ };
+ pub type ParentOrSiblings: impl Contains<MultiLocation> = {
+ MultiLocation { parents: 1, interior: Here } |
+ MultiLocation { parents: 1, interior: X1(_) }
+ };
+}
+
+/// Deny executing the XCM 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.
+pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)
+ where
+ Deny: ShouldExecute,
+ Allow: ShouldExecute;
+
+impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>
+ where
+ Deny: ShouldExecute,
+ Allow: ShouldExecute,
+{
+ fn should_execute<Call>(
+ origin: &MultiLocation,
+ message: &mut Xcm<Call>,
+ max_weight: Weight,
+ weight_credit: &mut Weight,
+ ) -> Result<(), ()> {
+ Deny::should_execute(origin, message, max_weight, weight_credit)?;
+ Allow::should_execute(origin, message, max_weight, weight_credit)
+ }
+}
+
+pub type Barrier = DenyThenTry<
+ DenyExchangeWithUnknownLocation,
+ (
+ TakeWeightCredit,
+ AllowTopLevelPaidExecutionFrom<Everything>,
+ // Parent and its exec plurality get free execution
+ AllowUnpaidExecutionFrom<ParentOrParentsExecutivePlurality>,
+ // Expected responses are OK.
+ AllowKnownQueryResponses<PolkadotXcm>,
+ // Subscriptions for version tracking are OK.
+ AllowSubscriptionsFrom<ParentOrSiblings>,
+ ),
+>;
\ No newline at end of file
runtime/unique/src/xcm_config.rsdiffbeforeafterbothno changes