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
	governance, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm,
22
	Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, OpenTechCommitteeInstance,
23
	ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights,
24
	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, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily,
45
	EnsureXcmOrigin, FungibleAdapter as XcmCurrencyAdapter, FungiblesAdapter, HashedDescription,
46
	NoChecking, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
47
	SiblingParachainConvertsVia, SignedAccountKey20AsNative, SovereignSignedViaLocation,
48
	TakeWeightCredit, TrailingSetTopicAsId, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
49
};
50

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

            
57
use xcm_executor::traits::{CallDispatcher, ConvertLocation, JustTry};
58

            
59
use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
60
use pallet_xcm::EnsureXcm;
61
use xcm_primitives::{
62
	AbsoluteAndRelativeReserve, AccountIdToCurrencyId, AccountIdToLocation, AsAssetType,
63
	IsBridgedConcreteAssetFrom, MultiNativeAsset, SignedToAccountId20, UtilityAvailableCalls,
64
	UtilityEncodeCall, XcmTransact,
65
};
66

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

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

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

            
100
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
101
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
102
/// `Transact` in order to determine the dispatch Origin.
103
pub type LocationToAccountId = (
104
	// The parent (Relay-chain) origin converts to the default `AccountId`.
105
	ParentIsPreset<AccountId>,
106
	// Sibling parachain origins convert to AccountId via the `ParaId::into`.
107
	SiblingParachainConvertsVia<polkadot_parachain::primitives::Sibling, AccountId>,
108
	// If we receive a Location of type AccountKey20, just generate a native account
109
	AccountKey20Aliases<RelayNetwork, AccountId>,
110
	// Generate remote accounts according to polkadot standards
111
	HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
112
);
113

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

            
123
// The non-reserve fungible transactor type
124
// It will use pallet-assets, and the Id will be matched against AsAssetType
125
pub type ForeignFungiblesTransactor = FungiblesAdapter<
126
	// Use this fungibles implementation:
127
	super::Assets,
128
	// Use this currency when it is a fungible asset matching the given location or name:
129
	(
130
		ConvertedConcreteId<
131
			AssetId,
132
			Balance,
133
			AsAssetType<AssetId, AssetType, AssetManager>,
134
			JustTry,
135
		>,
136
	),
137
	// Do a simple punn to convert an AccountId20 Location into a native chain account ID:
138
	LocationToAccountId,
139
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
140
	AccountId,
141
	// We dont allow teleports.
142
	NoChecking,
143
	// We dont track any teleports
144
	(),
145
>;
146

            
147
/// The transactor for our own chain currency.
148
pub type LocalAssetTransactor = XcmCurrencyAdapter<
149
	// Use this currency:
150
	Balances,
151
	// Use this currency when it is a fungible asset matching any of the locations in
152
	// SelfReserveRepresentations
153
	xcm_builder::IsConcrete<SelfReserve>,
154
	// We can convert the MultiLocations with our converter above:
155
	LocationToAccountId,
156
	// Our chain's account ID type (we can't get away without mentioning it explicitly):
157
	AccountId,
158
	// We dont allow teleport
159
	(),
160
>;
161

            
162
// We use all transactors
163
// These correspond to
164
// SelfReserve asset, both pre and post 0.9.16
165
// Foreign assets
166
// Local assets, both pre and post 0.9.16
167
// We can remove the Old reanchor once
168
// we import https://github.com/open-web3-stack/open-runtime-module-library/pull/708
169
pub type AssetTransactors = (
170
	LocalAssetTransactor,
171
	EvmForeignAssets,
172
	ForeignFungiblesTransactor,
173
	Erc20XcmBridge,
174
);
175

            
176
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
177
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
178
/// biases the kind of local `Origin` it will become.
179
pub type XcmOriginToTransactDispatchOrigin = (
180
	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location
181
	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
182
	// foreign chains who want to have a local sovereign account on this chain which they control.
183
	SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
184
	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
185
	// recognised.
186
	RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
187
	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
188
	// recognised.
189
	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
190
	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
191
	pallet_xcm::XcmPassthrough<RuntimeOrigin>,
192
	// Xcm Origins defined by a Multilocation of type AccountKey20 can be converted to a 20 byte-
193
	// account local origin
194
	SignedAccountKey20AsNative<RelayNetwork, RuntimeOrigin>,
195
);
196

            
197
parameter_types! {
198
	/// Maximum number of instructions in a single XCM fragment. A sanity check against
199
	/// weight caculations getting too crazy.
200
	pub MaxInstructions: u32 = 100;
201
}
202

            
203
/// Xcm Weigher shared between multiple Xcm-related configs.
204
pub type XcmWeigher = WeightInfoBounds<
205
	moonbeam_xcm_benchmarks::weights::XcmWeight<Runtime, RuntimeCall>,
