xcm_config.rs 17.6 KiB
Newer Older
// Copyright (C) Parity Technologies (UK) Ltd.
Squirrel's avatar
Squirrel committed
// This file is part of Cumulus.

// Cumulus 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.

// Cumulus 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 Cumulus.  If not, see <http://www.gnu.org/licenses/>.

//! Holds the XCM specific configuration that would otherwise be in lib.rs
//!
//! This configuration dictates how the Penpal chain will communicate with other chains.
//!
//! One of the main uses of the penpal chain will be to be a benefactor of reserve asset transfers
//! with Asset Hub as the reserve. At present no derivative tokens are minted on receipt of a
//! `ReserveAssetTransferDeposited` message but that will but the intension will be to support this
//! soon.
Squirrel's avatar
Squirrel committed
use super::{
	AccountId, AllPalletsWithSystem, AssetId as AssetIdPalletAssets, Assets, Authorship, Balance,
	Balances, ForeignAssets, ForeignAssetsInstance, NonZeroIssuance, ParachainInfo,
	ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee,
	XcmpQueue,
Squirrel's avatar
Squirrel committed
};
use crate::{BaseDeliveryFee, FeeAssetId, TransactionByteFee};
Squirrel's avatar
Squirrel committed
use core::marker::PhantomData;
use frame_support::{
Francisco Aguirre's avatar
Francisco Aguirre committed
	parameter_types,
	traits::{ConstU32, Contains, ContainsPair, Everything, EverythingBut, Get, Nothing},
Gavin Wood's avatar
Gavin Wood committed
	weights::Weight,
Squirrel's avatar
Squirrel committed
};
use frame_system::EnsureRoot;
Squirrel's avatar
Squirrel committed
use pallet_xcm::XcmPassthrough;
use parachains_common::{xcm_config::AssetFeeAsExistentialDepositMultiplier, TREASURY_PALLET_ID};
use polkadot_parachain_primitives::primitives::Sibling;
use polkadot_runtime_common::{impls::ToAuthor, xcm_sender::ExponentialPrice};
use sp_runtime::traits::{AccountIdConversion, ConvertInto, Identity, TryConvertInto};
Squirrel's avatar
Squirrel committed
use xcm_builder::{
	AccountId32Aliases, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses,
	AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex,
	ConvertedConcreteId, EnsureXcmOrigin, FixedWeightBounds, FrameTransactionalProcessor,
	FungibleAdapter, FungiblesAdapter, IsConcrete, LocalMint, NativeAsset, NoChecking,
	ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
	SovereignSignedViaLocation, StartsWith, TakeWeightCredit, TrailingSetTopicAsId,
	UsingComponents, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents,
	XcmFeeToAccount,
Squirrel's avatar
Squirrel committed
};
Gavin Wood's avatar
Gavin Wood committed
use xcm_executor::{traits::JustTry, XcmExecutor};
Squirrel's avatar
Squirrel committed

