1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! XCM configuration for Moonbase.
18
//!
19

            
20
use super::{
21
	bridge_config, governance, AccountId, AssetId, Balance, Balances, BridgeXcmOverMoonriver,
22
	EmergencyParaXcm, Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue,
23
	OpenTechCommitteeInstance, ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime,
24
	RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue,
25
};
26

            
27
use super::moonbeam_weights;
28
use frame_support::{
29
	parameter_types,
30
	traits::{EitherOf, EitherOfDiverse, Everything, Nothing, PalletInfoAccess, TransformOrigin},
31
};
32
use moonkit_xcm_primitives::AccountIdAssetIdConversion;
33
use sp_runtime::{
34
	traits::{Hash as THash, MaybeEquivalence, PostDispatchInfoOf},
35
	DispatchErrorWithPostInfo,
36
};
37
use sp_weights::Weight;
38

            
39
use frame_system::{EnsureRoot, RawOrigin};
40
use sp_core::{ConstU32, H160, H256};
41

            
42
use xcm_builder::{
43
	AccountKey20Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
44
	AllowTopLevelPaidExecutionFrom, Case, DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin,
45
	FungibleAdapter as XcmCurrencyAdapter, GlobalConsensusParachainConvertsFor, HashedDescription,
46
	ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
47
	SignedAccountKey20AsNative, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
48
	WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
49
};
50

            
51
use parachains_common::message_queue::{NarrowOriginToSibling, ParaIdToSibling};
52
use xcm::{
53
	latest::prelude::{
54
		AllOf, Asset, AssetFilter, GlobalConsensus, InteriorLocation, Junction, Location,
55
		NetworkId, PalletInstance, Parachain, Wild, WildFungible,
56
	},
57
	IntoVersion,
58
};
59

            
60
use xcm_executor::traits::{CallDispatcher, ConvertLocation};
61

            
62
use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
63
use frame_support::traits::Disabled;
64
use pallet_xcm::EnsureXcm;
65
use xcm_primitives::{
66
	AbsoluteAndRelativeReserve, AccountIdToCurrencyId, AccountIdToLocation,
67
	IsBridgedConcreteAssetFrom, MultiNativeAsset, SignedToAccountId20, XcmTransact,
68
};
69

            
70
use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot};
71
use crate::runtime_params::dynamic_params;
72
use moonbeam_runtime_common::xcm_origins::AllowSiblingParachains;
73
use pallet_moonbeam_foreign_assets::{MapSuccessToGovernance, MapSuccessToXcm};
74
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
75
use scale_info::TypeInfo;
76
use sp_core::Get;
77
use sp_std::{
78
	convert::{From, Into, TryFrom},
79
	prelude::*,
80
};
81

            
82
parameter_types! {
83
	// The network Id of the relay
84
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
85
	// The relay chain Origin type
86
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
87
	pub UniversalLocation: InteriorLocation =
88
		[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
89
	// Self Reserve location, defines the multilocation identifiying the self-reserve currency
90
	// This is used to match it also against our Balances pallet when we receive such
91
	// a Location: (Self Balances pallet index)
92
	// We use the RELATIVE multilocation
93
	pub SelfReserve: Location = Location {
94
		parents:0,
95
		interior: [
96
			PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
97
		].into()
98
	};
99
}
100

            
101
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
102
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
103
/// `Transact` in order to determine the dispatch Origin.
104
pub type LocationToAccountId = (
105
	// The parent (Relay-chain) origin converts to the default `AccountId`.
106
	ParentIsPreset<AccountId>,
107
	// Sibling parachain origins convert to AccountId via the `ParaId::into`.
108
	SiblingParachainConvertsVia<polkadot_parachain::primitives::Sibling, AccountId>,
109
	// If we receive a Location of type AccountKey20, just generate a native account
110
	AccountKey20Aliases<RelayNetwork, AccountId>,
111
	// Foreign locations alias into accounts according to a hash of their standard description.
112
	HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
113
	// Different global consensus parachain sovereign account.
114
	// (Used for over-bridge transfers and reserve processing)
115
	GlobalConsensusParachainConvertsFor<UniversalLocation, AccountId>,
116
);
117

            
118
/// Wrapper type around `LocationToAccountId` to convert an `AccountId` to type `H160`.
119
pub struct LocationToH160;
120
impl ConvertLocation<H160> for LocationToH160 {
121
420
	fn convert_location(location: &Location) -> Option<H160> {
122
420
		<LocationToAccountId as ConvertLocation<AccountId>>::convert_location(location)
123
420
			.map(Into::into)
124
420
	}
125
}
126

            
127
/// The transactor for our own chain currency.
128
pub type LocalAssetTransactor = XcmCurrencyAdapter<
129
	// Use this currency:
130
	Balances,
131
	// Use this currency when it is a fungible asset matching any of the locations in
132
	// SelfReserveRepresentations
133
	xcm_builder::IsConcrete<SelfReserve>,
134
	// We can convert the MultiLocations with our converter above:
135
	LocationToAccountId,
136
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
137
	AccountId,
138
	// We dont allow teleport
139
	(),
140
>;
141

            
142
// We use all transactors
143
pub type AssetTransactors = (LocalAssetTransactor, EvmForeignAssets, Erc20XcmBridge);
144

            
145
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
146
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
147
/// biases the kind of local `Origin` it will become.
148
pub type XcmOriginToTransactDispatchOrigin = (
149
	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
150
	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
151
	// foreign chains who want to have a local sovereign account on this chain which they control.
152
	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
153
	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
154
	// recognised.
155
	RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
156
	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
157
	// recognised.
158
	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
159
	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
160
	pallet_xcm::XcmPassthrough<RuntimeOrigin>,
161
	// Xcm Origins defined by a Multilocation of type AccountKey20 can be converted to a 20 byte-
162
	// account local origin
163
	SignedAccountKey20AsNative<RelayNetwork, RuntimeOrigin>,
164
);
165

            
166
parameter_types! {
167
	/// Maximum number of instructions in a single XCM fragment. A sanity check against
168
	/// weight caculations getting too crazy.
169
	pub MaxInstructions: u32 = 100;
170
}
171

            
172
/// Xcm Weigher shared between multiple Xcm-related configs.
173
pub type XcmWeigher = WeightInfoBounds<
174
	crate::weights::xcm::XcmWeight<Runtime, RuntimeCall>,
175
	RuntimeCall,
176
	MaxInstructions,
177
>;
178

            
179
pub type XcmBarrier = TrailingSetTopicAsId<(
180
	// Weight that is paid for may be consumed.
181
	TakeWeightCredit,
182
	// Expected responses are OK.
183
	AllowKnownQueryResponses<PolkadotXcm>,
184
	WithComputedOrigin<
185
		(
186
			// If the message is one that immediately attemps to pay for execution, then allow it.
187
			AllowTopLevelPaidExecutionFrom<Everything>,
188
			// Subscriptions for version tracking are OK.
189
			AllowSubscriptionsFrom<Everything>,
190
		),
191
		UniversalLocation,
192
		ConstU32<8>,
193
	>,
194
)>;
195

            
196
parameter_types! {
197
	/// Xcm fees will go to the treasury account
198
	pub XcmFeesAccount: AccountId = Treasury::account_id();
199
}
200

            
201
pub struct SafeCallFilter;
202
impl frame_support::traits::Contains<RuntimeCall> for SafeCallFilter {
203
	fn contains(_call: &RuntimeCall) -> bool {
204
		// TODO review
205
		// This needs to be addressed at EVM level
206
		true
207
	}
208
}
209

            
210
parameter_types! {
211
	 /// Location of Asset Hub
212
	pub AssetHubLocation: Location = Location::new(1, [Parachain(1000)]);
213
	pub const RelayLocation: Location = Location::parent();
214
	pub RelayLocationFilter: AssetFilter = Wild(AllOf {
215
		fun: WildFungible,
216
		id: xcm::prelude::AssetId(RelayLocation::get()),
217
	});
218
	pub RelayChainNativeAssetFromAssetHub: (AssetFilter, Location) = (
219
		RelayLocationFilter::get(),
220
		AssetHubLocation::get()
221
	);
222
	pub const MaxAssetsIntoHolding: u32 = xcm_primitives::MAX_ASSETS;
223
}
224

            
225
type Reserves = (
226
	// Assets bridged from different consensus systems held in reserve on Asset Hub.
227
	IsBridgedConcreteAssetFrom<AssetHubLocation>,
228
	// Assets bridged from Moonriver
229
	IsBridgedConcreteAssetFrom<bp_moonriver::GlobalConsensusLocation>,
230
	// Relaychain (DOT) from Asset Hub
231
	Case<RelayChainNativeAssetFromAssetHub>,
232
	// Assets which the reserve is the same as the origin.
233
	MultiNativeAsset<AbsoluteAndRelativeReserve<SelfLocationAbsolute>>,
234
);
235

            
236
// Our implementation of the Moonbeam Call
237
// Attaches the right origin in case the call is made to pallet-ethereum-xcm
238
#[cfg(not(feature = "evm-tracing"))]
239
moonbeam_runtime_common::impl_moonbeam_xcm_call!();
240
#[cfg(feature = "evm-tracing")]
241
moonbeam_runtime_common::impl_moonbeam_xcm_call_tracing!();
242

            
243
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
244

            
245
pub struct XcmExecutorConfig;
246
impl xcm_executor::Config for XcmExecutorConfig {
247
	type RuntimeCall = RuntimeCall;
248
	type XcmSender = XcmRouter;
249
	// How to withdraw and deposit an asset.
250
	type AssetTransactor = AssetTransactors;
251
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
252
	// Filter to the reserve withdraw operations
253
	// Whenever the reserve matches the relative or absolute value
254
	// of our chain, we always return the relative reserve
255
	type IsReserve = Reserves;
256
	type IsTeleporter = (); // No teleport
257
	type UniversalLocation = UniversalLocation;
258
	type Barrier = XcmBarrier;
259
	type Weigher = XcmWeigher;
260
	// As trader we use the XcmWeightTrader pallet.
261
	// For each foreign asset, the fee is computed based on its relative price (also
262
	// stored in the XcmWeightTrader pallet) against the native asset.
263
	// For the native asset fee is computed using WeightToFee implementation.
264
	type Trader = pallet_xcm_weight_trader::Trader<Runtime>;
265
	type ResponseHandler = PolkadotXcm;
266
	type SubscriptionService = PolkadotXcm;
267
	type AssetTrap = pallet_erc20_xcm_bridge::AssetTrapWrapper<PolkadotXcm, Runtime>;
268
	type AssetClaims = PolkadotXcm;
269
	type CallDispatcher = MoonbeamCall;
270
	type PalletInstancesInfo = crate::AllPalletsWithSystem;
271
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
272
	type AssetLocker = ();
273
	type AssetExchanger = ();
274
	type FeeManager = ();
275
	type MessageExporter = BridgeXcmOverMoonriver;
276
	type UniversalAliases = bridge_config::UniversalAliases;
277
	type SafeCallFilter = SafeCallFilter;
278
	type Aliasers = Nothing;
279
	type TransactionalProcessor = xcm_builder::FrameTransactionalProcessor;
280
	type HrmpNewChannelOpenRequestHandler = ();
281
	type HrmpChannelAcceptedHandler = ();
282
	type HrmpChannelClosingHandler = ();
283
	type XcmRecorder = PolkadotXcm;
284
	type XcmEventEmitter = PolkadotXcm;
285
}
286

            
287
pub type XcmExecutor = pallet_erc20_xcm_bridge::XcmExecutorWrapper<
288
	XcmExecutorConfig,
289
	xcm_executor::XcmExecutor<XcmExecutorConfig>,
290
>;
291

            
292
// Converts a Signed Local Origin into a Location
293
pub type LocalOriginToLocation = SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
294

            
295
/// For routing XCM messages which do not cross local consensus boundary.
296
pub type LocalXcmRouter = (
297
	// Two routers - use UMP to communicate with the relay chain:
298
	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
299
	// ..and XCMP to communicate with the sibling chains.
300
	XcmpQueue,
301
);
302

            
303
/// The means for routing XCM messages which are not for local execution into the right message
304
/// queues.
305
pub type XcmRouter = WithUniqueTopic<(
306
	// The means for routing XCM messages which are not for local execution into the right message
307
	// queues.
308
	LocalXcmRouter,
309
	// Router that exports messages to be delivered to the Kusama GlobalConsensus
310
	moonbeam_runtime_common::bridge::BridgeXcmRouter<
311
		xcm_builder::LocalExporter<BridgeXcmOverMoonriver, UniversalLocation>,
312
	>,
313
)>;
314

            
315
parameter_types! {
316
	/// Conservative estimation for when AssetHub migration will start on Polkadot
317
	///
318
	/// # Calculation Details
319
	/// - **Computation date**: 2025-09-01 16:43:54 UTC
320
	/// - **Reference block**: 27_580_400
321
	/// - **Reference timestamp**: 1_756_741_434 (2025-09-01 16:43:54 UTC)
322
	/// - **Target date**: 2025-11-03 00:00:00 UTC (1 day before the migration)
323
	/// - **Target timestamp**: 1_762_128_000
324
	///
325
	/// # Block Estimation
326
	/// ```text
327
	/// Time difference: 1_762_128_000 - 1_756_741_434 = 5_386_566 seconds
328
	/// Estimated blocks: 5_386_566 ÷ 6 = 897_761 blocks (assuming 6s block time)
329
	/// Target block: 27_580_400 + 897_761 = 28_478_161
330
	/// ```
331
	///
332
	/// **Note**: This assumes consistent 6-second block times and no network delays.
333
	/// The actual migration is guaranteed to start no earlier than this block.
334
	///
335
	/// If the timeline changes, this value can be updated through a governance proposal.
336
	pub storage AssetHubMigrationStartsAtRelayBlock: u32 = 28_478_161;
337
}
338

            
339
pub struct AssetHubMigrationStarted;
340
impl Get<bool> for AssetHubMigrationStarted {
341
48
	fn get() -> bool {
342
		use cumulus_pallet_parachain_system::RelaychainDataProvider;
343
		use sp_runtime::traits::BlockNumberProvider;
344

            
345
48
		let ahm_relay_block = AssetHubMigrationStartsAtRelayBlock::get();
346
48
		let current_relay_block_number = RelaychainDataProvider::<Runtime>::current_block_number();
347
48

            
348
48
		current_relay_block_number >= ahm_relay_block
349
48
	}
350
}
351

            
352
impl pallet_xcm::Config for Runtime {
353
	type RuntimeEvent = RuntimeEvent;
354
	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
355
	type XcmRouter = XcmRouter;
356
	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
357
	type XcmExecuteFilter = Nothing;
358
	type XcmExecutor = XcmExecutor;
359
	type XcmTeleportFilter = Nothing;
360
	type XcmReserveTransferFilter = Everything;
361
	type Weigher = XcmWeigher;
362
	type UniversalLocation = UniversalLocation;
363
	type RuntimeOrigin = RuntimeOrigin;
364
	type RuntimeCall = RuntimeCall;
365
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
366
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
367
	type Currency = Balances;
368
	type CurrencyMatcher = ();
369
	type TrustedLockers = ();
370
	type SovereignAccountOf = LocationToAccountId;
371
	type MaxLockers = ConstU32<8>;
372
	type MaxRemoteLockConsumers = ConstU32<0>;
373
	type RemoteLockConsumerIdentifier = ();
374
	type WeightInfo = moonbeam_weights::pallet_xcm::WeightInfo<Runtime>;
375
	type AdminOrigin = EnsureRoot<AccountId>;
376
	type AuthorizedAliasConsideration = Disabled;
377
	/// Configuration for pallet-xcm AssetHub migration timing
378
	///
379
	/// This type alias informs pallet-xcm when to enable DOT reserve checks
380
	/// introduced in [PR #9137](https://github.com/paritytech/polkadot-sdk/pull/9137).
381
	///
382
	/// # Migration Strategy
383
	/// Rather than immediately enforcing strict reserve checks (which would cause
384
	/// hard failures), this provides a grace period for dApps to update their
385
	/// implementations and adapt to the new reserve validation requirements.
386
	///
387
	/// # Behavior
388
	/// - **Before migration**: Permissive reserve handling (legacy behavior)
389
	/// - **After migration**: Strict DOT reserve checks enforced
390
	///
391
	/// The migration timing is controlled by [`AssetHubMigrationStartsAtRelayBlock`].
392
	type AssetHubMigrationStarted = AssetHubMigrationStarted;
393
}
394

            
395
impl cumulus_pallet_xcm::Config for Runtime {
396
	type RuntimeEvent = RuntimeEvent;
397
	type XcmExecutor = XcmExecutor;
398
}
399

            
400
impl cumulus_pallet_xcmp_queue::Config for Runtime {
401
	type RuntimeEvent = RuntimeEvent;
402
	type ChannelInfo = ParachainSystem;
403
	type VersionWrapper = PolkadotXcm;
404
	type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
405
	type MaxInboundSuspended = sp_core::ConstU32<1_000>;
406
	type ControllerOrigin = EnsureRoot<AccountId>;
407
	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
408
	type WeightInfo = moonbeam_weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
409
	type PriceForSiblingDelivery = polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery<
410
		cumulus_primitives_core::ParaId,
411
	>;
412
	type MaxActiveOutboundChannels = ConstU32<128>;
413
	// Most on-chain HRMP channels are configured to use 102400 bytes of max message size, so we
414
	// need to set the page size larger than that until we reduce the channel size on-chain.
415
	type MaxPageSize = MessageQueueHeapSize;
416
}
417

            
418
parameter_types! {
419
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
420
}
421

            
422
parameter_types! {
423
	/// The amount of weight (if any) which should be provided to the message queue for
424
	/// servicing enqueued items.
425
	///
426
	/// This may be legitimately `None` in the case that you will call
427
	/// `ServiceQueues::service_queues` manually.
428
	pub MessageQueueServiceWeight: Weight =
429
		Perbill::from_percent(25) * RuntimeBlockWeights::get().max_block;
430
	/// The maximum number of stale pages (i.e. of overweight messages) allowed before culling
431
	/// can happen. Once there are more stale pages than this, then historical pages may be
432
	/// dropped, even if they contain unprocessed overweight messages.
433
	pub const MessageQueueMaxStale: u32 = 8;
434
	/// The size of the page; this implies the maximum message size which can be sent.
435
	///
436
	/// A good value depends on the expected message sizes, their weights, the weight that is
437
	/// available for processing them and the maximal needed message size. The maximal message
438
	/// size is slightly lower than this as defined by [`MaxMessageLenOf`].
439
	pub const MessageQueueHeapSize: u32 = 103 * 1024;
440
}
441

            
442
impl pallet_message_queue::Config for Runtime {
443
	type RuntimeEvent = RuntimeEvent;
444
	#[cfg(feature = "runtime-benchmarks")]
445
	type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
446
		cumulus_primitives_core::AggregateMessageOrigin,
447
	>;
448
	#[cfg(not(feature = "runtime-benchmarks"))]
449
	type MessageProcessor = pallet_ethereum_xcm::MessageProcessorWrapper<
450
		xcm_builder::ProcessXcmMessage<AggregateMessageOrigin, XcmExecutor, RuntimeCall>,
451
	>;
452
	type Size = u32;
453
	type HeapSize = MessageQueueHeapSize;
454
	type MaxStale = MessageQueueMaxStale;
455
	type ServiceWeight = MessageQueueServiceWeight;
456
	// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
457
	type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
458
	// NarrowOriginToSibling calls XcmpQueue's is_paused if Origin is sibling. Allows all other origins
459
	type QueuePausedQuery = EmergencyParaXcm;
460
	type WeightInfo = moonbeam_weights::pallet_message_queue::WeightInfo<Runtime>;
461
	type IdleMaxServiceWeight = MessageQueueServiceWeight;
462
}
463

            
464
pub type FastAuthorizeUpgradeOrigin = EitherOfDiverse<
465
	EnsureRoot<AccountId>,
466
	pallet_collective::EnsureProportionAtLeast<AccountId, OpenTechCommitteeInstance, 5, 9>,
467
>;
468

            
469
pub type ResumeXcmOrigin = EitherOfDiverse<
470
	EnsureRoot<AccountId>,
471
	pallet_collective::EnsureProportionAtLeast<AccountId, OpenTechCommitteeInstance, 5, 9>,
472
>;
473

            
474
impl pallet_emergency_para_xcm::Config for Runtime {
475
	type RuntimeEvent = RuntimeEvent;
476
	type CheckAssociatedRelayNumber =
477
		cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
478
	type QueuePausedQuery = (MaintenanceMode, NarrowOriginToSibling<XcmpQueue>);
479
	type PausedThreshold = ConstU32<300>;
480
	type FastAuthorizeUpgradeOrigin = FastAuthorizeUpgradeOrigin;
481
	type PausedToNormalOrigin = ResumeXcmOrigin;
482
}
483

            
484
// Our AssetType. For now we only handle Xcm Assets
485
#[derive(
486
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
487
)]
488
pub enum AssetType {
489
	Xcm(xcm::v3::Location),
490
}
491
impl Default for AssetType {
492
	fn default() -> Self {
493
		Self::Xcm(xcm::v3::Location::here())
494
	}
495
}
496

            
497
impl From<xcm::v3::Location> for AssetType {
498
	fn from(location: xcm::v3::Location) -> Self {
499
		Self::Xcm(location)
500
	}
501
}
502

            
503
// This can be removed once we fully adopt xcm::v5 everywhere
504
impl TryFrom<Location> for AssetType {
505
	type Error = ();
506

            
507
54
	fn try_from(location: Location) -> Result<Self, Self::Error> {
508
54
		// Convert the V5 location to a V3 location
509
54
		match xcm::VersionedLocation::V5(location).into_version(xcm::v3::VERSION) {
510
54
			Ok(xcm::VersionedLocation::V3(loc)) => Ok(AssetType::Xcm(loc.into())),
511
			// Any other version or conversion error returns an error
512
			_ => Err(()),
513
		}
514
54
	}
515
}
516

            
517
impl Into<Option<xcm::v3::Location>> for AssetType {
518
	fn into(self) -> Option<xcm::v3::Location> {
519
		match self {
520
			Self::Xcm(location) => Some(location),
521
		}
522
	}
523
}
524

            
525
impl Into<Option<Location>> for AssetType {
526
	fn into(self) -> Option<Location> {
527
		match self {
528
			Self::Xcm(location) => {
529
				let versioned = xcm::VersionedLocation::V3(location);
530
				match versioned.into_version(xcm::latest::VERSION) {
531
					Ok(xcm::VersionedLocation::V5(loc)) => Some(loc),
532
					_ => None,
533
				}
534
			}
535
		}
536
	}
537
}
538

            
539
// Implementation on how to retrieve the AssetId from an AssetType
540
// We simply hash the AssetType and take the lowest 128 bits
541
impl From<AssetType> for AssetId {
542
186
	fn from(asset: AssetType) -> AssetId {
543
186
		match asset {
544
186
			AssetType::Xcm(id) => {
545
186
				let mut result: [u8; 16] = [0u8; 16];
546
186
				let hash: H256 = id.using_encoded(<Runtime as frame_system::Config>::Hashing::hash);
547
186
				result.copy_from_slice(&hash.as_fixed_bytes()[0..16]);
548
186
				u128::from_le_bytes(result)
549
186
			}
550
186
		}
551
186
	}
552
}
553

            
554
// Our currencyId. We distinguish for now between SelfReserve, and Others, defined by their Id.
555
#[derive(
556
18
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
557
)]
558
pub enum CurrencyId {
559
	// Our native token
560
	SelfReserve,
561
	// Assets representing other chains native tokens
562
	ForeignAsset(AssetId),
563
	// Erc20 token
564
	Erc20 { contract_address: H160 },
565
}
566

            
567
impl AccountIdToCurrencyId<AccountId, CurrencyId> for Runtime {
568
	fn account_to_currency_id(account: AccountId) -> Option<CurrencyId> {
569
		Some(match account {
570
			// the self-reserve currency is identified by the pallet-balances address
571
			a if a == H160::from_low_u64_be(2050).into() => CurrencyId::SelfReserve,
572
			// the rest of the currencies, by their corresponding erc20 address
573
			_ => match Runtime::account_to_asset_id(account) {
574
				// We distinguish by prefix, and depending on it we create either
575
				// Foreign or Local
576
				Some((_prefix, asset_id)) => CurrencyId::ForeignAsset(asset_id),
577
				// If no known prefix is identified, we consider that it's a "real" erc20 token
578
				// (i.e. managed by a real smart contract)
579
				None => CurrencyId::Erc20 {
580
					contract_address: account.into(),
581
				},
582
			},
583
		})
584
	}
585
}
586
// How to convert from CurrencyId to Location
587
pub struct CurrencyIdToLocation<AssetXConverter>(sp_std::marker::PhantomData<AssetXConverter>);
588
impl<AssetXConverter> sp_runtime::traits::Convert<CurrencyId, Option<Location>>
589
	for CurrencyIdToLocation<AssetXConverter>