206
	RuntimeCall,
207
	MaxInstructions,
208
>;
209

            
210
pub type XcmBarrier = TrailingSetTopicAsId<(
211
	// Weight that is paid for may be consumed.
212
	TakeWeightCredit,
213
	// Expected responses are OK.
214
	AllowKnownQueryResponses<PolkadotXcm>,
215
	WithComputedOrigin<
216
		(
217
			// If the message is one that immediately attemps to pay for execution, then allow it.
218
			AllowTopLevelPaidExecutionFrom<Everything>,
219
			// Subscriptions for version tracking are OK.
220
			AllowSubscriptionsFrom<Everything>,
221
		),
222
		UniversalLocation,
223
		ConstU32<8>,
224
	>,
225
)>;
226

            
227
parameter_types! {
228
	/// Xcm fees will go to the treasury account
229
	pub XcmFeesAccount: AccountId = Treasury::account_id();
230
}
231

            
232
pub struct SafeCallFilter;
233
impl frame_support::traits::Contains<RuntimeCall> for SafeCallFilter {
234
	fn contains(_call: &RuntimeCall) -> bool {
235
		// TODO review
236
		// This needs to be addressed at EVM level
237
		true
238
	}
239
}
240

            
241
parameter_types! {
242
	/// Location of Asset Hub
243
	pub AssetHubLocation: Location = Location::new(1, [Parachain(1000)]);
244
	pub const RelayLocation: Location = Location::parent();
245
	pub RelayLocationFilter: AssetFilter = Wild(AllOf {
246
		fun: WildFungible,
247
		id: xcm::prelude::AssetId(RelayLocation::get()),
248
	});
249
	pub RelayChainNativeAssetFromAssetHub: (AssetFilter, Location) = (
250
		RelayLocationFilter::get(),
251
		AssetHubLocation::get()
252
	);
253
	pub const MaxAssetsIntoHolding: u32 = xcm_primitives::MAX_ASSETS;
254
}
255

            
256
type Reserves = (
257
	// Assets bridged from different consensus systems held in reserve on Asset Hub.
258
	IsBridgedConcreteAssetFrom<AssetHubLocation>,
259
	// Relaychain (DOT) from Asset Hub
260
	Case<RelayChainNativeAssetFromAssetHub>,
261
	// Assets which the reserve is the same as the origin.
262
	MultiNativeAsset<AbsoluteAndRelativeReserve<SelfLocationAbsolute>>,
263
);
264

            
265
// Our implementation of the Moonbeam Call
266
// Attachs the right origin in case the call is made to pallet-ethereum-xcm
267
#[cfg(not(feature = "evm-tracing"))]
268
moonbeam_runtime_common::impl_moonbeam_xcm_call!();
269
#[cfg(feature = "evm-tracing")]
270
16
moonbeam_runtime_common::impl_moonbeam_xcm_call_tracing!();
271

            
272
8
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
273

            
274
pub struct XcmExecutorConfig;
275
impl xcm_executor::Config for XcmExecutorConfig {
276
	type RuntimeCall = RuntimeCall;
277
	type XcmSender = XcmRouter;
278
	// How to withdraw and deposit an asset.
279
	type AssetTransactor = AssetTransactors;
280
	type OriginConverter = XcmOriginToTransactDispatchOrigin;
281
	// Filter to the reserve withdraw operations
282
	// Whenever the reserve matches the relative or absolute value
283
	// of our chain, we always return the relative reserve
284
	type IsReserve = Reserves;
285
	type IsTeleporter = (); // No teleport
286
	type UniversalLocation = UniversalLocation;
287
	type Barrier = XcmBarrier;
288
	type Weigher = XcmWeigher;
289
	// As trader we use the XcmWeightTrader pallet.
290
	// For each foreign asset, the fee is computed based on its relative price (also
291
	// stored in the XcmWeightTrader pallet) against the native asset.
292
	// For the native asset fee is computed using WeightToFee implementation.
293
	type Trader = pallet_xcm_weight_trader::Trader<Runtime>;
294
	type ResponseHandler = PolkadotXcm;
295
	type SubscriptionService = PolkadotXcm;
296
	type AssetTrap = pallet_erc20_xcm_bridge::AssetTrapWrapper<PolkadotXcm, Runtime>;
297
	type AssetClaims = PolkadotXcm;
298
	type CallDispatcher = MoonbeamCall;
299
	type PalletInstancesInfo = crate::AllPalletsWithSystem;
300
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
301
	type AssetLocker = ();
302
	type AssetExchanger = ();
303
	type FeeManager = ();
304
	type MessageExporter = ();
305
	type UniversalAliases = Nothing;
306
	type SafeCallFilter = SafeCallFilter;
307
	type Aliasers = Nothing;
308
	type TransactionalProcessor = pallet_ethereum_xcm::XcmEthTransactionalProcessor;
309
	type HrmpNewChannelOpenRequestHandler = ();
310
	type HrmpChannelAcceptedHandler = ();
311
	type HrmpChannelClosingHandler = ();
312
	type XcmRecorder = PolkadotXcm;
313
}
314

            
315
type XcmExecutor = pallet_erc20_xcm_bridge::XcmExecutorWrapper<
316
	XcmExecutorConfig,
