Skip to main content

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	AssetsInHolding, 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 SubscriptionService = PolkadotXcm;
222	type PalletInstancesInfo = AllPalletsWithSystem;
223	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
224	type FeeManager = XcmFeeManagerFromComponents<
225		WaivedLocations,
226		SendXcmFeeToAccount<Self::AssetTransactor, TreasuryAccount>,
227	>;
228	type MessageExporter = (
229		XcmOverBridgeHubWestend,
230		XcmOverRococoBulletin,
231		crate::bridge_to_ethereum_config::SnowbridgeExporter,
232	);
233	type UniversalAliases = Nothing;
234	type CallDispatcher = RuntimeCall;
235	type SafeCallFilter = Everything;
236	type Aliasers = TrustedAliasers;
237	type TransactionalProcessor = FrameTransactionalProcessor;
238	type HrmpNewChannelOpenRequestHandler = ();
239	type HrmpChannelAcceptedHandler = ();
240	type HrmpChannelClosingHandler = ();
241	type XcmRecorder = PolkadotXcm;
242}
243
244pub type PriceForParentDelivery =
245	ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
246
247/// Converts a local signed origin into an XCM location. Forms the basis for local origins
248/// sending/executing XCMs.
249pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
250
251/// The means for routing XCM messages which are not for local execution into the right message
252/// queues.
253pub type XcmRouter = WithUniqueTopic<(
254	// Two routers - use UMP to communicate with the relay chain:
255	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
256	// ..and XCMP to communicate with the sibling chains.
257	XcmpQueue,
258)>;
259
260parameter_types! {
261	pub const DepositPerItem: Balance = crate::deposit(1, 0);
262	pub const DepositPerByte: Balance = crate::deposit(0, 1);
263	pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias);
264}
265
266impl pallet_xcm::Config for Runtime {
267	type RuntimeEvent = RuntimeEvent;
268	type XcmRouter = XcmRouter;
269	// We want to disallow users sending (arbitrary) XCMs from this chain.
270	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, ()>;
271	// We support local origins dispatching XCM executions.
272	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
273	type XcmExecuteFilter = Everything;
274	type XcmExecutor = XcmExecutor<XcmConfig>;
275	type XcmTeleportFilter = Everything;
276	type XcmReserveTransferFilter = Nothing; // This parachain is not meant as a reserve location.
277	type Weigher = WeightInfoBounds<
278		crate::weights::xcm::BridgeHubRococoXcmWeight<RuntimeCall>,
279		RuntimeCall,
280		MaxInstructions,
281	>;
282	type UniversalLocation = UniversalLocation;
283	type RuntimeOrigin = RuntimeOrigin;
284	type RuntimeCall = RuntimeCall;
285	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
286	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
287	type Currency = Balances;
288	type CurrencyMatcher = ();
289	type TrustedLockers = ();
290	type SovereignAccountOf = LocationToAccountId;
291	type MaxLockers = ConstU32<8>;
292	type WeightInfo = crate::weights::pallet_xcm::WeightInfo<Runtime>;
293	type AdminOrigin = EnsureRoot<AccountId>;
294	type MaxRemoteLockConsumers = ConstU32<0>;
295	type RemoteLockConsumerIdentifier = ();
296	// xcm_executor::Config::Aliasers also uses pallet_xcm::AuthorizedAliasers.
297	type AuthorizedAliasConsideration = HoldConsideration<
298		AccountId,
299		Balances,
300		AuthorizeAliasHoldReason,
301		LinearStoragePrice<DepositPerItem, DepositPerByte, Balance>,
302	>;
303}
304
305impl cumulus_pallet_xcm::Config for Runtime {
306	type RuntimeEvent = RuntimeEvent;
307	type XcmExecutor = XcmExecutor<XcmConfig>;
308}
309
310pub struct XcmFeeManagerFromComponentsBridgeHub<WaivedLocations, HandleFee>(
311	PhantomData<(WaivedLocations, HandleFee)>,
312);
313impl<WaivedLocations: Contains<Location>, FeeHandler: HandleFee> FeeManager
314	for XcmFeeManagerFromComponentsBridgeHub<WaivedLocations, FeeHandler>
315{
316	fn is_waived(origin: Option<&Location>, fee_reason: FeeReason) -> bool {
317		let Some(loc) = origin else { return false };
318		if let Export { network, destination: Here } = fee_reason {
319			if network == EthereumNetwork::get().into() {
320				return false;
321			}
322		}
323		WaivedLocations::contains(loc)
324	}
325
326	fn handle_fee(fee: AssetsInHolding, context: Option<&XcmContext>, reason: FeeReason) {
327		FeeHandler::handle_fee(fee, context, reason);
328	}
329}