xcm_config.rs 13.8 KiB
Newer Older
Squirrel's avatar
Squirrel committed
// Copyright 2019-2022 Parity Technologies (UK) Ltd.
// 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 statemine 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.
use super::{
Gavin Wood's avatar
Gavin Wood committed
	AccountId, AllPalletsWithSystem, AssetId as AssetIdPalletAssets, Assets, Balance, Balances,
	ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
	WeightToFee, XcmpQueue,
Squirrel's avatar
Squirrel committed
};
use core::marker::PhantomData;
use frame_support::{
Squirrel's avatar
Squirrel committed
	traits::{
		fungibles::{self, Balanced, Credit},
Gavin Wood's avatar
Gavin Wood committed
		ConstU32, Contains, ContainsPair, Everything, Get, Nothing,
Squirrel's avatar
Squirrel committed
	},
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_asset_tx_payment::HandleCredit;
use pallet_xcm::XcmPassthrough;
use parachains_common::xcm_config::{DenyReserveTransferToRelayChain, DenyThenTry};
Squirrel's avatar
Squirrel committed
use polkadot_parachain::primitives::Sibling;
use polkadot_runtime_common::impls::ToAuthor;
use sp_runtime::traits::Zero;
Squirrel's avatar
Squirrel committed
use xcm_builder::{
Gavin Wood's avatar
Gavin Wood committed
	AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
	AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex,
	ConvertedConcreteId, CurrencyAdapter, EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter,
	IsConcrete, LocalMint, NativeAsset, ParentIsPreset, RelayChainAsNative,
	SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
	SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,
	WithComputedOrigin,
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! {
	pub const RelayLocation: MultiLocation = MultiLocation::parent();
Gavin Wood's avatar
Gavin Wood committed
	pub const RelayNetwork: Option<NetworkId> = None;
Sergej Sakac's avatar
Sergej Sakac committed
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
Gavin Wood's avatar
Gavin Wood committed
	pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));
Squirrel's avatar
Squirrel committed
}

/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
/// 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 CurrencyTransactor = CurrencyAdapter<
	// Use this currency:
	Balances,
	// Use this currency when it is a fungible asset matching the given location or name:
	IsConcrete<RelayLocation>,
	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
	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:
Gavin Wood's avatar
Gavin Wood committed
	ConvertedConcreteId<
Squirrel's avatar
Squirrel committed
		AssetIdPalletAssets,
		Balance,
		AsPrefixedGeneralIndex<CommonGoodAssetsPalletLocation, AssetIdPalletAssets, JustTry>,
		JustTry,
	>,
	// Convert an XCM MultiLocation into a local account id:
	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,
>;

/// Means for transacting assets on this chain.
pub type AssetTransactors = (CurrencyTransactor, FungiblesTransactor);

/// 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>,
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;
Squirrel's avatar
Squirrel committed
}

match_types! {
	pub type ParentOrParentsExecutivePlurality: impl Contains<MultiLocation> = {
		MultiLocation { parents: 1, interior: Here } |
		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) }
	};
	pub type CommonGoodAssetsParachain: impl Contains<MultiLocation> = {
		MultiLocation { parents: 1, interior: X1(Parachain(1000)) }
	};
}

pub type Barrier = DenyThenTry<
	DenyReserveTransferToRelayChain,
	(
		TakeWeightCredit,
		// Expected responses are OK.
		AllowKnownQueryResponses<PolkadotXcm>,
Gavin Wood's avatar
Gavin Wood committed
		// Allow XCMs with some computed origins to pass through.
		WithComputedOrigin<
			(
				// If the message is one that immediately attemps to pay for execution, then allow it.
				AllowTopLevelPaidExecutionFrom<Everything>,
				// Common Good Assets parachain, parent and its exec plurality get free execution
				AllowExplicitUnpaidExecutionFrom<(
					CommonGoodAssetsParachain,
					ParentOrParentsExecutivePlurality,
				)>,
				// Subscriptions for version tracking are OK.
				AllowSubscriptionsFrom<Everything>,
			),
			UniversalLocation,
			ConstU32<8>,
		>,
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.
pub struct AssetsFrom<T>(PhantomData<T>);
Gavin Wood's avatar
Gavin Wood committed
impl<T: Get<MultiLocation>> ContainsPair<MultiAsset, MultiLocation> for AssetsFrom<T> {
	fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool {
Squirrel's avatar
Squirrel committed
		let loc = T::get();
		&loc == origin &&
			matches!(asset, MultiAsset { id: AssetId::Concrete(asset_loc), fun: Fungible(_a) }
			if asset_loc.match_and_split(&loc).is_some())
	}
}

/// Allow checking in assets that have issuance > 0.
pub struct NonZeroIssuance<AccountId, Assets>(PhantomData<(AccountId, Assets)>);
impl<AccountId, Assets> Contains<<Assets as fungibles::Inspect<AccountId>>::AssetId>
	for NonZeroIssuance<AccountId, Assets>
where
	Assets: fungibles::Inspect<AccountId>,
{
	fn contains(id: &<Assets as fungibles::Inspect<AccountId>>::AssetId) -> bool {
		!Assets::total_issuance(id.clone()).is_zero()
Squirrel's avatar
Squirrel committed
	}
}

/// A `HandleCredit` implementation that naively transfers the fees to the block author.
/// Will drop and burn the assets in case the transfer fails.
pub struct AssetsToBlockAuthor<R>(PhantomData<R>);
impl<R> HandleCredit<AccountIdOf<R>, pallet_assets::Pallet<R>> for AssetsToBlockAuthor<R>
where
	R: pallet_authorship::Config + pallet_assets::Config,
	AccountIdOf<R>: From<polkadot_primitives::AccountId> + Into<polkadot_primitives::AccountId>,
	fn handle_credit(credit: Credit<AccountIdOf<R>, pallet_assets::Pallet<R>>) {
Squirrel's avatar
Squirrel committed
		if let Some(author) = pallet_authorship::Pallet::<R>::author() {
			// In case of error: Will drop the result triggering the `OnDrop` of the imbalance.
			let _ = pallet_assets::Pallet::<R>::resolve(&author, credit);
		}
	}
}