317
	xcm_executor::XcmExecutor<XcmExecutorConfig>,
318
>;
319

            
320
// Converts a Signed Local Origin into a Location
321
pub type LocalOriginToLocation = SignedToAccountId20<RuntimeOrigin, AccountId, RelayNetwork>;
322

            
323
/// The means for routing XCM messages which are not for local execution into the right message
324
/// queues.
325
pub type XcmRouter = WithUniqueTopic<(
326
	// Two routers - use UMP to communicate with the relay chain:
327
	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
328
	// ..and XCMP to communicate with the sibling chains.
329
	XcmpQueue,
330
)>;
331

            
332
impl pallet_xcm::Config for Runtime {
333
	type RuntimeEvent = RuntimeEvent;
334
	type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
335
	type XcmRouter = XcmRouter;
336
	type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
337
	type XcmExecuteFilter = Nothing;
338
	type XcmExecutor = XcmExecutor;
339
	type XcmTeleportFilter = Nothing;
340
	type XcmReserveTransferFilter = Everything;
341
	type Weigher = XcmWeigher;
342
	type UniversalLocation = UniversalLocation;
343
	type RuntimeOrigin = RuntimeOrigin;
344
	type RuntimeCall = RuntimeCall;
345
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
346
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
347
	type Currency = Balances;
348
	type CurrencyMatcher = ();
349
	type TrustedLockers = ();
350
	type SovereignAccountOf = LocationToAccountId;
351
	type MaxLockers = ConstU32<8>;
352
	type MaxRemoteLockConsumers = ConstU32<0>;
353
	type RemoteLockConsumerIdentifier = ();
354
	type WeightInfo = moonriver_weights::pallet_xcm::WeightInfo<Runtime>;
355
	type AdminOrigin = EnsureRoot<AccountId>;
356
}
357

            
358
impl cumulus_pallet_xcm::Config for Runtime {
359
	type RuntimeEvent = RuntimeEvent;
360
	type XcmExecutor = XcmExecutor;
361
}
362

            
363
impl cumulus_pallet_xcmp_queue::Config for Runtime {
364
	type RuntimeEvent = RuntimeEvent;
365
	type ChannelInfo = ParachainSystem;
366
	type VersionWrapper = PolkadotXcm;
367
	type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
368
	type MaxInboundSuspended = sp_core::ConstU32<1_000>;
369
	type ControllerOrigin = EnsureRoot<AccountId>;
370
	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
371
	type WeightInfo = moonriver_weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
372
	type PriceForSiblingDelivery = polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery<
373
		cumulus_primitives_core::ParaId,
374
	>;
375
	type MaxActiveOutboundChannels = ConstU32<128>;
376
	// Most on-chain HRMP channels are configured to use 102400 bytes of max message size, so we
377
	// need to set the page size larger than that until we reduce the channel size on-chain.
378
	type MaxPageSize = MessageQueueHeapSize;
379
}
380

            
381
parameter_types! {
382
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
383
}
384

            
385
parameter_types! {
386
	/// The amount of weight (if any) which should be provided to the message queue for
387
	/// servicing enqueued items.
388
	///
389
	/// This may be legitimately `None` in the case that you will call
390
	/// `ServiceQueues::service_queues` manually.
391
	pub MessageQueueServiceWeight: Weight =
392
		Perbill::from_percent(25) * RuntimeBlockWeights::get().max_block;
393
	/// The maximum number of stale pages (i.e. of overweight messages) allowed before culling
394
	/// can happen. Once there are more stale pages than this, then historical pages may be
395
	/// dropped, even if they contain unprocessed overweight messages.
396
	pub const MessageQueueMaxStale: u32 = 8;
397
	/// The size of the page; this implies the maximum message size which can be sent.
398
	///
399
	/// A good value depends on the expected message sizes, their weights, the weight that is
400
	/// available for processing them and the maximal needed message size. The maximal message
401
	/// size is slightly lower than this as defined by [`MaxMessageLenOf`].
402
	pub const MessageQueueHeapSize: u32 = 103 * 1024;
403
}
404

            
405
impl pallet_message_queue::Config for Runtime {
406
	type RuntimeEvent = RuntimeEvent;
407
	#[cfg(feature = "runtime-benchmarks")]
408
	type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
409
		cumulus_primitives_core::AggregateMessageOrigin,
410
	>;
411
	#[cfg(not(feature = "runtime-benchmarks"))]
412
	type MessageProcessor = pallet_ethereum_xcm::MessageProcessorWrapper<
413
		xcm_builder::ProcessXcmMessage<AggregateMessageOrigin, XcmExecutor, RuntimeCall>,
414
	>;
415
	type Size = u32;
416
	type HeapSize = MessageQueueHeapSize;
417
	type MaxStale = MessageQueueMaxStale;
418
	type ServiceWeight = MessageQueueServiceWeight;
419
	// The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
420
	type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
421
	// NarrowOriginToSibling calls XcmpQueue's is_paused if Origin is sibling. Allows all other origins
422
	type QueuePausedQuery = EmergencyParaXcm;
423
	type WeightInfo = moonriver_weights::pallet_message_queue::WeightInfo<Runtime>;
424
	type IdleMaxServiceWeight = MessageQueueServiceWeight;
425
}
426

            
427
pub type FastAuthorizeUpgradeOrigin = EitherOfDiverse<
428
	EnsureRoot<AccountId>,
