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, BridgeXcmOverMoonbeam,
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::moonriver_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::Kusama;
85
	// The relay chain Origin type
86
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
87
	// The universal location within the global consensus system
88
	pub UniversalLocation: InteriorLocation =
89
		[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
90

            
91
	// Self Reserve location, defines the multilocation identifying the self-reserve currency
92
	// This is used to match it also against our Balances pallet when we receive such
93
	// a Location: (Self Balances pallet index)
94
	// We use the RELATIVE multilocation
95
	pub SelfReserve: Location = Location {
96
		parents:0,
97
		interior: [
98
			PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
99
		].into()
100
	};
101
}
102

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

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

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

            
144
// We use all transactors
145
// These correspond to
146
// SelfReserve asset, both pre and post 0.9.16
147
// Foreign assets
148
// Local assets, both pre and post 0.9.16
149
// We can remove the Old reanchor once
150
// we import https://github.com/open-web3-stack/open-runtime-module-library/pull/708
151
pub type AssetTransactors = (LocalAssetTransactor, EvmForeignAssets, Erc20XcmBridge);
152

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

            
174
parameter_types! {
175
	/// Maximum number of instructions in a single XCM fragment. A sanity check against
176
	/// weight caculations getting too crazy.
177
	pub MaxInstructions: u32 = 100;
178
}
179

            
180
/// Xcm Weigher shared between multiple Xcm-related configs.
181
pub type XcmWeigher = WeightInfoBounds<
182
	crate::weights::xcm::XcmWeight<Runtime, RuntimeCall>,
183
	RuntimeCall,
184
	MaxInstructions,
185
>;
186

            
187
pub type XcmBarrier = TrailingSetTopicAsId<(
188
	// Weight that is paid for may be consumed.
189
	TakeWeightCredit,
190
	// Expected responses are OK.
191
	AllowKnownQueryResponses<PolkadotXcm>,
192
	WithComputedOrigin<
193
		(
194
			// If the message is one that immediately attemps to pay for execution, then allow it.
195
			AllowTopLevelPaidExecutionFrom<Everything>,
196
			// Subscriptions for version tracking are OK.
197
			AllowSubscriptionsFrom<Everything>,
198
		),
199
		UniversalLocation,
200
		ConstU32<8>,
201
	>,
202
)>;
203

            
204
parameter_types! {
205
	/// Xcm fees will go to the treasury account
206
	pub XcmFeesAccount: AccountId = Treasury::account_id();
207
}
208

            
209
pub struct SafeCallFilter;
210
impl frame_support::traits::Contains<RuntimeCall> for SafeCallFilter {
211
	fn contains(_call: &RuntimeCall) -> bool {
212
		// TODO review
213
		// This needs to be addressed at EVM level
214
		true
215
	}
216
}
217

            
218
parameter_types! {
219
	/// Location of Asset Hub
220
	pub AssetHubLocation: Location = Location::new(1, [Parachain(1000)]);
221
	pub const RelayLocation: Location = Location::parent();
222
	pub RelayLocationFilter: AssetFilter = Wild(AllOf {
223
		fun: WildFungible,
224
		id: xcm::prelude::AssetId(RelayLocation::get()),
225
	});
226
	pub RelayChainNativeAssetFromAssetHub: (AssetFilter, Location) = (
227
		RelayLocationFilter::get(),
228
		AssetHubLocation::get()
229
	);
230
	pub const MaxAssetsIntoHolding: u32 = xcm_primitives::MAX_ASSETS;
231
}
232

            
233
type Reserves = (
234
	// Assets bridged from different consensus systems held in reserve on Asset Hub.
235
	IsBridgedConcreteAssetFrom<AssetHubLocation>,
236
	// Assets bridged from Moonbeam
237
	IsBridgedConcreteAssetFrom<bp_moonbeam::GlobalConsensusLocation>,
238
	// Relaychain (DOT) from Asset Hub
239
	Case<RelayChainNativeAssetFromAssetHub>,
240
	// Assets which the reserve is the same as the origin.
241
	MultiNativeAsset<AbsoluteAndRelativeReserve<SelfLocationAbsolute>>,
242
);
243

            
244
// Our implementation of the Moonbeam Call
245
// Attaches the right origin in case the call is made to pallet-ethereum-xcm
246
#[cfg(not(feature = "evm-tracing"))]
247
moonbeam_runtime_common::impl_moonbeam_xcm_call!();
248
#[cfg(feature = "evm-tracing")]
249
moonbeam_runtime_common::impl_moonbeam_xcm_call_tracing!();
250

            
251
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
252

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

            
295
pub type XcmExecutor = pallet_erc20_xcm_bridge::XcmExecutorWrapper<
296
	XcmExecutorConfig,
