referrerpolicy=no-referrer-when-downgrade

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