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::moonbase_weights;
21
use super::{
22
	governance, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm,
23
	Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, ParachainInfo,
24
	ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent,
25
	RuntimeOrigin, Treasury, XcmpQueue,
26
};
27
use crate::OpenTechCommitteeInstance;
28
use moonkit_xcm_primitives::AccountIdAssetIdConversion;
29
use sp_runtime::{
30
	traits::{Hash as THash, MaybeEquivalence, PostDispatchInfoOf},
31
	DispatchErrorWithPostInfo,
32
};
33

            
34
use frame_support::{
35
	parameter_types,
36
	traits::{EitherOf, EitherOfDiverse, Everything, Nothing, PalletInfoAccess, TransformOrigin},
37
};
38

            
39
use frame_system::{EnsureRoot, RawOrigin};
40
use sp_core::{ConstU32, H160, H256};
41
use sp_weights::Weight;
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

            
53
use xcm::latest::prelude::{
54
	AllOf, Asset, AssetFilter, GlobalConsensus, InteriorLocation, Junction, Location, NetworkId,
55
	PalletInstance, Parachain, Wild, WildFungible,
56
};
57

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

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

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

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

            
89

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

            
102
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
103
/// when determining ownership of accounts for asset transacting, when attempting to use XCM
104
/// `Transact` in order to determine the dispatch Origin, and when validating foreign assets
105
/// creation and ownership through the moonbeam_foreign_assets pallet.
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
	// Generate remote accounts according to polkadot standards
114
	HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
115
);
116

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

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

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

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

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

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

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

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

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

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

            
242
16
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
243

            
244
pub struct SafeCallFilter;
245
impl frame_support::traits::Contains<RuntimeCall> for SafeCallFilter {
246
	fn contains(_call: &RuntimeCall) -> bool {
247
		// TODO review
248
		// This needs to be addressed at EVM level
249
		true
250
	}
251
}
252

            
253
parameter_types! {
254
	/// Location of Asset Hub
255
	pub AssetHubLocation: Location = Location::new(1, [Parachain(1001)]);
256
	pub const RelayLocation: Location = Location::parent();
257
	pub RelayLocationFilter: AssetFilter = Wild(AllOf {
258
		fun: WildFungible,
259
		id: xcm::prelude::AssetId(RelayLocation::get()),
260
	});
261
	pub RelayChainNativeAssetFromAssetHub: (AssetFilter, Location) = (
262
		RelayLocationFilter::get(),
263
		AssetHubLocation::get()
264
	);
265
	pub const MaxAssetsIntoHolding: u32 = xcm_primitives::MAX_ASSETS;
266
}
267

            
268
type Reserves = (
269
	// Assets bridged from different consensus systems held in reserve on Asset Hub.
270
	IsBridgedConcreteAssetFrom<AssetHubLocation>,
271
	// Relaychain (DOT) from Asset Hub
272
	Case<RelayChainNativeAssetFromAssetHub>,
273
	// Assets which the reserve is the same as the origin.
274
	MultiNativeAsset<AbsoluteAndRelativeReserve<SelfLocationAbsolute>>,
275
);
276

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

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

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

            
330
type XcmExecutor = pallet_erc20_xcm_bridge::XcmExecutorWrapper<
331
	XcmExecutorConfig,
332
	xcm_executor::XcmExecutor<XcmExecutorConfig>,
333
>;
334

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

            
361
impl cumulus_pallet_xcm::Config for Runtime {
362
	type RuntimeEvent = RuntimeEvent;
363
	type XcmExecutor = XcmExecutor;
364
}
365

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

            
384
parameter_types! {
385
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
386
}
387

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

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

            
430
pub type FastAuthorizeUpgradeOrigin = EitherOfDiverse<
431
	EnsureRoot<AccountId>,
432
	pallet_collective::EnsureProportionAtLeast<AccountId, OpenTechCommitteeInstance, 5, 9>,
433
>;
434

            
435
pub type ResumeXcmOrigin = EitherOfDiverse<
436
	EnsureRoot<AccountId>,
437
	pallet_collective::EnsureProportionAtLeast<AccountId, OpenTechCommitteeInstance, 5, 9>,
438
>;
439

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

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

            
461
impl From<xcm::v3::Location> for AssetType {
462
536
	fn from(location: xcm::v3::Location) -> Self {
463
536
		Self::Xcm(location)
464
536
	}
465
}
466

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

            
475
impl Into<Option<xcm::v3::Location>> for AssetType {
476
136
	fn into(self) -> Option<xcm::v3::Location> {
477
136
		match self {
478
136
			Self::Xcm(location) => Some(location),
479
136
		}
480
136
	}
481
}
482

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

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

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

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

            
538
// How to convert from CurrencyId to Location
539
pub struct CurrencyIdToLocation<AssetXConverter>(sp_std::marker::PhantomData<AssetXConverter>);
540
impl<AssetXConverter> sp_runtime::traits::Convert<CurrencyId, Option<Location>>
541
	for CurrencyIdToLocation<AssetXConverter>
542
where
543
	AssetXConverter: MaybeEquivalence<Location, AssetId>,
544
{
545
4
	fn convert(currency: CurrencyId) -> Option<Location> {
546
4
		match currency {
547
			CurrencyId::SelfReserve => {
548
1
				let multi: Location = SelfReserve::get();
549
1
				Some(multi)
550
			}
551
3
			CurrencyId::ForeignAsset(asset) => AssetXConverter::convert_back(&asset),
552
			CurrencyId::Erc20 { contract_address } => {
553
				let mut location = Erc20XcmBridgePalletLocation::get();
554
				location
555
					.push_interior(Junction::AccountKey20 {
556
						key: contract_address.0,
557
						network: None,
558
					})
559
					.ok();
560
				Some(location)
561
			}
562
		}
563
4
	}
564
}
565

            
566
parameter_types! {
567
	pub const BaseXcmWeight: Weight
568
		= Weight::from_parts(200_000_000u64, 0);
569
	pub const MaxAssetsForTransfer: usize = 2;
570
	// This is how we are going to detect whether the asset is a Reserve asset
571
	// This however is the chain part only
572
	pub SelfLocation: Location = Location::here();
573
	// We need this to be able to catch when someone is trying to execute a non-
574
	// cross-chain transfer in xtokens through the absolute path way
575
	pub SelfLocationAbsolute: Location = Location {
576
		parents:1,
577
		interior: [
578
			Parachain(ParachainInfo::parachain_id().into())
579
		].into()
580
	};
581

            
582
}
583

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

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

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

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

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

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

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

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

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

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

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

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

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

            
701
pub type ForeignAssetManagerOrigin = EitherOf<
702
	MapSuccessToXcm<EnsureXcm<AllowSiblingParachains>>,
703
	MapSuccessToGovernance<
704
		EitherOf<
705
			EnsureRoot<AccountId>,
706
			EitherOf<
707
				pallet_collective::EnsureProportionMoreThan<
708
					AccountId,
709
					OpenTechCommitteeInstance,
710
					5,
711
					9,
712
				>,
713
				EitherOf<
714
					governance::custom_origins::FastGeneralAdmin,
715
					governance::custom_origins::GeneralAdmin,
716
				>,
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 = moonbase_weights::pallet_moonbeam_foreign_assets::WeightInfo<Runtime>;
736
	type XcmLocationToH160 = LocationToH160;
737
	type ForeignAssetCreationDeposit = dynamic_params::xcm_config::ForeignAssetCreationDeposit;
738
	type Balance = Balance;
739
	type Currency = Balances;
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 = moonbase_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
}