referrerpolicy=no-referrer-when-downgrade

bridge_hub_westend_runtime/
xcm_config.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// 	http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17use super::{
18	AccountId, AllPalletsWithSystem, Balance, Balances, BaseDeliveryFee, FeeAssetId, ParachainInfo,
19	ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeHoldReason,
20	RuntimeOrigin, TransactionByteFee, WeightToFee, XcmOverBridgeHubRococo, XcmpQueue,
21};
22use crate::bridge_to_ethereum_config::SnowbridgeFrontendLocation;
23use bridge_hub_common::DenyExportMessageFrom;
24use frame_support::{
25	parameter_types,
26	traits::{
27		fungible::HoldConsideration, tokens::imbalance::ResolveTo, ConstU32, Contains, Equals,
28		Everything, EverythingBut, LinearStoragePrice, Nothing,
29	},
30};
31use frame_system::EnsureRoot;
32use pallet_collator_selection::StakingPotAccountId;
33use pallet_xcm::{AuthorizedAliasers, XcmPassthrough};
34use parachains_common::{
35	xcm_config::{
36		AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains,
37		RelayOrOtherSystemParachains,
38	},
39	TREASURY_PALLET_ID,
40};
41use polkadot_parachain_primitives::primitives::Sibling;
42use polkadot_runtime_common::xcm_sender::ExponentialPrice;
43use sp_runtime::traits::AccountIdConversion;
44use testnet_parachains_constants::westend::{
45	locations::AssetHubLocation, snowbridge::EthereumNetwork,
46};
47use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH};
48use xcm_builder::{
49	AccountId32Aliases, AliasChildLocation, AllowExplicitUnpaidExecutionFrom,
50	AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom,
51	AllowTopLevelPaidExecutionFrom, DenyRecursively, DenyReserveTransferToRelayChain, DenyThenTry,
52	DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, ExternalConsensusLocationsConverterFor,
53	FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsConcrete,
54	LocationAsSuperuser, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative,
55	SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia,
56	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
57	TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
58	XcmFeeManagerFromComponents,
59};
60use xcm_executor::XcmExecutor;
61
62// Re-export
63pub use testnet_parachains_constants::westend::locations::GovernanceLocation;
64
65parameter_types! {
66	pub const RootLocation: Location = Location::here();
67	pub const WestendLocation: Location = Location::parent();
68	pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
69	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
70	pub UniversalLocation: InteriorLocation =
71		[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
72	pub const MaxInstructions: u32 = 100;
73	pub const MaxAssetsIntoHolding: u32 = 64;
74	pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating();
75	pub RelayTreasuryLocation: Location = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into();
76}
77
78/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
79/// when determining ownership of accounts for asset transacting and when attempting to use XCM
80/// `Transact` in order to determine the dispatch Origin.
81pub type LocationToAccountId = (
82	// The parent (Relay-chain) origin converts to the parent `AccountId`.
83	ParentIsPreset<AccountId>,
84	// Sibling parachain origins convert to AccountId via the `ParaId::into`.
85	SiblingParachainConvertsVia<Sibling, AccountId>,
86	// Straight up local `AccountId32` origins just alias directly to `AccountId`.
87	AccountId32Aliases<RelayNetwork, AccountId>,
88	// Foreign locations alias into accounts according to a hash of their standard description.
89	HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
90	// Different global consensus locations sovereign accounts.
91	ExternalConsensusLocationsConverterFor<UniversalLocation, AccountId>,
92);
93
94/// Means for transacting the native currency on this chain.
95pub type FungibleTransactor = FungibleAdapter<
96	// Use this currency:
97	Balances,
98	// Use this currency when it is a fungible asset matching the given location or name:
99	IsConcrete<WestendLocation>,
100	// Do a simple punn to convert an AccountId32 Location into a native chain account ID:
101	LocationToAccountId,
102	// Our chain's account ID type (we can't get away without mentioning it explicitly):
103	AccountId,
104	// We don't track any teleports of `Balances`.
105	(),
106>;
107
108/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
109/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
110/// biases the kind of local `Origin` it will become.
111pub type XcmOriginToTransactDispatchOrigin = (
112	// Governance location can gain root.
113	LocationAsSuperuser<Equals<GovernanceLocation>, RuntimeOrigin>,
114	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
115	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
116	// foreign chains who want to have a local sovereign account on this chain which they control.
117	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
118	// Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
119	// recognized.
120	RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
121	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
122	// recognized.
123	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
124	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
125	// transaction from the Root origin.
126	ParentAsSuperuser<RuntimeOrigin>,
127	// Native signed account converter; this just converts an `AccountId32` origin into a normal
128	// `RuntimeOrigin::Signed` origin of the same 32-byte value.
129	SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
130	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
131	XcmPassthrough<RuntimeOrigin>,
132);
133
134pub struct ParentOrParentsPlurality;
135impl Contains<Location> for ParentOrParentsPlurality {
136	fn contains(location: &Location) -> bool {
137		let result = matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]));
138		tracing::trace!(target: "xcm::contains", ?location, ?result, "ParentOrParentsPlurality matches");
139		result
140	}
141}
142
143pub type Barrier = TrailingSetTopicAsId<
144	DenyThenTry<
145		(
146			DenyRecursively<DenyReserveTransferToRelayChain>,
147			DenyRecursively<
148				DenyExportMessageFrom<
149					EverythingBut<Equals<AssetHubLocation>>,
150					Equals<EthereumNetwork>,
151				>,
152			>,
153		),
154		(
155			// Allow local users to buy weight credit.
156			TakeWeightCredit,
157			// Expected responses are OK.
158			AllowKnownQueryResponses<PolkadotXcm>,
159			WithComputedOrigin<
160				(
161					// If the message is one that immediately attempts to pay for execution, then
162					// allow it.
163					AllowTopLevelPaidExecutionFrom<Everything>,
164					// Parent, its pluralities (i.e. governance bodies) and relay treasury pallet
165					// get free execution.
166					AllowExplicitUnpaidExecutionFrom<(
167						ParentOrParentsPlurality,
168						Equals<RelayTreasuryLocation>,
169						Equals<SnowbridgeFrontendLocation>,
170						Equals<GovernanceLocation>,
171					)>,
172					// Subscriptions for version tracking are OK.
173					AllowSubscriptionsFrom<ParentRelayOrSiblingParachains>,
174					// HRMP notifications from the relay chain are OK.
175					AllowHrmpNotificationsFromRelayChain,
176				),
177				UniversalLocation,
178				ConstU32<8>,
179			>,
180		),
181	>,
182>;
183
184/// Locations that will not be charged fees in the executor,
185/// either execution or delivery.
186/// We only waive fees for system functions, which these locations represent.
187pub type WaivedLocations = (
188	Equals<RootLocation>,
189	RelayOrOtherSystemParachains<AllSiblingSystemParachains, Runtime>,
190	Equals<RelayTreasuryLocation>,
191);
192
193/// Cases where a remote origin is accepted as trusted Teleporter for a given asset:
194/// - NativeToken with the parent Relay Chain and sibling parachains.
195pub type TrustedTeleporters = ConcreteAssetFromSystem<WestendLocation>;
196
197/// Defines origin aliasing rules for this chain.
198///
199/// - Allow any origin to alias into a child sub-location (equivalent to DescendOrigin),
200/// - Allow origins explicitly authorized by the alias target location.
201pub type TrustedAliasers = (AliasChildLocation, AuthorizedAliasers<Runtime>);
202
203pub struct XcmConfig;
204impl xcm_executor::Config for XcmConfig {
205	type RuntimeCall = RuntimeCall;
206	type XcmSender = XcmRouter;
207	type XcmEventEmitter = PolkadotXcm;
208	type AssetTransactor = FungibleTransactor;
209	type OriginConverter = XcmOriginToTransactDispatchOrigin;
210	// BridgeHub does not recognize a reserve location for any asset. Users must teleport Native
211	// token where allowed (e.g. with the Relay Chain).
212	type IsReserve = ();
213	type IsTeleporter = TrustedTeleporters;
214	type UniversalLocation = UniversalLocation;
215	type Barrier = Barrier;
216	type Weigher = WeightInfoBounds<
217		crate::weights::xcm::BridgeHubWestendXcmWeight<RuntimeCall>,
218		RuntimeCall,
219		MaxInstructions,
220	>;
221	type Trader = UsingComponents<
222		WeightToFee,
223		WestendLocation,
224		AccountId,
225		Balances,
226		ResolveTo<StakingPotAccountId<Runtime>, Balances>,
227	>;
228	type ResponseHandler = PolkadotXcm;
229	type AssetTrap = PolkadotXcm;
230	type AssetLocker = ();
231	type AssetExchanger = ();
232	type AssetClaims = PolkadotXcm;
233	type SubscriptionService = PolkadotXcm;
234	type PalletInstancesInfo = AllPalletsWithSystem;
235	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
236	type FeeManager = XcmFeeManagerFromComponents<
237		WaivedLocations,
238		SendXcmFeeToAccount<Self::AssetTransactor, TreasuryAccount>,
239	>;
240	type MessageExporter = (
241		XcmOverBridgeHubRococo,
242		crate::bridge_to_ethereum_config::SnowbridgeExporterV2,
243		crate::bridge_to_ethereum_config::SnowbridgeExporter,
244	);
245	type UniversalAliases = Nothing;
246	type CallDispatcher = RuntimeCall;
247	type SafeCallFilter = Everything;
248	type Aliasers = TrustedAliasers;
249	type TransactionalProcessor = FrameTransactionalProcessor;
250	type HrmpNewChannelOpenRequestHandler = ();
251	type HrmpChannelAcceptedHandler = ();
252	type HrmpChannelClosingHandler = ();
253	type XcmRecorder = PolkadotXcm;
254}
255
256pub type PriceForParentDelivery =
257	ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
258
259/// Converts a local signed origin into an XCM location. Forms the basis for local origins
260/// sending/executing XCMs.
261pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
262
263/// The means for routing XCM messages which are not for local execution into the right message
264/// queues.
265pub type XcmRouter = WithUniqueTopic<(
266	// Two routers - use UMP to communicate with the relay chain:
267	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
268	// ..and XCMP to communicate with the sibling chains.
269	XcmpQueue,
270)>;
271
272parameter_types! {
273	pub const DepositPerItem: Balance = crate::deposit(1, 0);
274	pub const DepositPerByte: Balance = crate::deposit(0, 1);
275	pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias);
276}
277
278impl pallet_xcm::Config for Runtime {
279	type RuntimeEvent = RuntimeEvent;
280	type XcmRouter = XcmRouter;
281	// We want to disallow users sending (arbitrary) XCMs from this chain.
282	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, ()>;
283	// We support local origins dispatching XCM executions.
284	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
285	type XcmExecuteFilter = Everything;
286	type XcmExecutor = XcmExecutor<XcmConfig>;
287	type XcmTeleportFilter = Everything;
288	type XcmReserveTransferFilter = Nothing; // This parachain is not meant as a reserve location.
289	type Weigher = WeightInfoBounds<
290		crate::weights::xcm::BridgeHubWestendXcmWeight<RuntimeCall>,
291		RuntimeCall,
292		MaxInstructions,
293	>;
294	type UniversalLocation = UniversalLocation;
295	type RuntimeOrigin = RuntimeOrigin;
296	type RuntimeCall = RuntimeCall;
297	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
298	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
299	type Currency = Balances;
300	type CurrencyMatcher = ();
301	type TrustedLockers = ();
302	type SovereignAccountOf = LocationToAccountId;
303	type MaxLockers = ConstU32<8>;
304	type WeightInfo = crate::weights::pallet_xcm::WeightInfo<Runtime>;
305	type AdminOrigin = EnsureRoot<AccountId>;
306	type MaxRemoteLockConsumers = ConstU32<0>;
307	type RemoteLockConsumerIdentifier = ();
308	// xcm_executor::Config::Aliasers also uses pallet_xcm::AuthorizedAliasers.
309	type AuthorizedAliasConsideration = HoldConsideration<
310		AccountId,
311		Balances,
312		AuthorizeAliasHoldReason,
313		LinearStoragePrice<DepositPerItem, DepositPerByte, Balance>,
314	>;
315}
316
317impl cumulus_pallet_xcm::Config for Runtime {
318	type RuntimeEvent = RuntimeEvent;
319	type XcmExecutor = XcmExecutor<XcmConfig>;
320}