297
	xcm_executor::XcmExecutor<XcmExecutorConfig>,
298
>;
299

            
300
// Converts a Signed Local Origin into a Location
301
pub type LocalOriginToLocation = SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
302

            
303
/// For routing XCM messages which do not cross local consensus boundary.
304
pub type LocalXcmRouter = (
305
	// Two routers - use UMP to communicate with the relay chain:
306
	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
307
	// ..and XCMP to communicate with the sibling chains.
308
	XcmpQueue,
309
);
310

            
311
/// The means for routing XCM messages which are not for local execution into the right message
312
/// queues.
313
pub type XcmRouter = WithUniqueTopic<(
314
	// The means for routing XCM messages which are not for local execution into the right message
315
	// queues.
316
	LocalXcmRouter,
317
	// Router that exports messages to be delivered to the Polkadot GlobalConsensus
318
	moonbeam_runtime_common::bridge::BridgeXcmRouter<
319
		xcm_builder::LocalExporter<BridgeXcmOverMoonbeam, UniversalLocation>,
320
	>,
321
)>;
322

            
323
parameter_types! {
324
	/// Conservative estimation for when AssetHub migration will start on Kusama
325
	///
326
	/// # Calculation Details
327
	/// - **Computation date**: 2025-09-01 16:29:48 UTC
328
	/// - **Reference block**: 29_913_400
329
	/// - **Reference timestamp**: 1_756_740_588 (2025-09-01 16:29:48 UTC)
330
	/// - **Target date**: 2025-10-06 00:00:00 UTC (1 day before the migration)
331
	/// - **Target timestamp**: 1_759_705_200
332
	///
333
	/// # Block Estimation
334
	/// ```text
335
	/// Time difference: 1_759_705_200 - 1_756_740_588 = 2_964_612 seconds
336
	/// Estimated blocks: 2_964_612 ÷ 6 = 494_102 blocks (assuming 6s block time)
337
	/// Target block: 29_913_400 + 494_102 = 30_407_502
338
	/// ```
339
	///
340
	/// **Note**: This assumes consistent 6-second block times and no network delays.
341
	/// The actual migration is guaranteed to start no earlier than this block.
342
	///
343
	/// If the timeline changes, this value can be updated through a governance proposal.
344
	pub storage AssetHubMigrationStartsAtRelayBlock: u32 = 30_407_502;
345
}
346

            
347
pub struct AssetHubMigrationStarted;
348
impl Get<bool> for AssetHubMigrationStarted {
349
42
	fn get() -> bool {
350
		use cumulus_pallet_parachain_system::RelaychainDataProvider;
351
		use sp_runtime::traits::BlockNumberProvider;
352

            
353
42
		let ahm_relay_block = AssetHubMigrationStartsAtRelayBlock::get();
354
42
		let current_relay_block_number = RelaychainDataProvider::<Runtime>::current_block_number();
355
42

            
356
42
		current_relay_block_number >= ahm_relay_block
357
42
	}
358
}
359

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

            
403
impl cumulus_pallet_xcm::Config for Runtime {
404
	type RuntimeEvent = RuntimeEvent;
405
	type XcmExecutor = XcmExecutor;
406
}
407

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

            
426
parameter_types! {
427
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
428
}
429

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

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

            
472
pub type FastAuthorizeUpgradeOrigin = EitherOfDiverse<
473
	EnsureRoot<AccountId>,
474
	pallet_collective::EnsureProportionAtLeast<AccountId, OpenTechCommitteeInstance, 5, 9>,
475
>;
476

            
477
pub type ResumeXcmOrigin = EitherOfDiverse<
478
	EnsureRoot<AccountId>,