429
	pallet_collective::EnsureProportionAtLeast<AccountId, OpenTechCommitteeInstance, 5, 9>,
430
>;
431

            
432
pub type ResumeXcmOrigin = EitherOfDiverse<
433
	EnsureRoot<AccountId>,
434
	pallet_collective::EnsureProportionAtLeast<AccountId, OpenTechCommitteeInstance, 5, 9>,
435
>;
436

            
437
impl pallet_emergency_para_xcm::Config for Runtime {
438
	type RuntimeEvent = RuntimeEvent;
439
	type CheckAssociatedRelayNumber =
440
		cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
441
	type QueuePausedQuery = (MaintenanceMode, NarrowOriginToSibling<XcmpQueue>);
442
	type PausedThreshold = ConstU32<300>;
443
	type FastAuthorizeUpgradeOrigin = FastAuthorizeUpgradeOrigin;
444
	type PausedToNormalOrigin = ResumeXcmOrigin;
445
}
446

            
447
// Our AssetType. For now we only handle Xcm Assets
448
8
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
449
pub enum AssetType {
450
27
	Xcm(xcm::v3::Location),
451
}
452
impl Default for AssetType {
453
	fn default() -> Self {
454
		Self::Xcm(xcm::v3::Location::here())
455
	}
456
}
457

            
458
impl From<xcm::v3::Location> for AssetType {
459
576
	fn from(location: xcm::v3::Location) -> Self {
460
576
		Self::Xcm(location)
461
576
	}
462
}
463

            
464
// This can be removed once we fully adopt xcm::v4 everywhere
465
impl TryFrom<Location> for AssetType {
466
	type Error = ();
467
	fn try_from(location: Location) -> Result<Self, Self::Error> {
468
		Ok(Self::Xcm(location.try_into()?))
469
	}
470
}
471

            
472
impl Into<Option<xcm::v3::Location>> for AssetType {
473
176
	fn into(self) -> Option<xcm::v3::Location> {
474
176
		match self {
475
176
			Self::Xcm(location) => Some(location),
476
176
		}
477
176
	}
478
}
479

            
480
impl Into<Option<Location>> for AssetType {
481
	fn into(self) -> Option<Location> {
482
		match self {
483
			Self::Xcm(location) => {
484
				xcm_builder::WithLatestLocationConverter::convert_back(&location)
485
			}
486
		}
487
	}
488
}
489

            
490
// Implementation on how to retrieve the AssetId from an AssetType
491
// We simply hash the AssetType and take the lowest 128 bits
492
impl From<AssetType> for AssetId {
493
752
	fn from(asset: AssetType) -> AssetId {
494
752
		match asset {
495
752
			AssetType::Xcm(id) => {
496
752
				let mut result: [u8; 16] = [0u8; 16];
497
752
				let hash: H256 = id.using_encoded(<Runtime as frame_system::Config>::Hashing::hash);
498
752
				result.copy_from_slice(&hash.as_fixed_bytes()[0..16]);
499
752
				u128::from_le_bytes(result)
500
752
			}
501
752
		}
502
752
	}
503
}
504

            
505
// Our currencyId. We distinguish for now between SelfReserve, and Others, defined by their Id.
506
24
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
507
pub enum CurrencyId {
508
	// Our native token
509
	SelfReserve,
510
	// Assets representing other chains native tokens
511
	ForeignAsset(AssetId),
512
	// Erc20 token
513
	Erc20 { contract_address: H160 },
514
}
515

            
516
impl AccountIdToCurrencyId<AccountId, CurrencyId> for Runtime {
517
16
	fn account_to_currency_id(account: AccountId) -> Option<CurrencyId> {
518
16
		Some(match account {
519
			// the self-reserve currency is identified by the pallet-balances address
520
16
			a if a == H160::from_low_u64_be(2050).into() => CurrencyId::SelfReserve,
521
			// the rest of the currencies, by their corresponding erc20 address
522
16
			_ => match Runtime::account_to_asset_id(account) {
523
				// A foreign asset
524
16
				Some((_prefix, asset_id)) => CurrencyId::ForeignAsset(asset_id),
525
				// If no known prefix is identified, we consider that it's a "real" erc20 token
526
				// (i.e. managed by a real smart contract)
527
				None => CurrencyId::Erc20 {
528
					contract_address: account.into(),
529
				},
530
			},
531
		})
532
16
	}
533
}
534

            
535
// How to convert from CurrencyId to Location
536
pub struct CurrencyIdToLocation<AssetXConverter>(sp_std::marker::PhantomData<AssetXConverter>);
537
impl<AssetXConverter> sp_runtime::traits::Convert<CurrencyId, Option<Location>>
538
	for CurrencyIdToLocation<AssetXConverter>