590
where
591
	AssetXConverter: MaybeEquivalence<Location, AssetId>,
592
{
593
9
	fn convert(currency: CurrencyId) -> Option<Location> {
594
9
		match currency {
595
			CurrencyId::SelfReserve => {
596
1
				let multi: Location = SelfReserve::get();
597
1
				Some(multi)
598
			}
599
8
			CurrencyId::ForeignAsset(asset) => AssetXConverter::convert_back(&asset),
600
			CurrencyId::Erc20 { contract_address } => {
601
				let mut location = Erc20XcmBridgePalletLocation::get();
602
				location
603
					.push_interior(Junction::AccountKey20 {
604
						key: contract_address.0,
605
						network: None,
606
					})
607
					.ok();
608
				Some(location)
609
			}
610
		}
611
9
	}
612
}
613

            
614
parameter_types! {
615
	pub const BaseXcmWeight: Weight = Weight::from_parts(200_000_000u64, 0);
616
	pub const MaxAssetsForTransfer: usize = 2;
617

            
618
	// This is how we are going to detect whether the asset is a Reserve asset
619
	// This however is the chain part only
620
	pub SelfLocation: Location = Location::here();
621
	// We need this to be able to catch when someone is trying to execute a non-
622
	// cross-chain transfer in xtokens through the absolute path way
623
	pub SelfLocationAbsolute: Location = Location {
624
		parents:1,
625
		interior: [
626
			Parachain(ParachainInfo::parachain_id().into())
627
		].into()
628
	};
629
}
630

            
631
// 1 DOT should be enough
632
parameter_types! {
633
	pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
634
}
635

            
636
// For now we only allow to transact in the relay, although this might change in the future
637
// Transactors just defines the chains in which we allow transactions to be issued through
638
// xcm
639
#[derive(
640
12
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
641
)]
642
pub enum Transactors {
643
	Relay,
644
	AssetHub,
645
}
646

            
647
// Default for benchmarking
648
#[cfg(feature = "runtime-benchmarks")]
649
impl Default for Transactors {
650
	fn default() -> Self {
651
		Transactors::Relay
652
	}
653
}
654

            
655
impl TryFrom<u8> for Transactors {
656
	type Error = ();
657
	fn try_from(value: u8) -> Result<Self, Self::Error> {
658
		match value {
659
			0u8 => Ok(Transactors::Relay),
660
			1u8 => Ok(Transactors::AssetHub),
661
			_ => Err(()),
662
		}
663
	}
664
}
665

            
666
impl XcmTransact for Transactors {
667
12
	fn destination(self) -> Location {
668
12
		match self {
669
12
			Transactors::Relay => RelayLocation::get(),
670
			Transactors::AssetHub => AssetHubLocation::get(),
671
		}
672
12
	}
673

            
674
12
	fn utility_pallet_index(&self) -> u8 {
675
12
		match self {
676
12
			Transactors::Relay => pallet_xcm_transactor::RelayIndices::<Runtime>::get().utility,
677
			Transactors::AssetHub => pallet_xcm_transactor::ASSET_HUB_UTILITY_PALLET_INDEX,
678
		}
679
12
	}
680

            
681
	fn staking_pallet_index(&self) -> u8 {
682
		match self {
683
			Transactors::Relay => pallet_xcm_transactor::RelayIndices::<Runtime>::get().staking,
684
			Transactors::AssetHub => pallet_xcm_transactor::ASSET_HUB_STAKING_PALLET_INDEX,
685
		}
686
	}
687
}
688

            
689
pub type DerivativeAddressRegistrationOrigin =
690
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
691

            
692
impl pallet_xcm_transactor::Config for Runtime {
693
	type RuntimeEvent = RuntimeEvent;
694
	type Balance = Balance;
695
	type Transactor = Transactors;
696
	type DerivativeAddressRegistrationOrigin = DerivativeAddressRegistrationOrigin;
697
	type SovereignAccountDispatcherOrigin = EnsureRoot<AccountId>;
698
	type CurrencyId = CurrencyId;
699
	type AccountIdToLocation = AccountIdToLocation<AccountId>;
700
	type CurrencyIdToLocation = CurrencyIdToLocation<(EvmForeignAssets,)>;
701
	type XcmSender = XcmRouter;
702
	type SelfLocation = SelfLocation;
703
	type Weigher = XcmWeigher;
704
	type UniversalLocation = UniversalLocation;
705
	type BaseXcmWeight = BaseXcmWeight;
706
	type AssetTransactor = AssetTransactors;
707
	type ReserveProvider = AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
708
	type WeightInfo = moonbeam_weights::pallet_xcm_transactor::WeightInfo<Runtime>;
709
	type HrmpManipulatorOrigin = GeneralAdminOrRoot;
710
	type HrmpOpenOrigin = FastGeneralAdminOrRoot;
711
	type MaxHrmpFee = xcm_builder::Case<MaxHrmpRelayFee>;
712
}
713

            
714
parameter_types! {
715
	// This is the relative view of erc20 assets.
716
	// Identified by this prefix + AccountKey20(contractAddress)
717
	// We use the RELATIVE multilocation
718
	pub Erc20XcmBridgePalletLocation: Location = Location {
719
		parents:0,
720
		interior: [
721
			PalletInstance(<Erc20XcmBridge as PalletInfoAccess>::index() as u8)
722
		].into()
723
	};
724

            
725
	// To be able to support almost all erc20 implementations,
726
	// we provide a sufficiently hight gas limit.
727
	pub Erc20XcmBridgeTransferGasLimit: u64 = 400_000;
728
}
729

            
730
impl pallet_erc20_xcm_bridge::Config for Runtime {
731
	type AccountIdConverter = LocationToH160;
732
	type Erc20MultilocationPrefix = Erc20XcmBridgePalletLocation;
733
	type Erc20TransferGasLimit = Erc20XcmBridgeTransferGasLimit;
734
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
735
}
736

            
737
pub struct AccountIdToH160;
738
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
739
336
	fn convert(account_id: AccountId) -> H160 {
740
336
		account_id.into()
741
336
	}