479
	pallet_collective::EnsureProportionAtLeast<AccountId, OpenTechCommitteeInstance, 5, 9>,
480
>;
481

            
482
impl pallet_emergency_para_xcm::Config for Runtime {
483
	type RuntimeEvent = RuntimeEvent;
484
	type CheckAssociatedRelayNumber =
485
		cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
486
	type QueuePausedQuery = (MaintenanceMode, NarrowOriginToSibling<XcmpQueue>);
487
	type PausedThreshold = ConstU32<300>;
488
	type FastAuthorizeUpgradeOrigin = FastAuthorizeUpgradeOrigin;
489
	type PausedToNormalOrigin = ResumeXcmOrigin;
490
}
491

            
492
// Our AssetType. For now we only handle Xcm Assets
493
#[derive(
494
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
495
)]
496
pub enum AssetType {
497
	Xcm(xcm::v3::Location),
498
}
499
impl Default for AssetType {
500
	fn default() -> Self {
501
		Self::Xcm(xcm::v3::Location::here())
502
	}
503
}
504

            
505
impl From<xcm::v3::Location> for AssetType {
506
	fn from(location: xcm::v3::Location) -> Self {
507
		Self::Xcm(location)
508
	}
509
}
510

            
511
// This can be removed once we fully adopt xcm::v5 everywhere
512
impl TryFrom<Location> for AssetType {
513
	type Error = ();
514

            
515
77
	fn try_from(location: Location) -> Result<Self, Self::Error> {
516
77
		// Convert the V5 location to a V3 location
517
77
		match xcm::VersionedLocation::V5(location).into_version(xcm::v3::VERSION) {
518
77
			Ok(xcm::VersionedLocation::V3(loc)) => Ok(AssetType::Xcm(loc.into())),
519
			// Any other version or conversion error returns an error
520
			_ => Err(()),
521
		}
522
77
	}
523
}
524

            
525
impl Into<Option<xcm::v3::Location>> for AssetType {
526
	fn into(self) -> Option<xcm::v3::Location> {
527
		match self {
528
			Self::Xcm(location) => Some(location),
529
		}
530
	}
531
}
532

            
533
impl Into<Option<Location>> for AssetType {
534
	fn into(self) -> Option<Location> {
535
		match self {
536
			Self::Xcm(location) => {
537
				let versioned = xcm::VersionedLocation::V3(location);
538
				match versioned.into_version(xcm::latest::VERSION) {
539
					Ok(xcm::VersionedLocation::V5(loc)) => Some(loc),
540
					_ => None,
541
				}
542
			}
543
		}
544
	}
545
}
546

            
547
// Implementation on how to retrieve the AssetId from an AssetType
548
// We simply hash the AssetType and take the lowest 128 bits
549
impl From<AssetType> for AssetId {
550
294
	fn from(asset: AssetType) -> AssetId {
551
294
		match asset {
552
294
			AssetType::Xcm(id) => {
553
294
				let mut result: [u8; 16] = [0u8; 16];
554
294
				let hash: H256 = id.using_encoded(<Runtime as frame_system::Config>::Hashing::hash);
555
294
				result.copy_from_slice(&hash.as_fixed_bytes()[0..16]);
556
294
				u128::from_le_bytes(result)
557
294
			}
558
294
		}
559
294
	}
560
}
561

            
562
// Our currencyId. We distinguish for now between SelfReserve, and Others, defined by their Id.
563
#[derive(
564
21
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
565
)]
566
pub enum CurrencyId {
567
	// Our native token
568
	SelfReserve,
569
	// Assets representing other chains native tokens
570
	ForeignAsset(AssetId),
571
	// Erc20 token
572
	Erc20 { contract_address: H160 },
573
}
574

            
575
impl AccountIdToCurrencyId<AccountId, CurrencyId> for Runtime {
576
	fn account_to_currency_id(account: AccountId) -> Option<CurrencyId> {
577
		Some(match account {
578
			// the self-reserve currency is identified by the pallet-balances address
579
			a if a == H160::from_low_u64_be(2050).into() => CurrencyId::SelfReserve,
580
			// the rest of the currencies, by their corresponding erc20 address
581
			_ => match Runtime::account_to_asset_id(account) {
582
				// A foreign asset
583
				Some((_prefix, asset_id)) => CurrencyId::ForeignAsset(asset_id),
584
				// If no known prefix is identified, we consider that it's a "real" erc20 token
585
				// (i.e. managed by a real smart contract)
586
				None => CurrencyId::Erc20 {
587
					contract_address: account.into(),
588
				},
589
			},
590
		})
591
	}
592
}
593

            
594
// How to convert from CurrencyId to Location
595
pub struct CurrencyIdToLocation<AssetXConverter>(sp_std::marker::PhantomData<AssetXConverter>);
596
impl<AssetXConverter> sp_runtime::traits::Convert<CurrencyId, Option<Location>>
597
	for CurrencyIdToLocation<AssetXConverter>