539
where
540
	AssetXConverter: MaybeEquivalence<Location, AssetId>,
541
{
542
6
	fn convert(currency: CurrencyId) -> Option<Location> {
543
6
		match currency {
544
			// For now and until Xtokens is adapted to handle 0.9.16 version we use
545
			// the old anchoring here
546
			// This is not a problem in either cases, since the view of the destination
547
			// chain does not change
548
			// TODO! change this to NewAnchoringSelfReserve once xtokens is adapted for it
549
			CurrencyId::SelfReserve => {
550
				let multi: Location = SelfReserve::get();
551
				Some(multi)
552
			}
553
6
			CurrencyId::ForeignAsset(asset) => AssetXConverter::convert_back(&asset),
554
			CurrencyId::Erc20 { contract_address } => {
555
				let mut location = Erc20XcmBridgePalletLocation::get();
556
				location
557
					.push_interior(Junction::AccountKey20 {
558
						key: contract_address.0,
559
						network: None,
560
					})
561
					.ok();
562
				Some(location)
563
			}
564
		}
565
6
	}
566
}
567

            
568
parameter_types! {
569
	pub const BaseXcmWeight: Weight = Weight::from_parts(200_000_000u64, 0);
570
	pub const MaxAssetsForTransfer: usize = 2;
571

            
572
	// This is how we are going to detect whether the asset is a Reserve asset
573
	// This however is the chain part only
574
	pub SelfLocation: Location = Location::here();
575
	// We need this to be able to catch when someone is trying to execute a non-
576
	// cross-chain transfer in xtokens through the absolute path way
577
	pub SelfLocationAbsolute: Location = Location {
578
		parents:1,
579
		interior: [
580
			Parachain(ParachainInfo::parachain_id().into())
581
		].into()
582
	};
583
}
584

            
585
// 1 KSM should be enough
586
parameter_types! {
587
	pub MaxHrmpRelayFee: Asset = (Location::parent(), 1_000_000_000_000u128).into();
588
}
589

            
590
// For now we only allow to transact in the relay, although this might change in the future
591
// Transactors just defines the chains in which we allow transactions to be issued through
592
// xcm
593
8
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
594
pub enum Transactors {
595
	Relay,
596
}
597

            
598
// Default for benchmarking
599
#[cfg(feature = "runtime-benchmarks")]
600
impl Default for Transactors {
601
	fn default() -> Self {
602
		Transactors::Relay
603
	}
604
}
605

            
606
impl TryFrom<u8> for Transactors {
607
	type Error = ();
608
	fn try_from(value: u8) -> Result<Self, Self::Error> {
609
		match value {
610
			0u8 => Ok(Transactors::Relay),
611
			_ => Err(()),
612
		}
613
	}
614
}
615

            
616
impl UtilityEncodeCall for Transactors {
617
16
	fn encode_call(self, call: UtilityAvailableCalls) -> Vec<u8> {
618
16
		match self {
619
16
			Transactors::Relay => pallet_xcm_transactor::Pallet::<Runtime>::encode_call(
620
16
				pallet_xcm_transactor::Pallet(sp_std::marker::PhantomData::<Runtime>),
621
16
				call,
622
16
			),
623
16
		}
624
16
	}
625
}
626

            
627
impl XcmTransact for Transactors {
628
16
	fn destination(self) -> Location {
629
16
		match self {
630
16
			Transactors::Relay => Location::parent(),
631
16
		}
632
16
	}
633
}
634

            
635
pub type DerivativeAddressRegistrationOrigin =
636
	EitherOfDiverse<EnsureRoot<AccountId>, governance::custom_origins::GeneralAdmin>;