742
}
743

            
744
pub type ForeignAssetManagerOrigin = EitherOf<
745
	MapSuccessToXcm<EnsureXcm<AllowSiblingParachains>>,
746
	MapSuccessToGovernance<
747
		EitherOf<
748
			EnsureRoot<AccountId>,
749
			EitherOf<
750
				pallet_collective::EnsureProportionMoreThan<
751
					AccountId,
752
					OpenTechCommitteeInstance,
753
					5,
754
					9,
755
				>,
756
				EitherOf<
757
					governance::custom_origins::FastGeneralAdmin,
758
					governance::custom_origins::GeneralAdmin,
759
				>,
760
			>,
761
		>,
762
	>,
763
>;
764

            
765
impl pallet_moonbeam_foreign_assets::Config for Runtime {
766
	type AccountIdToH160 = AccountIdToH160;
767
	type AssetIdFilter = Everything;
768
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
769
	type ConvertLocation =
770
		SiblingParachainConvertsVia<polkadot_parachain::primitives::Sibling, AccountId>;
771
	type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin;
772
	type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin;
773
	type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin;
774
	type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin;
775
	type OnForeignAssetCreated = ();
776
	type MaxForeignAssets = ConstU32<256>;
777
	type RuntimeEvent = RuntimeEvent;
778
	type WeightInfo = moonbeam_weights::pallet_moonbeam_foreign_assets::WeightInfo<Runtime>;
779
	type XcmLocationToH160 = LocationToH160;
780
	type ForeignAssetCreationDeposit = dynamic_params::xcm_config::ForeignAssetCreationDeposit;
781
	type Balance = Balance;
782
	type Currency = Balances;
783
}
784

            
785
pub struct AssetFeesFilter;
786
impl frame_support::traits::Contains<Location> for AssetFeesFilter {
787
42
	fn contains(location: &Location) -> bool {
788
42
		location.parent_count() > 0
789
42
			&& location.first_interior() != Erc20XcmBridgePalletLocation::get().first_interior()
790
42
	}
791
}
792

            
793
pub type AddAndEditSupportedAssetOrigin = EitherOfDiverse<
794
	EnsureRoot<AccountId>,