598
where
599
	AssetXConverter: MaybeEquivalence<Location, AssetId>,
600
{
601
9
	fn convert(currency: CurrencyId) -> Option<Location> {
602
9
		match currency {
603
			// For now and until Xtokens is adapted to handle 0.9.16 version we use
604
			// the old anchoring here
605
			// This is not a problem in either cases, since the view of the destination
606
			// chain does not change
607
			// TODO! change this to NewAnchoringSelfReserve once xtokens is adapted for it
608
			CurrencyId::SelfReserve => {
609
1
				let multi: Location = SelfReserve::get();
610
1
				Some(multi)
611
			}
612
8
			CurrencyId::ForeignAsset(asset) => AssetXConverter::convert_back(&asset),
613
			CurrencyId::Erc20 { contract_address } => {
614
				let mut location = Erc20XcmBridgePalletLocation::get();
615
				location
616
					.push_interior(Junction::AccountKey20 {
617
						key: contract_address.0,
618
						network: None,
619
					})
620
					.ok();
621
				Some(location)
622
			}
623
		}
624
9
	}
625
}
626

            
627
parameter_types! {
628
	pub const BaseXcmWeight: Weight = Weight::from_parts(200_000_000u64, 0);
629
	pub const MaxAssetsForTransfer: usize = 2;
630

            
631
	// This is how we are going to detect whether the asset is a Reserve asset
632
	// This however is the chain part only
633
	pub SelfLocation: Location = Location::here();
634
	// We need this to be able to catch when someone is trying to execute a non-
635
	// cross-chain transfer in xtokens through the absolute path way
636
	pub SelfLocationAbsolute: Location = Location {
637
		parents:1,
638
		interior: [
639
			Parachain(ParachainInfo::parachain_id().into())
640
		].into()
641
	};
642
}
643

            
644
// 1 KSM should be enough
645
parameter_types! {
646
	pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
647
}
648

            
649
// For now we only allow to transact in the relay, although this might change in the future
650
// Transactors just defines the chains in which we allow transactions to be issued through
651
// xcm
652
#[derive(
653
14
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
654
)]
655
pub enum Transactors {
656
	Relay,
657
	AssetHub,
658
}
659

            
660
// Default for benchmarking
661
#[cfg(feature = "runtime-benchmarks")]
662
impl Default for Transactors {
663
	fn default() -> Self {
664
		Transactors::Relay
665
	}
666
}
667

            
668
impl TryFrom<u8> for Transactors {
669
	type Error = ();
670
	fn try_from(value: u8) -> Result<Self, Self::Error> {
671
		match value {
672
			0u8 => Ok(Transactors::Relay),
673
			1u8 => Ok(Transactors::AssetHub),
674
			_ => Err(()),
675
		}
676
	}
677
}
678

            
679
impl XcmTransact for Transactors {
680
35
	fn destination(self) -> Location {
681
35
		match self {
682
35
			Transactors::Relay => RelayLocation::get(),
683
			Transactors::AssetHub => AssetHubLocation::get(),
684
		}
685
35
	}
686

            
687
63
	fn utility_pallet_index(&self) -> u8 {
688
63
		match self {
689
63
			Transactors::Relay => pallet_xcm_transactor::RelayIndices::<Runtime>::get().utility,
690
			Transactors::AssetHub => pallet_xcm_transactor::ASSET_HUB_UTILITY_PALLET_INDEX,
691
		}
692
63
	}
693

            
694
	fn staking_pallet_index(&self) -> u8 {
695
		match self {
696
			Transactors::Relay => pallet_xcm_transactor::RelayIndices::<Runtime>::get().staking,
697
			Transactors::AssetHub => pallet_xcm_transactor::ASSET_HUB_STAKING_PALLET_INDEX,
698
		}
699
	}
700
}
701

            
702
pub type DerivativeAddressRegistrationOrigin =
703
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
704

            
705
impl pallet_xcm_transactor::Config for Runtime {
706
	type RuntimeEvent = RuntimeEvent;
707
	type Balance = Balance;
708
	type Transactor = Transactors;
709
	type DerivativeAddressRegistrationOrigin = DerivativeAddressRegistrationOrigin;
710
	type SovereignAccountDispatcherOrigin = EnsureRoot<AccountId>;
711
	type CurrencyId = CurrencyId;
712
	type AccountIdToLocation = AccountIdToLocation<AccountId>;
713
	type CurrencyIdToLocation = CurrencyIdToLocation<(EvmForeignAssets,)>;
714
	type XcmSender = XcmRouter;
715
	type SelfLocation = SelfLocation;
716
	type Weigher = XcmWeigher;
717
	type UniversalLocation = UniversalLocation;
718
	type BaseXcmWeight = BaseXcmWeight;
719
	type AssetTransactor = AssetTransactors;
720
	type ReserveProvider = AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
721
	type WeightInfo = moonriver_weights::pallet_xcm_transactor::WeightInfo<Runtime>;
722
	type HrmpManipulatorOrigin = GeneralAdminOrRoot;
723
	type HrmpOpenOrigin = FastGeneralAdminOrRoot;
724
	type MaxHrmpFee = xcm_builder::Case<MaxHrmpRelayFee>;
725
}
726

            
727
parameter_types! {
728
	// This is the relative view of erc20 assets.
729
	// Identified by this prefix + AccountKey20(contractAddress)
730
	// We use the RELATIVE multilocation
731
	pub Erc20XcmBridgePalletLocation: Location = Location {
732
		parents:0,
733
		interior: [
734
			PalletInstance(<Erc20XcmBridge as PalletInfoAccess>::index() as u8)
735
		].into()
736
	};
737

            
738
	// To be able to support almost all erc20 implementations,
739
	// we provide a sufficiently hight gas limit.
740
	pub Erc20XcmBridgeTransferGasLimit: u64 = 400_000;
741
}
742

            
743
impl pallet_erc20_xcm_bridge::Config for Runtime {
744
	type AccountIdConverter = LocationToH160;
745
	type Erc20MultilocationPrefix = Erc20XcmBridgePalletLocation;
746
	type Erc20TransferGasLimit = Erc20XcmBridgeTransferGasLimit;
747
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
748
}
749

            
750
pub struct AccountIdToH160;
751
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
752
448
	fn convert(account_id: AccountId) -> H160 {
753
448
		account_id.into()
754
448
	}
