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

difftreelog

source

runtime/common/config/xcm/mod.rs10.4 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, Nothing, Get, ConstU32},19	parameter_types,20};21use frame_system::EnsureRoot;22use pallet_xcm::XcmPassthrough;23use polkadot_parachain::primitives::Sibling;24use xcm::latest::{prelude::*, Weight, MultiLocation};25use xcm::v3::Instruction;26use xcm_builder::{27	AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, ParentAsSuperuser, RelayChainAsNative,28	SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,29	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, RelayNetwork, AllPalletsWithSystem, Balances,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 RelayOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();57	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();58	pub UniversalLocation: InteriorMultiLocation = Parachain(ParachainInfo::get().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 = Weight::from_parts(1_000_000, 1000); // ?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 [Instruction<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 [Instruction<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>(132		_origin: &MultiLocation,133		message: &mut [Instruction<Call>],134	) -> Result<(), ()> {135		let transact_inst = message136			.iter()137			.find(|inst| matches![inst, Instruction::Transact { .. }]);138139		if transact_inst.is_some() {140			log::warn!(141				target: "xcm::barrier",142				"transact XCM rejected"143			);144145			Err(())146		} else {147			Ok(())148		}149	}150}151152/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.153/// If it passes the Deny, and matches one of the Allow cases then it is let through.154pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)155where156	Deny: TryPass,157	Allow: ShouldExecute;158159impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>160where161	Deny: TryPass,162	Allow: ShouldExecute,163{164	fn should_execute<Call>(165		origin: &MultiLocation,166		message: &mut [Instruction<Call>],167		max_weight: Weight,168		weight_credit: &mut Weight,169	) -> Result<(), ()> {170		Deny::try_pass(origin, message)?;171		Allow::should_execute(origin, message, max_weight, weight_credit)172	}173}174175// Allow xcm exchange only with locations in list176pub struct DenyExchangeWithUnknownLocation<T>(PhantomData<T>);177impl<T: Get<Vec<MultiLocation>>> TryPass for DenyExchangeWithUnknownLocation<T> {178	fn try_pass<Call>(origin: &MultiLocation, message: &mut [Instruction<Call>]) -> Result<(), ()> {179		let allowed_locations = T::get();180181		// Check if deposit or transfer belongs to allowed parachains182		let mut allowed = allowed_locations.contains(origin);183184		message.iter().for_each(|inst| match inst {185			DepositReserveAsset { dest: dst, .. }186			| TransferReserveAsset { dest: dst, .. }187			| InitiateReserveWithdraw { reserve: dst, .. } => {188				allowed |= allowed_locations.contains(&dst);189			}190			// ? There are more instructions worth checking191			_ => {}192		});193194		if allowed {195			return Ok(());196		}197198		log::warn!(199			target: "xcm::barrier",200			"Unexpected deposit or transfer location"201		);202		// Deny203		Err(())204	}205}206207pub type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;208209pub struct XcmConfig<T>(PhantomData<T>);210impl<T> Config for XcmConfig<T>211where212	T: pallet_configuration::Config,213{214	type RuntimeCall = RuntimeCall;215	type XcmSender = XcmRouter;216	// How to withdraw and deposit an asset.217	type AssetTransactor = AssetTransactors;218	type OriginConverter = XcmOriginToTransactDispatchOrigin;219	type IsReserve = IsReserve;220	type IsTeleporter = (); // Teleportation is disabled221	type UniversalLocation = UniversalLocation;222	type Barrier = Barrier;223	type Weigher = Weigher;224	type Trader = Trader<T>;225	type ResponseHandler = PolkadotXcm;226	type SubscriptionService = PolkadotXcm;227	type PalletInstancesInfo = AllPalletsWithSystem;228	type MaxAssetsIntoHolding = ConstU32<64>;229230	type AssetTrap = PolkadotXcm;231	type AssetClaims = PolkadotXcm;232	type AssetLocker = ();233	type AssetExchanger = ();234	type FeeManager = ();235	type MessageExporter = ();236	type UniversalAliases = Nothing; // ?237	type CallDispatcher = RuntimeCall;238	type SafeCallFilter = Nothing; // ? Only non-recursive calls may go here, but do we need this?239}240241#[cfg(feature = "runtime-benchmarks")]242parameter_types! {243	pub ReachableDest: Option<MultiLocation> = Some(Parent.into());244}245246impl pallet_xcm::Config for Runtime {247	type RuntimeEvent = RuntimeEvent;248	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;249	type XcmRouter = XcmRouter;250	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;251	type XcmExecuteFilter = Everything;252	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;253	type XcmTeleportFilter = Everything;254	type XcmReserveTransferFilter = Everything;255	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;256	type RuntimeOrigin = RuntimeOrigin;257	type RuntimeCall = RuntimeCall;258	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;259	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;260	type UniversalLocation = UniversalLocation;261	type Currency = Balances;262	type CurrencyMatcher = (); // ?263	type TrustedLockers = ();264	type SovereignAccountOf = ();265	type MaxLockers = ConstU32<8>;266	type WeightInfo = crate::weights::xcm::SubstrateWeight<Runtime>;267	#[cfg(feature = "runtime-benchmarks")]268	type ReachableDest = ReachableDest;269}270271impl cumulus_pallet_xcm::Config for Runtime {272	type RuntimeEvent = RuntimeEvent;273	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;274}275276impl cumulus_pallet_xcmp_queue::Config for Runtime {277	type WeightInfo = ();278	type RuntimeEvent = RuntimeEvent;279	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;280	type ChannelInfo = ParachainSystem;281	type VersionWrapper = ();282	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;283	type ControllerOrigin = EnsureRoot<AccountId>;284	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;285	type PriceForSiblingDelivery = ();286}287288impl cumulus_pallet_dmp_queue::Config for Runtime {289	type RuntimeEvent = RuntimeEvent;290	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;291	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;292}