difftreelog
feat(xcm) move DenyThenTry to common, add DenyTransact
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,20 Everything, 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,41 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,42 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,43 ParentIsPreset, ConvertedConcreteAssetId,44};45use xcm_executor::{Config, XcmExecutor, Assets};46use xcm_executor::traits::{47 Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation,48};49use pallet_foreing_assets::{50 AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency, FreeForAll,51 TryAsForeing, ForeignAssetId,52};53use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};54use crate::{55 Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,56 xcm_config::Barrier,57};58#[cfg(feature = "foreign-assets")]59use crate::ForeingAssets;6061use up_common::{62 types::{AccountId, Balance},63 constants::*,64};6566parameter_types! {67 pub const RelayLocation: MultiLocation = MultiLocation::parent();68 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;69 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();70 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();71}7273/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used74/// when determining ownership of accounts for asset transacting and when attempting to use XCM75/// `Transact` in order to determine the dispatch Origin.76pub type LocationToAccountId = (77 // The parent (Relay-chain) origin converts to the default `AccountId`.78 ParentIsPreset<AccountId>,79 // Sibling parachain origins convert to AccountId via the `ParaId::into`.80 SiblingParachainConvertsVia<Sibling, AccountId>,81 // Straight up local `AccountId32` origins just alias directly to `AccountId`.82 AccountId32Aliases<RelayNetwork, AccountId>,83);8485pub struct OnlySelfCurrency;86impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {87 fn matches_fungible(a: &MultiAsset) -> Option<B> {88 let paraid = Parachain(ParachainInfo::parachain_id().into());89 match (&a.id, &a.fun) {90 (91 Concrete(MultiLocation {92 parents: 1,93 interior: X1(loc),94 }),95 XcmFungible(ref amount),96 ) if paraid == *loc => CheckedConversion::checked_from(*amount),97 (98 Concrete(MultiLocation {99 parents: 0,100 interior: Here,101 }),102 XcmFungible(ref amount),103 ) => CheckedConversion::checked_from(*amount),104 _ => None,105 }106 }107}108109/// Means for transacting assets on this chain.110pub type LocalAssetTransactor = CurrencyAdapter<111 // Use this currency:112 Balances,113 // Use this currency when it is a fungible asset matching the given location or name:114 OnlySelfCurrency,115 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:116 LocationToAccountId,117 // Our chain's account ID type (we can't get away without mentioning it explicitly):118 AccountId,119 // We don't track any teleports.120 (),121>;122123/// No local origins on this chain are allowed to dispatch XCM sends/executions.124pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);125126/// The means for routing XCM messages which are not for local execution into the right message127/// queues.128pub type XcmRouter = (129 // Two routers - use UMP to communicate with the relay chain:130 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,131 // ..and XCMP to communicate with the sibling chains.132 XcmpQueue,133);134135/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,136/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can137/// biases the kind of local `Origin` it will become.138pub type XcmOriginToTransactDispatchOrigin = (139 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location140 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for141 // foreign chains who want to have a local sovereign account on this chain which they control.142 SovereignSignedViaLocation<LocationToAccountId, Origin>,143 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when144 // recognised.145 RelayChainAsNative<RelayOrigin, Origin>,146 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when147 // recognised.148 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,149 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a150 // transaction from the Root origin.151 ParentAsSuperuser<Origin>,152 // Native signed account converter; this just converts an `AccountId32` origin into a normal153 // `Origin::Signed` origin of the same 32-byte value.154 SignedAccountId32AsNative<RelayNetwork, Origin>,155 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.156 XcmPassthrough<Origin>,157);158159parameter_types! {160 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.161 pub UnitWeightCost: Weight = 1_000_000;162 // 1200 UNIQUEs buy 1 second of weight.163 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);164 pub const MaxInstructions: u32 = 100;165}166167match_types! {168 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {169 MultiLocation { parents: 1, interior: Here } |170 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }171 };172}173174/*175pub type Barrier = (176 TakeWeightCredit,177 AllowTopLevelPaidExecutionFrom<Everything>,178 // ^^^ Parent & its unit plurality gets free execution179);180 */181182pub struct UsingOnlySelfCurrencyComponents<183 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,184 AssetId: Get<MultiLocation>,185 AccountId,186 Currency: CurrencyT<AccountId>,187 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,188>(189 Weight,190 Currency::Balance,191 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,192);193impl<194 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,195 AssetId: Get<MultiLocation>,196 AccountId,197 Currency: CurrencyT<AccountId>,198 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,199 > WeightTrader200 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>201{202 fn new() -> Self {203 Self(0, Zero::zero(), PhantomData)204 }205206 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {207 Ok(payment)208 }209}210impl<211 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,212 AssetId: Get<MultiLocation>,213 AccountId,214 Currency: CurrencyT<AccountId>,215 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,216 > Drop217 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>218{219 fn drop(&mut self) {220 OnUnbalanced::on_unbalanced(Currency::issue(self.1));221 }222}223224parameter_types! {225 pub CheckingAccount: AccountId = PolkadotXcm::check_account();226}227/// Allow checking in assets that have issuance > 0.228#[cfg(feature = "foreign-assets")]229pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);230231#[cfg(feature = "foreign-assets")]232impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>233 for NonZeroIssuance<AccountId, ForeingAssets>234where235 ForeingAssets: fungibles::Inspect<AccountId>,236{237 fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {238 !ForeingAssets::total_issuance(*id).is_zero()239 }240}241242#[cfg(feature = "foreign-assets")]243pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);244#[cfg(feature = "foreign-assets")]245impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>246 ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>247where248 AssetId: Borrow<AssetId>,249 AssetId: TryAsForeing<AssetId, ForeignAssetId>,250 AssetIds: Borrow<AssetId>,251{252 fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {253 let id = id.borrow();254255 log::trace!(256 target: "xcm::AsInnerId::Convert",257 "AsInnerId {:?}",258 id259 );260261 let parent = MultiLocation::parent();262 let here = MultiLocation::here();263 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));264265 if *id == parent {266 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));267 }268269 if *id == here || *id == self_location {270 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));271 }272273 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {274 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {275 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))276 }277 _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),278 }279 }280281 fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {282 log::trace!(283 target: "xcm::AsInnerId::Reverse",284 "AsInnerId",285 );286287 let asset_id = what.borrow();288289 let parent_id =290 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();291 let here_id =292 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();293294 if asset_id.clone() == parent_id {295 return Ok(MultiLocation::parent());296 }297298 if asset_id.clone() == here_id {299 return Ok(MultiLocation::new(300 1,301 X1(Parachain(ParachainInfo::get().into())),302 ));303 }304305 match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {306 Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {307 Some(location) => Ok(location),308 None => Err(()),309 },310 None => Err(()),311 }312 }313}314315/// Means for transacting assets besides the native currency on this chain.316#[cfg(feature = "foreign-assets")]317pub type FungiblesTransactor = FungiblesAdapter<318 // Use this fungibles implementation:319 ForeingAssets,320 // Use this currency when it is a fungible asset matching the given location or name:321 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,322 // Convert an XCM MultiLocation into a local account id:323 LocationToAccountId,324 // Our chain's account ID type (we can't get away without mentioning it explicitly):325 AccountId,326 // We only want to allow teleports of known assets. We use non-zero issuance as an indication327 // that this asset is known.328 NonZeroIssuance<AccountId, ForeingAssets>,329 // The account to use for tracking teleports.330 CheckingAccount,331>;332333/// Means for transacting assets on this chain.334#[cfg(feature = "foreign-assets")]335pub type AssetTransactors = FungiblesTransactor;336337#[cfg(not(feature = "foreign-assets"))]338pub type AssetTransactors = LocalAssetTransactor;339340#[cfg(feature = "foreign-assets")]341pub struct AllAsset;342#[cfg(feature = "foreign-assets")]343impl FilterAssetLocation for AllAsset {344 fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {345 true346 }347}348349#[cfg(feature = "foreign-assets")]350pub type IsReserve = AllAsset;351#[cfg(not(feature = "foreign-assets"))]352pub type IsReserve = NativeAsset;353354#[cfg(feature = "foreign-assets")]355type Trader<T> = FreeForAll<356 pallet_configuration::WeightToFee<T, Balance>,357 RelayLocation,358 AccountId,359 Balances,360 (),361>;362#[cfg(not(feature = "foreign-assets"))]363type Trader<T> = UsingOnlySelfCurrencyComponents<364 pallet_configuration::WeightToFee<T, Balance>,365 RelayLocation,366 AccountId,367 Balances,368 (),369>;370371pub struct XcmConfig<T>(PhantomData<T>);372impl<T> Config for XcmConfig<T>373where374 T: pallet_configuration::Config,375{376 type Call = Call;377 type XcmSender = XcmRouter;378 // How to withdraw and deposit an asset.379 type AssetTransactor = AssetTransactors;380 type OriginConverter = XcmOriginToTransactDispatchOrigin;381 type IsReserve = IsReserve;382 type IsTeleporter = (); // Teleportation is disabled383 type LocationInverter = LocationInverter<Ancestry>;384 type Barrier = Barrier;385 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;386 type Trader = Trader<T>;387 type ResponseHandler = (); // Don't handle responses for now.388 type SubscriptionService = PolkadotXcm;389390 type AssetTrap = PolkadotXcm;391 type AssetClaims = PolkadotXcm;392}393394impl pallet_xcm::Config for Runtime {395 type Event = Event;396 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;397 type XcmRouter = XcmRouter;398 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;399 type XcmExecuteFilter = Everything;400 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;401 type XcmTeleportFilter = Everything;402 type XcmReserveTransferFilter = Everything;403 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;404 type LocationInverter = LocationInverter<Ancestry>;405 type Origin = Origin;406 type Call = Call;407 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;408 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;409}410411impl cumulus_pallet_xcm::Config for Runtime {412 type Event = Event;413 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;414}415416impl cumulus_pallet_xcmp_queue::Config for Runtime {417 type WeightInfo = ();418 type Event = Event;419 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;420 type ChannelInfo = ParachainSystem;421 type VersionWrapper = ();422 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;423 type ControllerOrigin = EnsureRoot<AccountId>;424 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;425}426427impl cumulus_pallet_dmp_queue::Config for Runtime {428 type Event = Event;429 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;430 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;431}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 frame_support::{18 traits::{19 Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get,20 Everything, 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 Instruction, Xcm,38};39use xcm_builder::{40 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,41 FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser,42 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,43 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,44 ParentIsPreset, ConvertedConcreteAssetId,45};46use xcm_executor::{Config, XcmExecutor, Assets};47use xcm_executor::traits::{48 Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation,49 ShouldExecute,50};51use pallet_foreing_assets::{52 AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency, FreeForAll,53 TryAsForeing, ForeignAssetId,54};55use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};56use crate::{57 Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,58 xcm_config::Barrier,59};60#[cfg(feature = "foreign-assets")]61use crate::ForeingAssets;6263use up_common::{64 types::{AccountId, Balance},65 constants::*,66};6768parameter_types! {69 pub const RelayLocation: MultiLocation = MultiLocation::parent();70 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;71 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();72 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();73}7475/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used76/// when determining ownership of accounts for asset transacting and when attempting to use XCM77/// `Transact` in order to determine the dispatch Origin.78pub type LocationToAccountId = (79 // The parent (Relay-chain) origin converts to the default `AccountId`.80 ParentIsPreset<AccountId>,81 // Sibling parachain origins convert to AccountId via the `ParaId::into`.82 SiblingParachainConvertsVia<Sibling, AccountId>,83 // Straight up local `AccountId32` origins just alias directly to `AccountId`.84 AccountId32Aliases<RelayNetwork, AccountId>,85);8687pub struct OnlySelfCurrency;88impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {89 fn matches_fungible(a: &MultiAsset) -> Option<B> {90 let paraid = Parachain(ParachainInfo::parachain_id().into());91 match (&a.id, &a.fun) {92 (93 Concrete(MultiLocation {94 parents: 1,95 interior: X1(loc),96 }),97 XcmFungible(ref amount),98 ) if paraid == *loc => CheckedConversion::checked_from(*amount),99 (100 Concrete(MultiLocation {101 parents: 0,102 interior: Here,103 }),104 XcmFungible(ref amount),105 ) => CheckedConversion::checked_from(*amount),106 _ => None,107 }108 }109}110111/// Means for transacting assets on this chain.112pub type LocalAssetTransactor = CurrencyAdapter<113 // Use this currency:114 Balances,115 // Use this currency when it is a fungible asset matching the given location or name:116 OnlySelfCurrency,117 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:118 LocationToAccountId,119 // Our chain's account ID type (we can't get away without mentioning it explicitly):120 AccountId,121 // We don't track any teleports.122 (),123>;124125/// No local origins on this chain are allowed to dispatch XCM sends/executions.126pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);127128/// The means for routing XCM messages which are not for local execution into the right message129/// queues.130pub type XcmRouter = (131 // Two routers - use UMP to communicate with the relay chain:132 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,133 // ..and XCMP to communicate with the sibling chains.134 XcmpQueue,135);136137/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,138/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can139/// biases the kind of local `Origin` it will become.140pub type XcmOriginToTransactDispatchOrigin = (141 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location142 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for143 // foreign chains who want to have a local sovereign account on this chain which they control.144 SovereignSignedViaLocation<LocationToAccountId, Origin>,145 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when146 // recognised.147 RelayChainAsNative<RelayOrigin, Origin>,148 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when149 // recognised.150 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,151 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a152 // transaction from the Root origin.153 ParentAsSuperuser<Origin>,154 // Native signed account converter; this just converts an `AccountId32` origin into a normal155 // `Origin::Signed` origin of the same 32-byte value.156 SignedAccountId32AsNative<RelayNetwork, Origin>,157 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.158 XcmPassthrough<Origin>,159);160161parameter_types! {162 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.163 pub UnitWeightCost: Weight = 1_000_000;164 // 1200 UNIQUEs buy 1 second of weight.165 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);166 pub const MaxInstructions: u32 = 100;167}168169match_types! {170 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {171 MultiLocation { parents: 1, interior: Here } |172 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }173 };174}175176pub struct DenyTransact;177impl ShouldExecute for DenyTransact {178 fn should_execute<Call>(179 _origin: &MultiLocation,180 message: &mut Xcm<Call>,181 _max_weight: Weight,182 _weight_credit: &mut Weight,183 ) -> Result<(), ()> {184 let transact_inst = message.0.iter()185 .find(|inst| matches![inst, Instruction::Transact { .. }]);186187 match transact_inst {188 Some(_) => {189 log::warn!(190 target: "xcm::barrier",191 "transact XCM rejected"192 );193194 Err(())195 },196 None => Ok(())197 }198 }199}200201/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.202/// If it passes the Deny, and matches one of the Allow cases then it is let through.203pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)204 where205 Deny: ShouldExecute,206 Allow: ShouldExecute;207208impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>209 where210 Deny: ShouldExecute,211 Allow: ShouldExecute,212{213 fn should_execute<Call>(214 origin: &MultiLocation,215 message: &mut Xcm<Call>,216 max_weight: Weight,217 weight_credit: &mut Weight,218 ) -> Result<(), ()> {219 Deny::should_execute(origin, message, max_weight, weight_credit)?;220 Allow::should_execute(origin, message, max_weight, weight_credit)221 }222}223224pub struct UsingOnlySelfCurrencyComponents<225 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,226 AssetId: Get<MultiLocation>,227 AccountId,228 Currency: CurrencyT<AccountId>,229 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,230>(231 Weight,232 Currency::Balance,233 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,234);235impl<236 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,237 AssetId: Get<MultiLocation>,238 AccountId,239 Currency: CurrencyT<AccountId>,240 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,241 > WeightTrader242 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>243{244 fn new() -> Self {245 Self(0, Zero::zero(), PhantomData)246 }247248 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {249 Ok(payment)250 }251}252impl<253 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,254 AssetId: Get<MultiLocation>,255 AccountId,256 Currency: CurrencyT<AccountId>,257 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,258 > Drop259 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>260{261 fn drop(&mut self) {262 OnUnbalanced::on_unbalanced(Currency::issue(self.1));263 }264}265266parameter_types! {267 pub CheckingAccount: AccountId = PolkadotXcm::check_account();268}269/// Allow checking in assets that have issuance > 0.270#[cfg(feature = "foreign-assets")]271pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);272273#[cfg(feature = "foreign-assets")]274impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>275 for NonZeroIssuance<AccountId, ForeingAssets>276where277 ForeingAssets: fungibles::Inspect<AccountId>,278{279 fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {280 !ForeingAssets::total_issuance(*id).is_zero()281 }282}283284#[cfg(feature = "foreign-assets")]285pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);286#[cfg(feature = "foreign-assets")]287impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>288 ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>289where290 AssetId: Borrow<AssetId>,291 AssetId: TryAsForeing<AssetId, ForeignAssetId>,292 AssetIds: Borrow<AssetId>,293{294 fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {295 let id = id.borrow();296297 log::trace!(298 target: "xcm::AsInnerId::Convert",299 "AsInnerId {:?}",300 id301 );302303 let parent = MultiLocation::parent();304 let here = MultiLocation::here();305 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));306307 if *id == parent {308 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));309 }310311 if *id == here || *id == self_location {312 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));313 }314315 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {316 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {317 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))318 }319 _ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),320 }321 }322323 fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {324 log::trace!(325 target: "xcm::AsInnerId::Reverse",326 "AsInnerId",327 );328329 let asset_id = what.borrow();330331 let parent_id =332 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();333 let here_id =334 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();335336 if asset_id.clone() == parent_id {337 return Ok(MultiLocation::parent());338 }339340 if asset_id.clone() == here_id {341 return Ok(MultiLocation::new(342 1,343 X1(Parachain(ParachainInfo::get().into())),344 ));345 }346347 match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {348 Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {349 Some(location) => Ok(location),350 None => Err(()),351 },352 None => Err(()),353 }354 }355}356357/// Means for transacting assets besides the native currency on this chain.358#[cfg(feature = "foreign-assets")]359pub type FungiblesTransactor = FungiblesAdapter<360 // Use this fungibles implementation:361 ForeingAssets,362 // Use this currency when it is a fungible asset matching the given location or name:363 ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,364 // Convert an XCM MultiLocation into a local account id:365 LocationToAccountId,366 // Our chain's account ID type (we can't get away without mentioning it explicitly):367 AccountId,368 // We only want to allow teleports of known assets. We use non-zero issuance as an indication369 // that this asset is known.370 NonZeroIssuance<AccountId, ForeingAssets>,371 // The account to use for tracking teleports.372 CheckingAccount,373>;374375/// Means for transacting assets on this chain.376#[cfg(feature = "foreign-assets")]377pub type AssetTransactors = FungiblesTransactor;378379#[cfg(not(feature = "foreign-assets"))]380pub type AssetTransactors = LocalAssetTransactor;381382#[cfg(feature = "foreign-assets")]383pub struct AllAsset;384#[cfg(feature = "foreign-assets")]385impl FilterAssetLocation for AllAsset {386 fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {387 true388 }389}390391#[cfg(feature = "foreign-assets")]392pub type IsReserve = AllAsset;393#[cfg(not(feature = "foreign-assets"))]394pub type IsReserve = NativeAsset;395396#[cfg(feature = "foreign-assets")]397type Trader<T> = FreeForAll<398 pallet_configuration::WeightToFee<T, Balance>,399 RelayLocation,400 AccountId,401 Balances,402 (),403>;404#[cfg(not(feature = "foreign-assets"))]405type Trader<T> = UsingOnlySelfCurrencyComponents<406 pallet_configuration::WeightToFee<T, Balance>,407 RelayLocation,408 AccountId,409 Balances,410 (),411>;412413pub struct XcmConfig<T>(PhantomData<T>);414impl<T> Config for XcmConfig<T>415where416 T: pallet_configuration::Config,417{418 type Call = Call;419 type XcmSender = XcmRouter;420 // How to withdraw and deposit an asset.421 type AssetTransactor = AssetTransactors;422 type OriginConverter = XcmOriginToTransactDispatchOrigin;423 type IsReserve = IsReserve;424 type IsTeleporter = (); // Teleportation is disabled425 type LocationInverter = LocationInverter<Ancestry>;426 type Barrier = Barrier;427 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;428 type Trader = Trader<T>;429 type ResponseHandler = (); // Don't handle responses for now.430 type SubscriptionService = PolkadotXcm;431432 type AssetTrap = PolkadotXcm;433 type AssetClaims = PolkadotXcm;434}435436impl pallet_xcm::Config for Runtime {437 type Event = Event;438 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;439 type XcmRouter = XcmRouter;440 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;441 type XcmExecuteFilter = Everything;442 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;443 type XcmTeleportFilter = Everything;444 type XcmReserveTransferFilter = Everything;445 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;446 type LocationInverter = LocationInverter<Ancestry>;447 type Origin = Origin;448 type Call = Call;449 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;450 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;451}452453impl cumulus_pallet_xcm::Config for Runtime {454 type Event = Event;455 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;456}457458impl cumulus_pallet_xcmp_queue::Config for Runtime {459 type WeightInfo = ();460 type Event = Event;461 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;462 type ChannelInfo = ParachainSystem;463 type VersionWrapper = ();464 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;465 type ControllerOrigin = EnsureRoot<AccountId>;466 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;467}468469impl cumulus_pallet_dmp_queue::Config for Runtime {470 type Event = Event;471 type XcmExecutor = XcmExecutor<XcmConfig<Self>>;472 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;473}runtime/opal/src/xcm_config.rsdiffbeforeafterboth--- a/runtime/opal/src/xcm_config.rs
+++ b/runtime/opal/src/xcm_config.rs
@@ -301,13 +301,16 @@
}
}
-pub type Barrier = (
- TakeWeightCredit,
- AllowTopLevelPaidExecutionFrom<Everything>,
- AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,
- // ^^^ Parent & its unit plurality gets free execution
- AllowAllDebug,
-);
+pub type Barrier = DenyThenTry<
+ DenyTransact,
+ (
+ TakeWeightCredit,
+ AllowTopLevelPaidExecutionFrom<Everything>,
+ AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,
+ // ^^^ Parent & its unit plurality gets free execution
+ AllowAllDebug,
+ )
+>;
pub struct AllAsset;
impl FilterAssetLocation for AllAsset {
runtime/quartz/src/xcm_config.rsdiffbeforeafterboth--- a/runtime/quartz/src/xcm_config.rs
+++ b/runtime/quartz/src/xcm_config.rs
@@ -76,29 +76,6 @@
};
}
-/// 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 fn get_allowed_locations() -> Vec<MultiLocation> {
vec![
// Self location
@@ -151,6 +128,7 @@
pub type Barrier = DenyThenTry<
DenyExchangeWithUnknownLocation,
(
+ DenyTransact,
TakeWeightCredit,
AllowTopLevelPaidExecutionFrom<Everything>,
// Parent and its exec plurality get free execution
runtime/unique/src/xcm_config.rsdiffbeforeafterboth--- a/runtime/unique/src/xcm_config.rs
+++ b/runtime/unique/src/xcm_config.rs
@@ -69,6 +69,7 @@
pub type Barrier = DenyThenTry<
DenyExchangeWithUnknownLocation,
(
+ DenyTransact,
TakeWeightCredit,
AllowTopLevelPaidExecutionFrom<Everything>,
// Parent and its exec plurality get free execution
@@ -93,27 +94,6 @@
// Self parachain address
MultiLocation { parents: 1, interior: X1(Parachain(ParachainInfo::get().into())) },
]
-}
-
-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)
- }
}
// Allow xcm exchange only with locations in list