755
}
756

            
757
pub type ForeignAssetManagerOrigin = EitherOf<
758
	MapSuccessToXcm<EnsureXcm<AllowSiblingParachains>>,
759
	MapSuccessToGovernance<
760
		EitherOf<
761
			EnsureRoot<AccountId>,
762
			EitherOf<
763
				pallet_collective::EnsureProportionMoreThan<
764
					AccountId,
765
					OpenTechCommitteeInstance,
766
					5,
767
					9,
768
				>,
769
				EitherOf<
770
					governance::custom_origins::FastGeneralAdmin,
771
					governance::custom_origins::GeneralAdmin,
772
				>,
773
			>,
774
		>,
775
	>,
776
>;
777
impl pallet_moonbeam_foreign_assets::Config for Runtime {
778
	type AccountIdToH160 = AccountIdToH160;
779
	type AssetIdFilter = Everything;
780
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
781
	type ConvertLocation =
782
		SiblingParachainConvertsVia<polkadot_parachain::primitives::Sibling, AccountId>;
783
	type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin;
784
	type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin;
785
	type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin;
786
	type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin;
787
	type OnForeignAssetCreated = ();
788
	type MaxForeignAssets = ConstU32<256>;
789
	type RuntimeEvent = RuntimeEvent;
790
	type WeightInfo = moonriver_weights::pallet_moonbeam_foreign_assets::WeightInfo<Runtime>;
791
	type XcmLocationToH160 = LocationToH160;
792
	type ForeignAssetCreationDeposit = dynamic_params::xcm_config::ForeignAssetCreationDeposit;
793
	type Currency = Balances;
794
	type Balance = Balance;
795
}
796

            
797
pub struct AssetFeesFilter;
798
impl frame_support::traits::Contains<Location> for AssetFeesFilter {
799
49
	fn contains(location: &Location) -> bool {
800
49
		location.parent_count() > 0
801
49
			&& location.first_interior() != Erc20XcmBridgePalletLocation::get().first_interior()
802
49
	}
803
}
804

            
805
pub type AddAndEditSupportedAssetOrigin = EitherOfDiverse<
806
	EnsureRoot<AccountId>,