795
	EitherOfDiverse<
796
		pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
797
		EitherOf<
798
			governance::custom_origins::GeneralAdmin,
799
			governance::custom_origins::FastGeneralAdmin,
800
		>,
801
	>,
802
>;
803

            
804
pub type RemoveSupportedAssetOrigin = EitherOfDiverse<
805
	EnsureRoot<AccountId>,
806
	pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
807
>;
808

            
809
impl pallet_xcm_weight_trader::Config for Runtime {
810
	type AccountIdToLocation = AccountIdToLocation<AccountId>;
811
	type AddSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
812
	type AssetLocationFilter = AssetFeesFilter;
813
	type AssetTransactor = AssetTransactors;
814
	type Balance = Balance;
815
	type EditSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
816
	type NativeLocation = SelfReserve;
817
	type PauseSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
818
	type ResumeSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
819
	type RemoveSupportedAssetOrigin = RemoveSupportedAssetOrigin;
820
	type RuntimeEvent = RuntimeEvent;
821
	type WeightInfo = moonbeam_weights::pallet_xcm_weight_trader::WeightInfo<Runtime>;
822
	type WeightToFee = <Runtime as pallet_transaction_payment::Config>::WeightToFee;
823
	type XcmFeesAccount = XcmFeesAccount;
824
	#[cfg(feature = "runtime-benchmarks")]
825
	type NotFilteredLocation = RelayLocation;
826
}
827

            
828
#[cfg(feature = "runtime-benchmarks")]
829
mod testing {
830
	use super::*;
831

            
832
	/// This From exists for benchmarking purposes. It has the potential side-effect of calling
833
	/// EvmForeignAssets::set_asset() and should NOT be used in any production code.
834
	impl From<Location> for CurrencyId {
835
		fn from(location: Location) -> CurrencyId {
836
			use sp_runtime::traits::MaybeEquivalence;
837

            
838
			// If it does not exist, for benchmarking purposes, we create the association
839
			let asset_id = if let Some(asset_id) = EvmForeignAssets::convert(&location) {
840
				asset_id
841
			} else {
842
				// Generate asset ID from location hash (similar to old AssetManager approach)
843
				let hash: H256 =
844
					location.using_encoded(<Runtime as frame_system::Config>::Hashing::hash);
845
				let mut result: [u8; 16] = [0u8; 16];
846
				result.copy_from_slice(&hash.as_fixed_bytes()[0..16]);
847
				let asset_id = u128::from_le_bytes(result);
848

            
849
				EvmForeignAssets::set_asset(location, asset_id);
850
				asset_id
851
			};
852

            
853
			CurrencyId::ForeignAsset(asset_id)
854
		}
855
	}
856
}
857

            
858
#[cfg(test)]
859
mod tests {
860
	use super::AssetHubMigrationStartsAtRelayBlock;
861

            
862
	#[test]
863
1
	fn check_type_parameter_key() {
864
1
		let implicit_key = AssetHubMigrationStartsAtRelayBlock::key();
865
1
		let explicit_key = sp_core::twox_128(b":AssetHubMigrationStartsAtRelayBlock:");
866
1
		assert_eq!(implicit_key, explicit_key);
867
1
	}
868
}