1
// Copyright 2019-2022 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, ParachainInfo,
23
	ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent,
24
	RuntimeOrigin, Treasury, XcmpQueue,
25
};
26
use crate::OpenTechCommitteeInstance;
27
use moonbeam_runtime_common::weights as moonbase_weights;
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::{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, WeightInfoBounds, WithComputedOrigin,
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 xcm_primitives::{
62
	AbsoluteAndRelativeReserve, AccountIdToCurrencyId, AccountIdToLocation, AsAssetType,
63
	IsBridgedConcreteAssetFrom, MultiNativeAsset, SignedToAccountId20, UtilityAvailableCalls,
64
	UtilityEncodeCall, XcmTransact,
65
};
66

            
67
use parity_scale_codec::{Decode, Encode};
68
use scale_info::TypeInfo;
69

            
70
use sp_core::Get;
71
use sp_std::{
72
	convert::{From, Into, TryFrom},
73
	prelude::*,
74
};
75

            
76
use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot};
77

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

            
87

            
88
	// Self Reserve location, defines the multilocation identifiying 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
32
	fn convert_location(location: &Location) -> Option<H160> {
118
32
		<LocationToAccountId as ConvertLocation<AccountId>>::convert_location(location)
119
32
			.map(Into::into)
120
32
	}
121
}
122

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

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

            
163
// We use all transactors
164
// These correspond to
165
// SelfReserve asset, both pre and post 0.9.16
166
// Foreign assets
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 = (
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
// Our implementation of the Moonbeam Call
233
// Attachs the right origin in case the call is made to pallet-ethereum-xcm
234
#[cfg(not(feature = "evm-tracing"))]
235
moonbeam_runtime_common::impl_moonbeam_xcm_call!();
236
#[cfg(feature = "evm-tracing")]
237
64
moonbeam_runtime_common::impl_moonbeam_xcm_call_tracing!();
238

            
239
16
moonbeam_runtime_common::impl_evm_runner_precompile_or_eth_xcm!();
240

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

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

            
265
type Reserves = (
266
	// Assets bridged from different consensus systems held in reserve on Asset Hub.
267
	IsBridgedConcreteAssetFrom<AssetHubLocation>,
268
	// Relaychain (DOT) from Asset Hub
269
	Case<RelayChainNativeAssetFromAssetHub>,
270
	// Assets which the reserve is the same as the origin.
271
	MultiNativeAsset<AbsoluteAndRelativeReserve<SelfLocationAbsolute>>,
272
);
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
	// We use two traders
290
	// When we receive the relative representation of the self-reserve asset,
291
	// we use UsingComponents and the local way of handling fees
292
	// When we receive a non-reserve asset, we use AssetManager to fetch how many
293
	// units per second we should charge
294
	type Trader = pallet_xcm_weight_trader::Trader<Runtime>;
295
	type ResponseHandler = PolkadotXcm;
296
	type SubscriptionService = PolkadotXcm;
297
	type AssetTrap = pallet_erc20_xcm_bridge::AssetTrapWrapper<PolkadotXcm, Runtime>;
298
	type AssetClaims = PolkadotXcm;
299
	type CallDispatcher = MoonbeamCall;
300
	type PalletInstancesInfo = crate::AllPalletsWithSystem;
301
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
302
	type AssetLocker = ();
303
	type AssetExchanger = ();
304
	type FeeManager = ();
305
	type MessageExporter = ();
306
	type UniversalAliases = Nothing;
307
	type SafeCallFilter = SafeCallFilter;
308
	type Aliasers = Nothing;
309
	type TransactionalProcessor = xcm_builder::FrameTransactionalProcessor;
310
	type HrmpNewChannelOpenRequestHandler = ();
311
	type HrmpChannelAcceptedHandler = ();
312
	type HrmpChannelClosingHandler = ();
313
	type XcmRecorder = PolkadotXcm;
314
}
315

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

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

            
328
type XcmExecutor = pallet_erc20_xcm_bridge::XcmExecutorWrapper<
329
	XcmExecutorConfig,
330
	xcm_executor::XcmExecutor<XcmExecutorConfig>,