807
	EitherOfDiverse<
808
		pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
809
		EitherOf<
810
			governance::custom_origins::GeneralAdmin,
811
			governance::custom_origins::FastGeneralAdmin,
812
		>,
813
	>,
814
>;
815

            
816
pub type RemoveSupportedAssetOrigin = EitherOfDiverse<
817
	EnsureRoot<AccountId>,
818
	pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
819
>;
820

            
821
impl pallet_xcm_weight_trader::Config for Runtime {
822
	type AccountIdToLocation = AccountIdToLocation<AccountId>;
823
	type AddSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
824
	type AssetLocationFilter = AssetFeesFilter;
825
	type AssetTransactor = AssetTransactors;
826
	type Balance = Balance;
827
	type EditSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
828
	type NativeLocation = SelfReserve;
829
	type PauseSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
830
	type ResumeSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
831
	type RemoveSupportedAssetOrigin = RemoveSupportedAssetOrigin;
832
	type RuntimeEvent = RuntimeEvent;
833
	type WeightInfo = moonriver_weights::pallet_xcm_weight_trader::WeightInfo<Runtime>;
834
	type WeightToFee = <Runtime as pallet_transaction_payment::Config>::WeightToFee;
835
	type XcmFeesAccount = XcmFeesAccount;
836
	#[cfg(feature = "runtime-benchmarks")]
837
	type NotFilteredLocation = RelayLocation;
838
}
839

            
840
#[cfg(feature = "runtime-benchmarks")]
841
mod testing {
842
	use super::*;
843

            
844
	/// This From exists for benchmarking purposes. It has the potential side-effect of calling
845
	/// EvmForeignAssets::set_asset() and should NOT be used in any production code.
846
	impl From<Location> for CurrencyId {
847
		fn from(location: Location) -> CurrencyId {
848
			use sp_runtime::traits::MaybeEquivalence;
849

            
850
			// If it does not exist, for benchmarking purposes, we create the association
851
			let asset_id = if let Some(asset_id) = EvmForeignAssets::convert(&location) {
852
				asset_id
853
			} else {
854
				// Generate asset ID from location hash (similar to old AssetManager approach)
855
				let hash: H256 =
856
					location.using_encoded(<Runtime as frame_system::Config>::Hashing::hash);
857
				let mut result: [u8; 16] = [0u8; 16];
858
				result.copy_from_slice(&hash.as_fixed_bytes()[0..16]);
859
				let asset_id = u128::from_le_bytes(result);
860

            
861
				EvmForeignAssets::set_asset(location, asset_id);
862
				asset_id
863
			};
864

            
865
			CurrencyId::ForeignAsset(asset_id)
866
		}
867
	}
868
}
869

            
870
#[cfg(test)]
871
mod tests {
872
	use super::AssetHubMigrationStartsAtRelayBlock;
873

            
874
	#[test]
875
1
	fn check_type_parameter_key() {
876
1
		let implicit_key = AssetHubMigrationStartsAtRelayBlock::key();
877
1
		let explicit_key = sp_core::twox_128(b":AssetHubMigrationStartsAtRelayBlock:");
878
1
		assert_eq!(implicit_key, explicit_key);
879
1
	}
880
}