git.delta.rocks / unique-network / refs/commits / 5667e2a82ef1

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 UniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::get().into()));58	pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));5960	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.61	pub UnitWeightCost: Weight = Weight::from_parts(1_000_000, 1000); // ?62	pub const MaxInstructions: u32 = 100;63}6465/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used66/// when determining ownership of accounts for asset transacting and when attempting to use XCM67/// `Transact` in order to determine the dispatch Origin.68pub type LocationToAccountId = (69	// The parent (Relay-chain) origin converts to the default `AccountId`.70	ParentIsPreset<AccountId>,71	// Sibling parachain origins convert to AccountId via the `ParaId::into`.72	SiblingParachainConvertsVia<Sibling, AccountId>,73	// Straight up local `AccountId32` origins just alias directly to `AccountId`.74	AccountId32Aliases<RelayNetwork, AccountId>,75);7677/// No local origins on this chain are allowed to dispatch XCM sends/executions.78pub type LocalOriginToLocation = (SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>,);7980/// The means for routing XCM messages which are not for local execution into the right message81/// queues.82pub type XcmRouter = (83	// Two routers - use UMP to communicate with the relay chain:84	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,85	// ..and XCMP to communicate with the sibling chains.86	XcmpQueue,87);8889/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,90/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can91/// biases the kind of local `Origin` it will become.92pub type XcmOriginToTransactDispatchOrigin = (93	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location94	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for95	// foreign chains who want to have a local sovereign account on this chain which they control.96	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,97	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when98	// recognised.99	RelayChainAsNative<RelayOrigin, RuntimeOrigin>,100	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when101	// recognised.102	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,103	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a104	// transaction from the Root origin.105	ParentAsSuperuser<RuntimeOrigin>,106	// Native signed account converter; this just converts an `AccountId32` origin into a normal107	// `Origin::Signed` origin of the same 32-byte value.108	SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,109	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.110	XcmPassthrough<RuntimeOrigin>,111);112113pub trait TryPass {114	fn try_pass<Call>(origin: &MultiLocation, message: &mut [Instruction<Call>]) -> Result<(), ()>;115}116117#[impl_trait_for_tuples::impl_for_tuples(30)]118impl TryPass for Tuple {119	fn try_pass<Call>(origin: &MultiLocation, message: &mut [Instruction<Call>]) -> Result<(), ()> {120		for_tuples!( #(121			Tuple::try_pass(origin, message)?;122		)* );123124		Ok(())125	}126}127128pub struct DenyTransact;129impl TryPass for DenyTransact {130	fn try_pass<Call>(131		_origin: &MultiLocation,132		message: &mut [Instruction<Call>],133	) -> Result<(), ()> {134		let transact_inst = message135			.iter()136			.find(|inst| matches![inst, Instruction::Transact { .. }]);137138		if transact_inst.is_some() {139			log::warn!(140				target: "xcm::barrier",141				"transact XCM rejected"142			);143144			Err(())145		} else {146			Ok(())147		}148	}149}150151/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.152/// If it passes the Deny, and matches one of the Allow cases then it is let through.153pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)154where155	Deny: TryPass,156	Allow: ShouldExecute;157158impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>159where160	Deny: TryPass,161	Allow: ShouldExecute,162{163	fn should_execute<Call>(164		origin: &MultiLocation,165		message: &mut [Instruction<Call>],166		max_weight: Weight,167		weight_credit: &mut Weight,168	) -> Result<(), ()> {169		Deny::try_pass(origin, message)?;170		Allow::should_execute(origin, message, max_weight, weight_credit)171	}172}173174// Allow xcm exchange only with locations in list175pub struct DenyExchangeWithUnknownLocation<T>(PhantomData<T>);176impl<T: Get<Vec<MultiLocation>>> TryPass for DenyExchangeWithUnknownLocation<T> {177	fn try_pass<Call>(origin: &MultiLocation, message: &mut [Instruction<Call>]) -> Result<(), ()> {178		let allowed_locations = T::get();179180		// Check if deposit or transfer belongs to allowed parachains181		let mut allowed = allowed_locations.contains(origin);182183		message.iter().for_each(|inst| match inst {184			DepositReserveAsset { dest: dst, .. }185			| TransferReserveAsset { dest: dst, .. }186			| InitiateReserveWithdraw { reserve: dst, .. } => {187				allowed |= allowed_locations.contains(&dst);188			}189			// ? There are more instructions worth checking190			_ => {}191		});192193		if allowed {194			return Ok(());195		}196197		log::warn!(198			target: "xcm::barrier",199			"Unexpected deposit or transfer location"200		);201		// Deny202		Err(())203	}204}205206pub type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;207208pub struct XcmConfig<T>(PhantomData<T>);209impl<T> Config for XcmConfig<T>210where211	T: pallet_configuration::Config,212{213	type RuntimeCall = RuntimeCall;214	type XcmSender = XcmRouter;215	// How to withdraw and deposit an asset.216	type AssetTransactor = AssetTransactors;217	type OriginConverter = XcmOriginToTransactDispatchOrigin;218	type IsReserve = IsReserve;219	type IsTeleporter = (); // Teleportation is disabled220	type UniversalLocation = UniversalLocation;221	type Barrier = Barrier;222	type Weigher = Weigher;223	type Trader = Trader<T>;224	type ResponseHandler = PolkadotXcm;225	type SubscriptionService = PolkadotXcm;226	type PalletInstancesInfo = AllPalletsWithSystem;227	type MaxAssetsIntoHolding = ConstU32<8>;228229	type AssetTrap = PolkadotXcm;230	type AssetClaims = PolkadotXcm;231	type AssetLocker = ();232	type AssetExchanger = ();233	type FeeManager = ();234	type MessageExporter = ();235	type UniversalAliases = Nothing;236	type CallDispatcher = RuntimeCall;237	type SafeCallFilter = Nothing; // ? Only non-recursive calls may go here, but do we need this?238}239240#[cfg(feature = "runtime-benchmarks")]241parameter_types! {242	pub ReachableDest: Option<MultiLocation> = Some(Parent.into());243}244245impl pallet_xcm::Config for Runtime {246	type RuntimeEvent = RuntimeEvent;247	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;248	type XcmRouter = XcmRouter;249	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;250	type XcmExecuteFilter = Everything;251	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;252	type XcmTeleportFilter = Everything;253	type XcmReserveTransferFilter = Everything;254	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;255	type RuntimeOrigin = RuntimeOrigin;256	type RuntimeCall = RuntimeCall;257	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;258	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;259	type UniversalLocation = UniversalLocation;260	type Currency = Balances;261	type CurrencyMatcher = ();262	type TrustedLockers = ();263	type SovereignAccountOf = LocationToAccountId;264	type MaxLockers = ConstU32<8>;265	type WeightInfo = crate::weights::xcm::SubstrateWeight<Runtime>;266	#[cfg(feature = "runtime-benchmarks")]267	type ReachableDest = ReachableDest;268}269270impl cumulus_pallet_xcm::Config for Runtime {271	type RuntimeEvent = RuntimeEvent;272	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;273}274275impl cumulus_pallet_xcmp_queue::Config for Runtime {276	type WeightInfo = ();277	type RuntimeEvent = RuntimeEvent;278	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;279	type ChannelInfo = ParachainSystem;280	type VersionWrapper = ();281	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;282	type ControllerOrigin = EnsureRoot<AccountId>;283	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;284	type PriceForSiblingDelivery = ();285}286287impl cumulus_pallet_dmp_queue::Config for Runtime {288	type RuntimeEvent = RuntimeEvent;289	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;290	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;291}