331
>;
332

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
580
}
581

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

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

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

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

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

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

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

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

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

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

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

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

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

            
699
pub type ForeignAssetManagerOrigin = EitherOfDiverse<
700
	EnsureRoot<AccountId>,
701
	EitherOfDiverse<
702
		pallet_collective::EnsureProportionMoreThan<AccountId, OpenTechCommitteeInstance, 5, 9>,
703
		governance::custom_origins::FastGeneralAdmin,
704
	>,
705
>;
706

            
707
impl pallet_moonbeam_foreign_assets::Config for Runtime {
708
	type AccountIdToH160 = AccountIdToH160;
709
	type AssetIdFilter = EvmForeignAssetIdFilter;
710
	type EvmRunner = EvmRunnerPrecompileOrEthXcm<MoonbeamCall, Self>;
711
	type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin;
712
	type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin;
713
	type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin;
714
	type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin;
715
	type OnForeignAssetCreated = ();
716
	type MaxForeignAssets = ConstU32<256>;
717
	type RuntimeEvent = RuntimeEvent;
718
	type WeightInfo = moonbase_weights::pallet_moonbeam_foreign_assets::WeightInfo<Runtime>;
719
	type XcmLocationToH160 = LocationToH160;
720
}
721

            
722
pub struct AssetFeesFilter;
723
impl frame_support::traits::Contains<Location> for AssetFeesFilter {
724
	fn contains(location: &Location) -> bool {
725
		location.parent_count() > 0
726
			&& location.first_interior() != Erc20XcmBridgePalletLocation::get().first_interior()
727
	}
728
}
729

            
730
impl pallet_xcm_weight_trader::Config for Runtime {
731
	type AccountIdToLocation = AccountIdToLocation<AccountId>;
732
	type AddSupportedAssetOrigin = EnsureRoot<AccountId>;
733
	type AssetLocationFilter = AssetFeesFilter;
734
	type AssetTransactor = AssetTransactors;
735
	type Balance = Balance;
736
	type EditSupportedAssetOrigin = EnsureRoot<AccountId>;
737
	type NativeLocation = SelfReserve;
738
	type PauseSupportedAssetOrigin = EnsureRoot<AccountId>;
739
	type RemoveSupportedAssetOrigin = EnsureRoot<AccountId>;
740
	type RuntimeEvent = RuntimeEvent;
741
	type ResumeSupportedAssetOrigin = EnsureRoot<AccountId>;
742
	type WeightInfo = moonbase_weights::pallet_xcm_weight_trader::WeightInfo<Runtime>;
743
	type WeightToFee = <Runtime as pallet_transaction_payment::Config>::WeightToFee;
744
	type XcmFeesAccount = XcmFeesAccount;
745
	#[cfg(feature = "runtime-benchmarks")]
746
	type NotFilteredLocation = RelayLocation;
747
}
748

            
749
#[cfg(feature = "runtime-benchmarks")]
750
mod testing {
751
	use super::*;
752
	use xcm_builder::WithLatestLocationConverter;
753

            
754
	/// This From exists for benchmarking purposes. It has the potential side-effect of calling
755
	/// AssetManager::set_asset_type_asset_id() and should NOT be used in any production code.
756
	impl From<Location> for CurrencyId {
757
		fn from(location: Location) -> CurrencyId {
758
			use xcm_primitives::AssetTypeGetter;
759

            
760
			// If it does not exist, for benchmarking purposes, we create the association
761
			let asset_id = if let Some(asset_id) =
762
				AsAssetType::<AssetId, AssetType, AssetManager>::convert_location(&location)
763
			{
764
				asset_id
765
			} else {
766
				let asset_type = AssetType::Xcm(
767
					WithLatestLocationConverter::convert(&location).expect("convert to v3"),
768
				);
769
				let asset_id: AssetId = asset_type.clone().into();
770
				AssetManager::set_asset_type_asset_id(asset_type, asset_id);
771
				asset_id
772
			};
773

            
774
			CurrencyId::ForeignAsset(asset_id)
775
		}
776
	}
777
}