git.delta.rocks / unique-network / refs/commits / 3c77c1e2ea04

difftreelog

source

runtime/common/config/xcm/mod.rs9.6 KiBsourcehistory
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::{Everything, Get},19	parameter_types,20};21use frame_system::EnsureRoot;22use pallet_xcm::XcmPassthrough;23use polkadot_parachain::primitives::Sibling;24use xcm::v1::{Junction::*, MultiLocation, NetworkId};25use xcm::latest::{prelude::*, Weight};26use xcm_builder::{27	AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, LocationInverter, ParentAsSuperuser,28	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,29	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, ParentIsPreset,30};31use xcm_executor::{Config, XcmExecutor, traits::ShouldExecute};32use sp_std::{marker::PhantomData, vec::Vec};33use crate::{34	Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, ParachainInfo, ParachainSystem, PolkadotXcm,35	XcmpQueue, xcm_barrier::Barrier,36};3738use up_common::types::AccountId;3940#[cfg(feature = "foreign-assets")]41pub mod foreignassets;4243#[cfg(not(feature = "foreign-assets"))]44pub mod nativeassets;4546#[cfg(feature = "foreign-assets")]47pub use foreignassets as xcm_assets;4849#[cfg(not(feature = "foreign-assets"))]50pub use nativeassets as xcm_assets;5152use xcm_assets::{AssetTransactors, IsReserve, Trader};5354parameter_types! {55	pub const RelayLocation: MultiLocation = MultiLocation::parent();56	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;57	pub RelayOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();58	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();59	pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));6061	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.62	pub UnitWeightCost: Weight = 1_000_000;63	pub const MaxInstructions: u32 = 100;64}6566/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used67/// when determining ownership of accounts for asset transacting and when attempting to use XCM68/// `Transact` in order to determine the dispatch Origin.69pub type LocationToAccountId = (70	// The parent (Relay-chain) origin converts to the default `AccountId`.71	ParentIsPreset<AccountId>,72	// Sibling parachain origins convert to AccountId via the `ParaId::into`.73	SiblingParachainConvertsVia<Sibling, AccountId>,74	// Straight up local `AccountId32` origins just alias directly to `AccountId`.75	AccountId32Aliases<RelayNetwork, AccountId>,76);7778/// No local origins on this chain are allowed to dispatch XCM sends/executions.79pub type LocalOriginToLocation = (SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>,);8081/// The means for routing XCM messages which are not for local execution into the right message82/// queues.83pub type XcmRouter = (84	// Two routers - use UMP to communicate with the relay chain:85	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,86	// ..and XCMP to communicate with the sibling chains.87	XcmpQueue,88);8990/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,91/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can92/// biases the kind of local `Origin` it will become.93pub type XcmOriginToTransactDispatchOrigin = (94	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location95	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for96	// foreign chains who want to have a local sovereign account on this chain which they control.97	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,98	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when99	// recognised.100	RelayChainAsNative<RelayOrigin, RuntimeOrigin>,101	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when102	// recognised.103	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,104	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a105	// transaction from the Root origin.106	ParentAsSuperuser<RuntimeOrigin>,107	// Native signed account converter; this just converts an `AccountId32` origin into a normal108	// `Origin::Signed` origin of the same 32-byte value.109	SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,110	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.111	XcmPassthrough<RuntimeOrigin>,112);113114pub trait TryPass {115	fn try_pass<Call>(origin: &MultiLocation, message: &mut Xcm<Call>) -> Result<(), ()>;116}117118#[impl_trait_for_tuples::impl_for_tuples(30)]119impl TryPass for Tuple {120	fn try_pass<Call>(origin: &MultiLocation, message: &mut Xcm<Call>) -> Result<(), ()> {121		for_tuples!( #(122			Tuple::try_pass(origin, message)?;123		)* );124125		Ok(())126	}127}128129pub struct DenyTransact;130impl TryPass for DenyTransact {131	fn try_pass<Call>(_origin: &MultiLocation, message: &mut Xcm<Call>) -> Result<(), ()> {132		let transact_inst = message133			.0134			.iter()135			.find(|inst| matches![inst, Instruction::Transact { .. }]);136137		if transact_inst.is_some() {138			log::warn!(139				target: "xcm::barrier",140				"transact XCM rejected"141			);142143			Err(())144		} else {145			Ok(())146		}147	}148}149150/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.151/// If it passes the Deny, and matches one of the Allow cases then it is let through.152pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)153where154	Deny: TryPass,155	Allow: ShouldExecute;156157impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>158where159	Deny: TryPass,160	Allow: ShouldExecute,161{162	fn should_execute<Call>(163		origin: &MultiLocation,164		message: &mut Xcm<Call>,165		max_weight: Weight,166		weight_credit: &mut Weight,167	) -> Result<(), ()> {168		Deny::try_pass(origin, message)?;169		Allow::should_execute(origin, message, max_weight, weight_credit)170	}171}172173// Allow xcm exchange only with locations in list174pub struct DenyExchangeWithUnknownLocation<T>(PhantomData<T>);175impl<T: Get<Vec<MultiLocation>>> TryPass for DenyExchangeWithUnknownLocation<T> {176	fn try_pass<Call>(origin: &MultiLocation, message: &mut Xcm<Call>) -> Result<(), ()> {177		let allowed_locations = T::get();178179		// Check if deposit or transfer belongs to allowed parachains180		let mut allowed = allowed_locations.contains(origin);181182		message.0.iter().for_each(|inst| match inst {183			DepositReserveAsset { dest: dst, .. } => {184				allowed |= allowed_locations.contains(dst);185			}186			TransferReserveAsset { dest: dst, .. } => {187				allowed |= allowed_locations.contains(dst);188			}189			InitiateReserveWithdraw { reserve: dst, .. } => {190				allowed |= allowed_locations.contains(dst);191			}192			_ => {}193		});194195		if allowed {196			return Ok(());197		}198199		log::warn!(200			target: "xcm::barrier",201			"Unexpected deposit or transfer location"202		);203		// Deny204		Err(())205	}206}207208pub type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;209210pub struct XcmConfig<T>(PhantomData<T>);211impl<T> Config for XcmConfig<T>212where213	T: pallet_configuration::Config,214{215	type RuntimeCall = RuntimeCall;216	type XcmSender = XcmRouter;217	// How to withdraw and deposit an asset.218	type AssetTransactor = AssetTransactors;219	type OriginConverter = XcmOriginToTransactDispatchOrigin;220	type IsReserve = IsReserve;221	type IsTeleporter = (); // Teleportation is disabled222	type LocationInverter = LocationInverter<Ancestry>;223	type Barrier = Barrier;224	type Weigher = Weigher;225	type Trader = Trader<T>;226	type ResponseHandler = (); // Don't handle responses for now.227	type SubscriptionService = PolkadotXcm;228229	type AssetTrap = PolkadotXcm;230	type AssetClaims = PolkadotXcm;231}232233impl pallet_xcm::Config for Runtime {234	type RuntimeEvent = RuntimeEvent;235	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;236	type XcmRouter = XcmRouter;237	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;238	type XcmExecuteFilter = Everything;239	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;240	type XcmTeleportFilter = Everything;241	type XcmReserveTransferFilter = Everything;242	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;243	type LocationInverter = LocationInverter<Ancestry>;244	type RuntimeOrigin = RuntimeOrigin;245	type RuntimeCall = RuntimeCall;246	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;247	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;248}249250impl cumulus_pallet_xcm::Config for Runtime {251	type RuntimeEvent = RuntimeEvent;252	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;253}254255impl cumulus_pallet_xcmp_queue::Config for Runtime {256	type WeightInfo = ();257	type RuntimeEvent = RuntimeEvent;258	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;259	type ChannelInfo = ParachainSystem;260	type VersionWrapper = ();261	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;262	type ControllerOrigin = EnsureRoot<AccountId>;263	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;264}265266impl cumulus_pallet_dmp_queue::Config for Runtime {267	type RuntimeEvent = RuntimeEvent;268	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;269	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;270}