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