637

            
638
impl pallet_xcm_transactor::Config for Runtime {
639
	type RuntimeEvent = RuntimeEvent;
640
	type Balance = Balance;
641
	type Transactor = Transactors;
642
	type DerivativeAddressRegistrationOrigin = DerivativeAddressRegistrationOrigin;
643
	type SovereignAccountDispatcherOrigin = EnsureRoot<AccountId>;
644
	type CurrencyId = CurrencyId;
645
	type AccountIdToLocation = AccountIdToLocation<AccountId>;
646
	type CurrencyIdToLocation = CurrencyIdToLocation<(
647
		EvmForeignAssets,
648
		AsAssetType<AssetId, AssetType, AssetManager>,
649
	)>;
650
	type XcmSender = XcmRouter;
651
	type SelfLocation = SelfLocation;
652
	type Weigher = XcmWeigher;
653
	type UniversalLocation = UniversalLocation;
654
	type BaseXcmWeight = BaseXcmWeight;
655
	type AssetTransactor = AssetTransactors;
656
	type ReserveProvider = AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
657
	type WeightInfo = moonriver_weights::pallet_xcm_transactor::WeightInfo<Runtime>;
658
	type HrmpManipulatorOrigin = GeneralAdminOrRoot;
659
	type HrmpOpenOrigin = FastGeneralAdminOrRoot;
660
	type MaxHrmpFee = xcm_builder::Case<MaxHrmpRelayFee>;
661
}
662

            
663
parameter_types! {
664
	// This is the relative view of erc20 assets.
665
	// Identified by this prefix + AccountKey20(contractAddress)
666
	// We use the RELATIVE multilocation
667
	pub Erc20XcmBridgePalletLocation: Location = Location {
668
		parents:0,
669
		interior: [
670
			PalletInstance(<Erc20XcmBridge as PalletInfoAccess>::index() as u8)
671
		].into()
672
	};
673

            
674
	// To be able to support almost all erc20 implementations,
675
	// we provide a sufficiently hight gas limit.
676
	pub Erc20XcmBridgeTransferGasLimit: u64 = 400_000;
677
}
678

            
679
impl pallet_erc20_xcm_bridge::Config for Runtime {
680
	type AccountIdConverter = LocationToH160;
681
	type Erc20MultilocationPrefix = Erc20XcmBridgePalletLocation;
682
	type Erc20TransferGasLimit = Erc20XcmBridgeTransferGasLimit;
683
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
684
}
685

            
686
pub struct AccountIdToH160;
687
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
688
48
	fn convert(account_id: AccountId) -> H160 {
689
48
		account_id.into()
690
48
	}