pub trait Reserve {
	/// Returns assets reserve location.
	fn reserve(&self) -> Option<MultiLocation>;
}

// Takes the chain part of a MultiAsset
impl Reserve for MultiAsset {
	fn reserve(&self) -> Option<MultiLocation> {
Oliver Tale-Yazdi's avatar
Oliver Tale-Yazdi committed
		if let AssetId::Concrete(location) = self.id {
Squirrel's avatar
Squirrel committed
			let first_interior = location.first_interior();
			let parents = location.parent_count();
Oliver Tale-Yazdi's avatar
Oliver Tale-Yazdi committed
			match (parents, first_interior) {
				(0, Some(Parachain(id))) => Some(MultiLocation::new(0, X1(Parachain(*id)))),
				(1, Some(Parachain(id))) => Some(MultiLocation::new(1, X1(Parachain(*id)))),
Squirrel's avatar
Squirrel committed
				(1, _) => Some(MultiLocation::parent()),
				_ => None,
			}
		} else {
			None
		}
	}
}

/// A `FilterAssetLocation` implementation. Filters multi native assets whose
/// reserve is same with `origin`.
pub struct MultiNativeAsset;
Gavin Wood's avatar
Gavin Wood committed
impl ContainsPair<MultiAsset, MultiLocation> for MultiNativeAsset {
	fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool {
Squirrel's avatar
Squirrel committed
		if let Some(ref reserve) = asset.reserve() {
			if reserve == origin {
				return true
			}
		}
		false
	}
}

parameter_types! {
	pub CommonGoodAssetsLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(1000)));
	// ALWAYS ensure that the index in PalletInstance stays up-to-date with
	// Statemint's Assets pallet index
	pub CommonGoodAssetsPalletLocation: MultiLocation =
		MultiLocation::new(1, X2(Parachain(1000), PalletInstance(50)));
	pub CheckingAccount: AccountId = PolkadotXcm::check_account();
}

pub type Reserves = (NativeAsset, AssetsFrom<CommonGoodAssetsLocation>);

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;
	type IsReserve = MultiNativeAsset; // TODO: maybe needed to be replaced by Reserves
	type IsTeleporter = NativeAsset;
Gavin Wood's avatar
Gavin Wood committed
	type UniversalLocation = UniversalLocation;
Squirrel's avatar
Squirrel committed
	type Barrier = Barrier;
	type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
Squirrel's avatar
Squirrel committed
	type Trader =
		UsingComponents<WeightToFee, RelayLocation, AccountId, Balances, ToAuthor<Runtime>>;
	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 = ();
	type MessageExporter = ();
	type UniversalAliases = Nothing;
	type CallDispatcher = RuntimeCall;
	type SafeCallFilter = Everything;
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>;
Squirrel's avatar
Squirrel committed

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

Gavin Wood's avatar
Gavin Wood committed
#[cfg(feature = "runtime-benchmarks")]
parameter_types! {
	pub ReachableDest: Option<MultiLocation> = Some(Parent.into());
}

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>;
Squirrel's avatar
Squirrel committed
	type XcmExecuteFilter = Nothing;
	// ^ Disable dispatchable execute on the XCM pallet.
	// Needs to be `Everything` for local testing.
	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;
	#[cfg(feature = "runtime-benchmarks")]
	type ReachableDest = ReachableDest;
	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>;
}