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, UtilityAvailableCalls,
68
	UtilityEncodeCall, XcmTransact,
69
};
70

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

            
83
parameter_types! {
84
	// The network Id of the relay
85
	pub const RelayNetwork: NetworkId = NetworkId::Kusama;
86
	// The relay chain Origin type
87
	pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
88
	// The universal location within the global consensus system
89
	pub UniversalLocation: InteriorLocation =
90
		[GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
91

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
252
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
253

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
650
// For now we only allow to transact in the relay, although this might change in the future
651
// Transactors just defines the chains in which we allow transactions to be issued through
652
// xcm
653
#[derive(
654
7
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
655
)]
656
pub enum Transactors {
657
	Relay,
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
			_ => Err(()),
674
		}
675
	}
676
}
677

            
678
impl UtilityEncodeCall for Transactors {
679
14
	fn encode_call(self, call: UtilityAvailableCalls) -> Vec<u8> {
680
14
		match self {
681
14
			Transactors::Relay => pallet_xcm_transactor::Pallet::<Runtime>::encode_call(
682
14
				pallet_xcm_transactor::Pallet(sp_std::marker::PhantomData::<Runtime>),
683
14
				call,
684
14
			),
685
14
		}
686
14
	}
687
}
688

            
689
impl XcmTransact for Transactors {
690
14
	fn destination(self) -> Location {
691
14
		match self {
692
14
			Transactors::Relay => Location::parent(),
693
14
		}
694
14
	}
695
}
696

            
697
pub type DerivativeAddressRegistrationOrigin =
698
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
699

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

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

            
733
	// To be able to support almost all erc20 implementations,
734
	// we provide a sufficiently hight gas limit.
735
	pub Erc20XcmBridgeTransferGasLimit: u64 = 400_000;
736
}
737

            
738
impl pallet_erc20_xcm_bridge::Config for Runtime {
739
	type AccountIdConverter = LocationToH160;
740
	type Erc20MultilocationPrefix = Erc20XcmBridgePalletLocation;
741
	type Erc20TransferGasLimit = Erc20XcmBridgeTransferGasLimit;
742
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
743
}
744

            
745
pub struct AccountIdToH160;
746
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
747
448
	fn convert(account_id: AccountId) -> H160 {
748
448
		account_id.into()
749
448
	}
750
}
751

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

            
792
pub struct AssetFeesFilter;
793
impl frame_support::traits::Contains<Location> for AssetFeesFilter {
794
49
	fn contains(location: &Location) -> bool {
795
49
		location.parent_count() > 0
796
49
			&& location.first_interior() != Erc20XcmBridgePalletLocation::get().first_interior()
797
49
	}
798
}
799

            
800
pub type AddAndEditSupportedAssetOrigin = EitherOfDiverse<
801
	EnsureRoot<AccountId>,
802
	EitherOfDiverse<
803
		pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
804
		EitherOf<
805
			governance::custom_origins::GeneralAdmin,
806
			governance::custom_origins::FastGeneralAdmin,
807
		>,
808
	>,
809
>;
810

            
811
pub type RemoveSupportedAssetOrigin = EitherOfDiverse<
812
	EnsureRoot<AccountId>,
813
	pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
814
>;
815

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

            
835
#[cfg(feature = "runtime-benchmarks")]
836
mod testing {
837
	use super::*;
838

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

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

            
856
				EvmForeignAssets::set_asset(location, asset_id);
857
				asset_id
858
			};
859

            
860
			CurrencyId::ForeignAsset(asset_id)
861
		}
862
	}
863
}
864

            
865
#[cfg(test)]
866
mod tests {
867
	use super::AssetHubMigrationStartsAtRelayBlock;
868

            
869
	#[test]
870
1
	fn check_type_parameter_key() {
871
1
		let implicit_key = AssetHubMigrationStartsAtRelayBlock::key();
872
1
		let explicit_key = sp_core::twox_128(b":AssetHubMigrationStartsAtRelayBlock:");
873
1
		assert_eq!(implicit_key, explicit_key);
874
1
	}
875
}