691
}
692

            
693
pub struct EvmForeignAssetIdFilter;
694
impl frame_support::traits::Contains<AssetId> for EvmForeignAssetIdFilter {
695
8
	fn contains(asset_id: &AssetId) -> bool {
696
8
		use xcm_primitives::AssetTypeGetter as _;
697
8
		// We should return true only if the AssetId doesn't exist in AssetManager
698
8
		AssetManager::get_asset_type(*asset_id).is_none()
699
8
	}
700
}
701

            
702
pub type ForeignAssetManagerOrigin = EitherOf<
703
	MapSuccessToXcm<EnsureXcm<AllowSiblingParachains>>,
704
	MapSuccessToGovernance<
705
		EitherOf<
706
			EnsureRoot<AccountId>,
707
			EitherOf<
708
				pallet_collective::EnsureProportionMoreThan<
709
					AccountId,
710
					OpenTechCommitteeInstance,
711
					5,
712
					9,
713
				>,
714
				EitherOf<
715
					governance::custom_origins::FastGeneralAdmin,
716
					governance::custom_origins::GeneralAdmin,
717
				>,
718
			>,
719
		>,
720
	>,
721
>;
722
impl pallet_moonbeam_foreign_assets::Config for Runtime {
723
	type AccountIdToH160 = AccountIdToH160;
724
	type AssetIdFilter = EvmForeignAssetIdFilter;
725
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
726
	type ConvertLocation =
727
		SiblingParachainConvertsVia<polkadot_parachain::primitives::Sibling, AccountId>;
728
	type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin;
729
	type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin;
730
	type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin;
731
	type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin;
732
	type OnForeignAssetCreated = ();
733
	type MaxForeignAssets = ConstU32<256>;
734
	type RuntimeEvent = RuntimeEvent;
735
	type WeightInfo = moonriver_weights::pallet_moonbeam_foreign_assets::WeightInfo<Runtime>;
736
	type XcmLocationToH160 = LocationToH160;
737
	type ForeignAssetCreationDeposit = dynamic_params::xcm_config::ForeignAssetCreationDeposit;
738
	type Currency = Balances;
739
	type Balance = Balance;
740
}
741

            
742
pub struct AssetFeesFilter;
743
impl frame_support::traits::Contains<Location> for AssetFeesFilter {
744
	fn contains(location: &Location) -> bool {
745
		location.parent_count() > 0
746
			&& location.first_interior() != Erc20XcmBridgePalletLocation::get().first_interior()
747
	}
748
}
749

            
750
pub type AddAndEditSupportedAssetOrigin = EitherOfDiverse<
751
	EnsureRoot<AccountId>,