parameter_types! {
Francisco Aguirre's avatar
Francisco Aguirre committed
	pub const RelayLocation: Location = Location::parent();
	// Local native currency which is stored in `pallet_balances``
	pub const PenpalNativeCurrency: Location = Location::here();
	// The Penpal runtime is utilized for testing with various environment setups.
	// This storage item allows us to customize the `NetworkId` where Penpal is deployed.
	// By default, it is set to `NetworkId::Rococo` and can be changed using `System::set_storage`.
	pub storage RelayNetworkId: NetworkId = NetworkId::Westend;
	pub RelayNetwork: Option<NetworkId> = Some(RelayNetworkId::get());
Sergej Sakac's avatar
Sergej Sakac committed
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
	pub UniversalLocation: InteriorLocation = [
		GlobalConsensus(RelayNetworkId::get()),
		Parachain(ParachainInfo::parachain_id().into())
	].into();
	pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
Francisco Aguirre's avatar
Francisco Aguirre committed
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
Squirrel's avatar
Squirrel committed
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
/// `Transact` in order to determine the dispatch Origin.
pub type LocationToAccountId = (
	// The parent (Relay-chain) origin converts to the parent `AccountId`.
	ParentIsPreset<AccountId>,
	// Sibling parachain origins convert to AccountId via the `ParaId::into`.
	SiblingParachainConvertsVia<Sibling, AccountId>,
	// Straight up local `AccountId32` origins just alias directly to `AccountId`.
	AccountId32Aliases<RelayNetwork, AccountId>,
);

/// Means for transacting assets on this chain.
pub type FungibleTransactor = FungibleAdapter<
Squirrel's avatar
Squirrel committed
	// Use this currency:
	Balances,
	// Use this currency when it is a fungible asset matching the given location or name:
	IsConcrete<PenpalNativeCurrency>,
Francisco Aguirre's avatar
Francisco Aguirre committed
	// Do a simple punn to convert an AccountId32 Location into a native chain account ID:
Squirrel's avatar
Squirrel committed
	LocationToAccountId,
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
	AccountId,
	// We don't track any teleports.
	(),
>;

/// Means for transacting assets besides the native currency on this chain.
pub type FungiblesTransactor = FungiblesAdapter<
	// Use this fungibles implementation:
	Assets,
	// Use this currency when it is a fungible asset matching the given location or name:
	(
		ConvertedConcreteId<
			AssetIdPalletAssets,
			Balance,
			AsPrefixedGeneralIndex<AssetsPalletLocation, AssetIdPalletAssets, JustTry>,
			JustTry,
		>,
		ConvertedConcreteId<
			AssetIdPalletAssets,
			Balance,
			AsPrefixedGeneralIndex<
				SystemAssetHubAssetsPalletLocation,
				AssetIdPalletAssets,
				JustTry,
			>,
			JustTry,
		>,
	),
Francisco Aguirre's avatar
Francisco Aguirre committed
	// Convert an XCM Location into a local account id:
Squirrel's avatar
Squirrel committed
	LocationToAccountId,
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
	AccountId,
	// We only want to allow teleports of known assets. We use non-zero issuance as an indication
	// that this asset is known.
Gavin Wood's avatar
Gavin Wood committed
	LocalMint<NonZeroIssuance<AccountId, Assets>>,
Squirrel's avatar
Squirrel committed
	// The account to use for tracking teleports.
	CheckingAccount,
>;

// Using the latest `Location`, we don't need to worry about migrations for Penpal.
pub type ForeignAssetsAssetId = Location;
pub type ForeignAssetsConvertedConcreteId = xcm_builder::MatchedConvertedConcreteId<
	Location,
	Balance,
	EverythingBut<(
		// Here we rely on fact that something like this works:
		// assert!(Location::new(1,
		// [Parachain(100)]).starts_with(&Location::parent()));
		// assert!([Parachain(100)].into().starts_with(&Here));
		StartsWith<assets_common::matching::LocalLocationPattern>,
	)>,

/// Means for transacting foreign assets from different global consensus.
pub type ForeignFungiblesTransactor = FungiblesAdapter<
	// Use this fungibles implementation:
	ForeignAssets,
	// Use this currency when it is a fungible asset matching the given location or name:
	ForeignAssetsConvertedConcreteId,
	// Convert an XCM Location into a local account id:
	LocationToAccountId,
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
	AccountId,
	// We don't need to check teleports here.
	NoChecking,
	// The account to use for tracking teleports.
	CheckingAccount,
>;

Squirrel's avatar
Squirrel committed
/// Means for transacting assets on this chain.
pub type AssetTransactors = (FungibleTransactor, ForeignFungiblesTransactor, FungiblesTransactor);
Squirrel's avatar
Squirrel committed

/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
/// biases the kind of local `Origin` it will become.
pub type XcmOriginToTransactDispatchOrigin = (
	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
	// foreign chains who want to have a local sovereign account on this chain which they control.
Sergej Sakac's avatar
Sergej Sakac committed
	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
	// Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
Squirrel's avatar
Squirrel committed
	// recognized.
Sergej Sakac's avatar
Sergej Sakac committed
	RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
Squirrel's avatar
Squirrel committed
	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
	// recognized.
Sergej Sakac's avatar
Sergej Sakac committed
	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
	// transaction from the Root origin.
	ParentAsSuperuser<RuntimeOrigin>,
Squirrel's avatar
Squirrel committed
	// Native signed account converter; this just converts an `AccountId32` origin into a normal
Sergej Sakac's avatar
Sergej Sakac committed
	// `RuntimeOrigin::Signed` origin of the same 32-byte value.
	SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
Squirrel's avatar
Squirrel committed
	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
Sergej Sakac's avatar
Sergej Sakac committed
	XcmPassthrough<RuntimeOrigin>,
Squirrel's avatar
Squirrel committed
);

parameter_types! {
	// One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate.
Gavin Wood's avatar
Gavin Wood committed
	pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
Squirrel's avatar
Squirrel committed
	pub const MaxInstructions: u32 = 100;
Gavin Wood's avatar
Gavin Wood committed
	pub const MaxAssetsIntoHolding: u32 = 64;
	pub XcmAssetFeesReceiver: Option<AccountId> = Authorship::author();
Francisco Aguirre's avatar
Francisco Aguirre committed
pub struct ParentOrParentsExecutivePlurality;
impl Contains<Location> for ParentOrParentsExecutivePlurality {
	fn contains(location: &Location) -> bool {
		matches!(location.unpack(), (1, []) | (1, [Plurality { id: BodyId::Executive, .. }]))
	}
}

pub type Barrier = TrailingSetTopicAsId<(
	TakeWeightCredit,
	// Expected responses are OK.
	AllowKnownQueryResponses<PolkadotXcm>,
	// Allow XCMs with some computed origins to pass through.
	WithComputedOrigin<
			// If the message is one that immediately attempts to pay for execution, then
			// allow it.
			AllowTopLevelPaidExecutionFrom<Everything>,
			// Subscriptions for version tracking are OK.
			AllowSubscriptionsFrom<Everything>,
			// HRMP notifications from the relay chain are OK.
			AllowHrmpNotificationsFromRelayChain,
Squirrel's avatar
Squirrel committed

/// Type alias to conveniently refer to `frame_system`'s `Config::AccountId`.
pub type AccountIdOf<R> = <R as frame_system::Config>::AccountId;

/// Asset filter that allows all assets from a certain location matching asset id.
pub struct AssetPrefixFrom<Prefix, Origin>(PhantomData<(Prefix, Origin)>);
Francisco Aguirre's avatar
Francisco Aguirre committed
impl<Prefix, Origin> ContainsPair<Asset, Location> for AssetPrefixFrom<Prefix, Origin>
Francisco Aguirre's avatar
Francisco Aguirre committed
	Prefix: Get<Location>,
	Origin: Get<Location>,
Francisco Aguirre's avatar
Francisco Aguirre committed
	fn contains(asset: &Asset, origin: &Location) -> bool {
		let loc = Origin::get();
Squirrel's avatar
Squirrel committed
		&loc == origin &&
Francisco Aguirre's avatar
Francisco Aguirre committed
			matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) }
			if asset_loc.starts_with(&Prefix::get()))
type AssetsFrom<T> = AssetPrefixFrom<T, T>;

/// Asset filter that allows native/relay asset if coming from a certain location.
pub struct NativeAssetFrom<T>(PhantomData<T>);
Francisco Aguirre's avatar
Francisco Aguirre committed
impl<T: Get<Location>> ContainsPair<Asset, Location> for NativeAssetFrom<T> {
	fn contains(asset: &Asset, origin: &Location) -> bool {
Francisco Aguirre's avatar
Francisco Aguirre committed
			matches!(asset, Asset { id: AssetId(asset_loc), fun: Fungible(_a) }
			if *asset_loc == Location::from(Parent))
// This asset can be added to AH as Asset and reserved transfer between Penpal and AH
pub const RESERVABLE_ASSET_ID: u32 = 1;
// This asset can be added to AH as ForeignAsset and teleported between Penpal and AH
pub const TELEPORTABLE_ASSET_ID: u32 = 2;

pub const ASSETS_PALLET_ID: u8 = 50;
pub const ASSET_HUB_ID: u32 = 1000;

Squirrel's avatar
Squirrel committed
parameter_types! {
	/// The location that this chain recognizes as the Relay network's Asset Hub.
	pub SystemAssetHubLocation: Location = Location::new(1, [Parachain(ASSET_HUB_ID)]);
	// the Relay Chain's Asset Hub's Assets pallet index
Francisco Aguirre's avatar
Francisco Aguirre committed
	pub SystemAssetHubAssetsPalletLocation: Location =
		Location::new(1, [Parachain(ASSET_HUB_ID), PalletInstance(ASSETS_PALLET_ID)]);
Francisco Aguirre's avatar
Francisco Aguirre committed
	pub AssetsPalletLocation: Location =
		Location::new(0, [PalletInstance(ASSETS_PALLET_ID)]);
Squirrel's avatar
Squirrel committed
	pub CheckingAccount: AccountId = PolkadotXcm::check_account();
Francisco Aguirre's avatar
Francisco Aguirre committed
	pub LocalTeleportableToAssetHub: Location = Location::new(
		0,
		[PalletInstance(ASSETS_PALLET_ID), GeneralIndex(TELEPORTABLE_ASSET_ID.into())]
Francisco Aguirre's avatar
Francisco Aguirre committed
	);
	pub LocalReservableFromAssetHub: Location = Location::new(
		1,
		[Parachain(ASSET_HUB_ID), PalletInstance(ASSETS_PALLET_ID), GeneralIndex(RESERVABLE_ASSET_ID.into())]

	/// The Penpal runtime is utilized for testing with various environment setups.
	/// This storage item provides the opportunity to customize testing scenarios
	/// by configuring the trusted asset from the `SystemAssetHub`.
	///
	/// By default, it is configured as a `SystemAssetHubLocation` and can be modified using `System::set_storage`.
	pub storage CustomizableAssetFromSystemAssetHub: Location = SystemAssetHubLocation::get();
}

/// Accepts asset with ID `AssetLocation` and is coming from `Origin` chain.
pub struct AssetFromChain<AssetLocation, Origin>(PhantomData<(AssetLocation, Origin)>);
Francisco Aguirre's avatar
Francisco Aguirre committed
impl<AssetLocation: Get<Location>, Origin: Get<Location>> ContainsPair<Asset, Location>
	for AssetFromChain<AssetLocation, Origin>
Francisco Aguirre's avatar
Francisco Aguirre committed
	fn contains(asset: &Asset, origin: &Location) -> bool {
		log::trace!(target: "xcm::contains", "AssetFromChain asset: {:?}, origin: {:?}", asset, origin);
Francisco Aguirre's avatar
Francisco Aguirre committed
		*origin == Origin::get() &&
			matches!(asset.id.clone(), AssetId(id) if id == AssetLocation::get())
	NativeAsset,
	AssetsFrom<SystemAssetHubLocation>,
	NativeAssetFrom<SystemAssetHubLocation>,
	AssetPrefixFrom<CustomizableAssetFromSystemAssetHub, SystemAssetHubLocation>,
pub type TrustedTeleporters =
	(AssetFromChain<LocalTeleportableToAssetHub, SystemAssetHubLocation>,);
Squirrel's avatar
Squirrel committed

pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
	type RuntimeCall = RuntimeCall;
Squirrel's avatar
Squirrel committed
	type XcmSender = XcmRouter;
	// How to withdraw and deposit an asset.
	type AssetTransactor = AssetTransactors;
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
	// no teleport trust established with other chains
	type IsTeleporter = TrustedTeleporters;
Gavin Wood's avatar
Gavin Wood committed
	type UniversalLocation = UniversalLocation;
Squirrel's avatar
Squirrel committed
	type Barrier = Barrier;
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
	type Trader = (
		UsingComponents<WeightToFee, RelayLocation, AccountId, Balances, ToAuthor<Runtime>>,
		// This trader allows to pay with `is_sufficient=true` "Foreign" assets from dedicated
		// `pallet_assets` instance - `ForeignAssets`.
		cumulus_primitives_utility::TakeFirstAssetTrader<
			AccountId,
			ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger,
			ForeignAssetsConvertedConcreteId,
			ForeignAssets,
			cumulus_primitives_utility::XcmFeesTo32ByteAccount<
				ForeignFungiblesTransactor,
				AccountId,
				XcmAssetFeesReceiver,
			>,
		>,
	);
Squirrel's avatar
Squirrel committed
	type ResponseHandler = PolkadotXcm;
	type AssetTrap = PolkadotXcm;
	type AssetClaims = PolkadotXcm;
	type SubscriptionService = PolkadotXcm;
Gavin Wood's avatar
Gavin Wood committed
	type PalletInstancesInfo = AllPalletsWithSystem;
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
	type AssetLocker = ();
	type AssetExchanger = ();
	type FeeManager = XcmFeeManagerFromComponents<
		(),
		XcmFeeToAccount<Self::AssetTransactor, AccountId, TreasuryAccount>,
	>;
Gavin Wood's avatar
Gavin Wood committed
	type MessageExporter = ();
	type UniversalAliases = Nothing;
	type CallDispatcher = RuntimeCall;
	type SafeCallFilter = Everything;
	type Aliasers = Nothing;
	type TransactionalProcessor = FrameTransactionalProcessor;
	type HrmpNewChannelOpenRequestHandler = ();
	type HrmpChannelAcceptedHandler = ();
	type HrmpChannelClosingHandler = ();
/// Multiplier used for dedicated `TakeFirstAssetTrader` with `ForeignAssets` instance.
pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger =
	AssetFeeAsExistentialDepositMultiplier<
		Runtime,
		WeightToFee,
		pallet_assets::BalanceToAssetBalance<Balances, Runtime, ConvertInto, ForeignAssetsInstance>,
		ForeignAssetsInstance,
	>;

Squirrel's avatar
Squirrel committed
/// No local origins on this chain are allowed to dispatch XCM sends/executions.
Sergej Sakac's avatar
Sergej Sakac committed
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
pub type PriceForParentDelivery =
	ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;

Squirrel's avatar
Squirrel committed
/// The means for routing XCM messages which are not for local execution into the right message
/// queues.
Squirrel's avatar
Squirrel committed
	// Two routers - use UMP to communicate with the relay chain:
	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
Squirrel's avatar
Squirrel committed
	// ..and XCMP to communicate with the sibling chains.
	XcmpQueue,
Squirrel's avatar
Squirrel committed

impl pallet_xcm::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
Sergej Sakac's avatar
Sergej Sakac committed
	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
Squirrel's avatar
Squirrel committed
	type XcmRouter = XcmRouter;
Sergej Sakac's avatar
Sergej Sakac committed
	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
	type XcmExecuteFilter = Everything;
Squirrel's avatar
Squirrel committed
	type XcmExecutor = XcmExecutor<XcmConfig>;
	type XcmTeleportFilter = Everything;
	type XcmReserveTransferFilter = Everything;
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
Gavin Wood's avatar
Gavin Wood committed
	type UniversalLocation = UniversalLocation;
Sergej Sakac's avatar
Sergej Sakac committed
	type RuntimeOrigin = RuntimeOrigin;
	type RuntimeCall = RuntimeCall;
Squirrel's avatar
Squirrel committed

	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
	// ^ Override for AdvertisedXcmVersion default
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
Gavin Wood's avatar
Gavin Wood committed
	type Currency = Balances;
	type CurrencyMatcher = ();
	type TrustedLockers = ();
	type SovereignAccountOf = LocationToAccountId;
	type MaxLockers = ConstU32<8>;
	type WeightInfo = pallet_xcm::TestWeightInfo;
	type AdminOrigin = EnsureRoot<AccountId>;
	type MaxRemoteLockConsumers = ConstU32<0>;
	type RemoteLockConsumerIdentifier = ();
Squirrel's avatar
Squirrel committed
}

impl cumulus_pallet_xcm::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
Squirrel's avatar
Squirrel committed
	type XcmExecutor = XcmExecutor<XcmConfig>;
}

/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
pub struct XcmBenchmarkHelper;
#[cfg(feature = "runtime-benchmarks")]
impl pallet_assets::BenchmarkHelper<ForeignAssetsAssetId> for XcmBenchmarkHelper {
	fn create_asset_id_parameter(id: u32) -> ForeignAssetsAssetId {
		Location::new(1, [Parachain(id)])