752
	EitherOfDiverse<
753
		pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
754
		EitherOf<
755
			governance::custom_origins::GeneralAdmin,
756
			governance::custom_origins::FastGeneralAdmin,
757
		>,
758
	>,
759
>;
760

            
761
pub type RemoveSupportedAssetOrigin = EitherOfDiverse<
762
	EnsureRoot<AccountId>,
763
	pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
764
>;
765

            
766
impl pallet_xcm_weight_trader::Config for Runtime {
767
	type AccountIdToLocation = AccountIdToLocation<AccountId>;
768
	type AddSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
769
	type AssetLocationFilter = AssetFeesFilter;
770
	type AssetTransactor = AssetTransactors;
771
	type Balance = Balance;
772
	type EditSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
773
	type NativeLocation = SelfReserve;
774
	type PauseSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
775
	type ResumeSupportedAssetOrigin = AddAndEditSupportedAssetOrigin;
776
	type RemoveSupportedAssetOrigin = RemoveSupportedAssetOrigin;
777
	type RuntimeEvent = RuntimeEvent;
778
	type WeightInfo = moonriver_weights::pallet_xcm_weight_trader::WeightInfo<Runtime>;
779
	type WeightToFee = <Runtime as pallet_transaction_payment::Config>::WeightToFee;
780
	type XcmFeesAccount = XcmFeesAccount;
781
	#[cfg(feature = "runtime-benchmarks")]
782
	type NotFilteredLocation = RelayLocation;
783
}
784

            
785
#[cfg(feature = "runtime-benchmarks")]
786
mod testing {
787
	use super::*;
788
	use xcm_builder::WithLatestLocationConverter;
789

            
790
	/// This From exists for benchmarking purposes. It has the potential side-effect of calling
791
	/// AssetManager::set_asset_type_asset_id() and should NOT be used in any production code.
792
	impl From<Location> for CurrencyId {
793
		fn from(location: Location) -> CurrencyId {
794
			use xcm_primitives::AssetTypeGetter;
795

            
796
			// If it does not exist, for benchmarking purposes, we create the association
797
			let asset_id = if let Some(asset_id) =
798
				AsAssetType::<AssetId, AssetType, AssetManager>::convert_location(&location)
799
			{
800
				asset_id
801
			} else {
802
				let asset_type = AssetType::Xcm(
803
					WithLatestLocationConverter::convert(&location).expect("convert to v3"),
804
				);
805
				let asset_id: AssetId = asset_type.clone().into();
806
				AssetManager::set_asset_type_asset_id(asset_type, asset_id);
807
				asset_id
808
			};
809

            
810
			CurrencyId::ForeignAsset(asset_id)
811
		}
812
	}
813
}