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
//! Moonbeam Runtime Integration Tests
18

            
19
#![cfg(test)]
20

            
21
mod common;
22

            
23
use common::*;
24

            
25
use fp_evm::{Context, IsPrecompileResult};
26
use frame_support::{
27
	assert_noop, assert_ok,
28
	dispatch::DispatchClass,
29
	traits::{
30
		Contains, Currency as CurrencyT, EnsureOrigin, OnInitialize, PalletInfo, StorageInfo,
31
		StorageInfoTrait,
32
	},
33
	weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
34
	StorageHasher, Twox128,
35
};
36
use moonbeam_runtime::currency::{GIGAWEI, WEI};
37
use moonbeam_runtime::runtime_params::dynamic_params;
38
use moonbeam_runtime::xcm_config::{AssetHubLocation, XcmExecutor};
39
use moonbeam_runtime::{
40
	currency::GLMR,
41
	moonbeam_xcm_weights,
42
	xcm_config::{CurrencyId, SelfReserve},
43
	AccountId, Balances, EvmForeignAssets, Executive, NormalFilter, OpenTechCommitteeCollective,
44
	ParachainStaking, PolkadotXcm, Precompiles, ProxyType, Runtime, RuntimeBlockWeights,
45
	RuntimeCall, RuntimeEvent, System, TransactionPayment, TransactionPaymentAsGasPrice, Treasury,
46
	TreasuryCouncilCollective, XcmTransactor, WEIGHT_PER_GAS,
47
};
48
use moonbeam_xcm_weights::XcmWeight;
49
use nimbus_primitives::NimbusId;
50
use pallet_evm::PrecompileSet;
51
use pallet_moonbeam_foreign_assets::AssetStatus;
52
use pallet_parachain_staking::InflationDistributionAccount;
53
use pallet_transaction_payment::Multiplier;
54
use pallet_xcm_transactor::{Currency, CurrencyPayment, TransactWeights};
55
use parity_scale_codec::Encode;
56
use polkadot_parachain::primitives::Sibling;
57
use precompile_utils::{
58
	precompile_set::{is_precompile_or_fail, IsActivePrecompile},
59
	prelude::*,
60
	testing::*,
61
};
62
use sp_core::{ByteArray, Get, H160, U256};
63
use sp_runtime::{
64
	traits::{Convert, Dispatchable},
65
	BuildStorage, DispatchError, ModuleError, Percent,
66
};
67
use std::str::from_utf8;
68
use xcm::{latest::prelude::*, VersionedAssets, VersionedLocation};
69
use xcm_builder::{ParentIsPreset, SiblingParachainConvertsVia};
70
use xcm_executor::traits::ConvertLocation;
71
use xcm_primitives::split_location_into_chain_part_and_beneficiary;
72

            
73
type BatchPCall = pallet_evm_precompile_batch::BatchPrecompileCall<Runtime>;
74
type XcmUtilsPCall = pallet_evm_precompile_xcm_utils::XcmUtilsPrecompileCall<
75
	Runtime,
76
	moonbeam_runtime::xcm_config::XcmExecutorConfig,
77
>;
78
type XcmTransactorV2PCall =
79
	pallet_evm_precompile_xcm_transactor::v2::XcmTransactorPrecompileV2Call<Runtime>;
80

            
81
const BASE_FEE_GENESIS: u128 = 10000 * GIGAWEI;
82

            
83
7
fn currency_to_asset(currency_id: CurrencyId, amount: u128) -> Asset {
84
7
	Asset {
85
7
		id: AssetId(
86
7
			<moonbeam_runtime::Runtime as pallet_xcm_transactor::Config>::CurrencyIdToLocation::convert(
87
7
				currency_id,
88
7
			)
89
7
			.unwrap(),
90
7
		),
91
7
		fun: Fungibility::Fungible(amount),
92
7
	}
93
7
}
94
#[test]
95
1
fn xcmp_queue_controller_origin_is_root() {
96
1
	// important for the XcmExecutionManager impl of PauseExecution which uses root origin
97
1
	// to suspend/resume XCM execution in xcmp_queue::on_idle
98
1
	assert_ok!(
99
1
		<moonbeam_runtime::Runtime as cumulus_pallet_xcmp_queue::Config
100
1
		>::ControllerOrigin::ensure_origin(root_origin())
101
1
	);
102
1
}
103

            
104
#[test]
105
1
fn verify_pallet_prefixes() {
106
31
	fn is_pallet_prefix<P: 'static>(name: &str) {
107
31
		// Compares the unhashed pallet prefix in the `StorageInstance` implementation by every
108
31
		// storage item in the pallet P. This pallet prefix is used in conjunction with the
109
31
		// item name to get the unique storage key: hash(PalletPrefix) + hash(StorageName)
110
31
		// https://github.com/paritytech/substrate/blob/master/frame/support/procedural/src/pallet/
111
31
		// expand/storage.rs#L389-L401
112
31
		assert_eq!(
113
31
			<moonbeam_runtime::Runtime as frame_system::Config>::PalletInfo::name::<P>(),
114
31
			Some(name)
115
31
		);
116
31
	}
117
	// TODO: use StorageInfoTrait once https://github.com/paritytech/substrate/pull/9246
118
	// is pulled in substrate deps.
119
1
	is_pallet_prefix::<moonbeam_runtime::System>("System");
120
1
	is_pallet_prefix::<moonbeam_runtime::Utility>("Utility");
121
1
	is_pallet_prefix::<moonbeam_runtime::ParachainSystem>("ParachainSystem");
122
1
	is_pallet_prefix::<moonbeam_runtime::TransactionPayment>("TransactionPayment");
123
1
	is_pallet_prefix::<moonbeam_runtime::ParachainInfo>("ParachainInfo");
124
1
	is_pallet_prefix::<moonbeam_runtime::EthereumChainId>("EthereumChainId");
125
1
	is_pallet_prefix::<moonbeam_runtime::EVM>("EVM");
126
1
	is_pallet_prefix::<moonbeam_runtime::Ethereum>("Ethereum");
127
1
	is_pallet_prefix::<moonbeam_runtime::ParachainStaking>("ParachainStaking");
128
1
	is_pallet_prefix::<moonbeam_runtime::Scheduler>("Scheduler");
129
1
	is_pallet_prefix::<moonbeam_runtime::OpenTechCommitteeCollective>(
130
1
		"OpenTechCommitteeCollective",
131
1
	);
132
1
	is_pallet_prefix::<moonbeam_runtime::Treasury>("Treasury");
133
1
	is_pallet_prefix::<moonbeam_runtime::AuthorInherent>("AuthorInherent");
134
1
	is_pallet_prefix::<moonbeam_runtime::AuthorFilter>("AuthorFilter");
135
1
	is_pallet_prefix::<moonbeam_runtime::CrowdloanRewards>("CrowdloanRewards");
136
1
	is_pallet_prefix::<moonbeam_runtime::AuthorMapping>("AuthorMapping");
137
1
	is_pallet_prefix::<moonbeam_runtime::MaintenanceMode>("MaintenanceMode");
138
1
	is_pallet_prefix::<moonbeam_runtime::Identity>("Identity");
139
1
	is_pallet_prefix::<moonbeam_runtime::XcmpQueue>("XcmpQueue");
140
1
	is_pallet_prefix::<moonbeam_runtime::CumulusXcm>("CumulusXcm");
141
1
	is_pallet_prefix::<moonbeam_runtime::PolkadotXcm>("PolkadotXcm");
142
1
	is_pallet_prefix::<moonbeam_runtime::XcmTransactor>("XcmTransactor");
143
1
	is_pallet_prefix::<moonbeam_runtime::ProxyGenesisCompanion>("ProxyGenesisCompanion");
144
1
	is_pallet_prefix::<moonbeam_runtime::MoonbeamOrbiters>("MoonbeamOrbiters");
145
1
	is_pallet_prefix::<moonbeam_runtime::TreasuryCouncilCollective>("TreasuryCouncilCollective");
146
1
	is_pallet_prefix::<moonbeam_runtime::MoonbeamLazyMigrations>("MoonbeamLazyMigrations");
147
1
	is_pallet_prefix::<moonbeam_runtime::RelayStorageRoots>("RelayStorageRoots");
148
1
	is_pallet_prefix::<moonbeam_runtime::BridgeKusamaGrandpa>("BridgeKusamaGrandpa");
149
1
	is_pallet_prefix::<moonbeam_runtime::BridgeKusamaParachains>("BridgeKusamaParachains");
150
1
	is_pallet_prefix::<moonbeam_runtime::BridgeKusamaMessages>("BridgeKusamaMessages");
151
1
	is_pallet_prefix::<moonbeam_runtime::BridgeXcmOverMoonriver>("BridgeXcmOverMoonriver");
152
1

            
153
14
	let prefix = |pallet_name, storage_name| {
154
14
		let mut res = [0u8; 32];
155
14
		res[0..16].copy_from_slice(&Twox128::hash(pallet_name));
156
14
		res[16..32].copy_from_slice(&Twox128::hash(storage_name));
157
14
		res.to_vec()
158
14
	};
159
1
	assert_eq!(
160
1
		<moonbeam_runtime::Timestamp as StorageInfoTrait>::storage_info(),
161
1
		vec![
162
1
			StorageInfo {
163
1
				pallet_name: b"Timestamp".to_vec(),
164
1
				storage_name: b"Now".to_vec(),
165
1
				prefix: prefix(b"Timestamp", b"Now"),
166
1
				max_values: Some(1),
167
1
				max_size: Some(8),
168
1
			},
169
1
			StorageInfo {
170
1
				pallet_name: b"Timestamp".to_vec(),
171
1
				storage_name: b"DidUpdate".to_vec(),
172
1
				prefix: prefix(b"Timestamp", b"DidUpdate"),
173
1
				max_values: Some(1),
174
1
				max_size: Some(1),
175
1
			}
176
1
		]
177
1
	);
178
1
	assert_eq!(
179
1
		<moonbeam_runtime::Balances as StorageInfoTrait>::storage_info(),
180
1
		vec![
181
1
			StorageInfo {
182
1
				pallet_name: b"Balances".to_vec(),
183
1
				storage_name: b"TotalIssuance".to_vec(),
184
1
				prefix: prefix(b"Balances", b"TotalIssuance"),
185
1
				max_values: Some(1),
186
1
				max_size: Some(16),
187
1
			},
188
1
			StorageInfo {
189
1
				pallet_name: b"Balances".to_vec(),
190
1
				storage_name: b"InactiveIssuance".to_vec(),
191
1
				prefix: prefix(b"Balances", b"InactiveIssuance"),
192
1
				max_values: Some(1),
193
1
				max_size: Some(16),
194
1
			},
195
1
			StorageInfo {
196
1
				pallet_name: b"Balances".to_vec(),
197
1
				storage_name: b"Account".to_vec(),
198
1
				prefix: prefix(b"Balances", b"Account"),
199
1
				max_values: None,
200
1
				max_size: Some(100),
201
1
			},
202
1
			StorageInfo {
203
1
				pallet_name: b"Balances".to_vec(),
204
1
				storage_name: b"Locks".to_vec(),
205
1
				prefix: prefix(b"Balances", b"Locks"),
206
1
				max_values: None,
207
1
				max_size: Some(1287),
208
1
			},
209
1
			StorageInfo {
210
1
				pallet_name: b"Balances".to_vec(),
211
1
				storage_name: b"Reserves".to_vec(),
212
1
				prefix: prefix(b"Balances", b"Reserves"),
213
1
				max_values: None,
214
1
				max_size: Some(1037),
215
1
			},
216
1
			StorageInfo {
217
1
				pallet_name: b"Balances".to_vec(),
218
1
				storage_name: b"Holds".to_vec(),
219
1
				prefix: prefix(b"Balances", b"Holds"),
220
1
				max_values: None,
221
1
				max_size: Some(91),
222
1
			},
223
1
			StorageInfo {
224
1
				pallet_name: b"Balances".to_vec(),
225
1
				storage_name: b"Freezes".to_vec(),
226
1
				prefix: prefix(b"Balances", b"Freezes"),
227
1
				max_values: None,
228
1
				max_size: Some(73),
229
1
			},
230
1
		]
231
1
	);
232
1
	assert_eq!(
233
1
		<moonbeam_runtime::Proxy as StorageInfoTrait>::storage_info(),
234
1
		vec![
235
1
			StorageInfo {
236
1
				pallet_name: b"Proxy".to_vec(),
237
1
				storage_name: b"Proxies".to_vec(),
238
1
				prefix: prefix(b"Proxy", b"Proxies"),
239
1
				max_values: None,
240
1
				max_size: Some(845),
241
1
			},
242
1
			StorageInfo {
243
1
				pallet_name: b"Proxy".to_vec(),
244
1
				storage_name: b"Announcements".to_vec(),
245
1
				prefix: prefix(b"Proxy", b"Announcements"),
246
1
				max_values: None,
247
1
				max_size: Some(1837),
248
1
			}
249
1
		]
250
1
	);
251
1
	assert_eq!(
252
1
		<moonbeam_runtime::MaintenanceMode as StorageInfoTrait>::storage_info(),
253
1
		vec![StorageInfo {
254
1
			pallet_name: b"MaintenanceMode".to_vec(),
255
1
			storage_name: b"MaintenanceMode".to_vec(),
256
1
			prefix: prefix(b"MaintenanceMode", b"MaintenanceMode"),
257
1
			max_values: Some(1),
258
1
			max_size: None,
259
1
		},]
260
1
	);
261
1
	assert_eq!(
262
1
		<moonbeam_runtime::RelayStorageRoots as StorageInfoTrait>::storage_info(),
263
1
		vec![
264
1
			StorageInfo {
265
1
				pallet_name: b"RelayStorageRoots".to_vec(),
266
1
				storage_name: b"RelayStorageRoot".to_vec(),
267
1
				prefix: prefix(b"RelayStorageRoots", b"RelayStorageRoot"),
268
1
				max_values: None,
269
1
				max_size: Some(44),
270
1
			},
271
1
			StorageInfo {
272
1
				pallet_name: b"RelayStorageRoots".to_vec(),
273
1
				storage_name: b"RelayStorageRootKeys".to_vec(),
274
1
				prefix: prefix(b"RelayStorageRoots", b"RelayStorageRootKeys"),
275
1
				max_values: Some(1),
276
1
				max_size: Some(121),
277
1
			},
278
1
		]
279
1
	);
280
1
}
281

            
282
#[test]
283
1
fn test_collectives_storage_item_prefixes() {
284
7
	for StorageInfo { pallet_name, .. } in
285
8
		<moonbeam_runtime::TreasuryCouncilCollective as StorageInfoTrait>::storage_info()
286
	{
287
7
		assert_eq!(pallet_name, b"TreasuryCouncilCollective".to_vec());
288
	}
289

            
290
7
	for StorageInfo { pallet_name, .. } in
291
8
		<moonbeam_runtime::OpenTechCommitteeCollective as StorageInfoTrait>::storage_info()
292
	{
293
7
		assert_eq!(pallet_name, b"OpenTechCommitteeCollective".to_vec());
294
	}
295
1
}
296

            
297
#[test]
298
1
fn collective_set_members_root_origin_works() {
299
1
	ExtBuilder::default().build().execute_with(|| {
300
1
		// TreasuryCouncilCollective
301
1
		assert_ok!(TreasuryCouncilCollective::set_members(
302
1
			<Runtime as frame_system::Config>::RuntimeOrigin::root(),
303
1
			vec![AccountId::from(ALICE), AccountId::from(BOB)],
304
1
			Some(AccountId::from(ALICE)),
305
1
			2
306
1
		));
307
		// OpenTechCommitteeCollective
308
1
		assert_ok!(OpenTechCommitteeCollective::set_members(
309
1
			<Runtime as frame_system::Config>::RuntimeOrigin::root(),
310
1
			vec![AccountId::from(ALICE), AccountId::from(BOB)],
311
1
			Some(AccountId::from(ALICE)),
312
1
			2
313
1
		));
314
1
	});
315
1
}
316

            
317
#[test]
318
1
fn collective_set_members_general_admin_origin_works() {
319
	use moonbeam_runtime::{
320
		governance::custom_origins::Origin as CustomOrigin, OriginCaller, Utility,
321
	};
322

            
323
1
	ExtBuilder::default().build().execute_with(|| {
324
1
		let root_caller = <Runtime as frame_system::Config>::RuntimeOrigin::root();
325
1
		let alice = AccountId::from(ALICE);
326
1

            
327
1
		// TreasuryCouncilCollective
328
1
		let _ = Utility::dispatch_as(
329
1
			root_caller.clone(),
330
1
			Box::new(OriginCaller::Origins(CustomOrigin::GeneralAdmin)),
331
1
			Box::new(
332
1
				pallet_collective::Call::<Runtime, pallet_collective::Instance3>::set_members {
333
1
					new_members: vec![alice, AccountId::from(BOB)],
334
1
					prime: Some(alice),
335
1
					old_count: 2,
336
1
				}
337
1
				.into(),
338
1
			),
339
1
		);
340
1
		// OpenTechCommitteeCollective
341
1
		let _ = Utility::dispatch_as(
342
1
			root_caller,
343
1
			Box::new(OriginCaller::Origins(CustomOrigin::GeneralAdmin)),
344
1
			Box::new(
345
1
				pallet_collective::Call::<Runtime, pallet_collective::Instance4>::set_members {
346
1
					new_members: vec![alice, AccountId::from(BOB)],
347
1
					prime: Some(alice),
348
1
					old_count: 2,
349
1
				}
350
1
				.into(),
351
1
			),
352
1
		);
353
1

            
354
1
		assert_eq!(
355
1
			System::events()
356
1
				.into_iter()
357
2
				.filter_map(|r| {
358
2
					match r.event {
359
2
						RuntimeEvent::Utility(pallet_utility::Event::DispatchedAs { result })
360
2
							if result.is_ok() =>
361
2
						{
362
2
							Some(true)
363
						}
364
						_ => None,
365
					}
366
2
				})
367
1
				.collect::<Vec<_>>()
368
1
				.len(),
369
1
			2
370
1
		)
371
1
	});
372
1
}
373

            
374
#[test]
375
1
fn collective_set_members_signed_origin_does_not_work() {
376
1
	let alice = AccountId::from(ALICE);
377
1
	ExtBuilder::default().build().execute_with(|| {
378
1
		// TreasuryCouncilCollective
379
1
		assert!(TreasuryCouncilCollective::set_members(
380
1
			<Runtime as frame_system::Config>::RuntimeOrigin::signed(alice),
381
1
			vec![AccountId::from(ALICE), AccountId::from(BOB)],
382
1
			Some(AccountId::from(ALICE)),
383
1
			2
384
1
		)
385
1
		.is_err());
386
		// OpenTechCommitteeCollective
387
1
		assert!(OpenTechCommitteeCollective::set_members(
388
1
			<Runtime as frame_system::Config>::RuntimeOrigin::signed(alice),
389
1
			vec![AccountId::from(ALICE), AccountId::from(BOB)],
390
1
			Some(AccountId::from(ALICE)),
391
1
			2
392
1
		)
393
1
		.is_err());
394
1
	});
395
1
}
396

            
397
#[test]
398
1
fn verify_pallet_indices() {
399
33
	fn is_pallet_index<P: 'static>(index: usize) {
400
33
		assert_eq!(
401
33
			<moonbeam_runtime::Runtime as frame_system::Config>::PalletInfo::index::<P>(),
402
33
			Some(index)
403
33
		);
404
33
	}
405

            
406
	// System support
407
1
	is_pallet_index::<moonbeam_runtime::System>(0);
408
1
	is_pallet_index::<moonbeam_runtime::ParachainSystem>(1);
409
1
	is_pallet_index::<moonbeam_runtime::Timestamp>(3);
410
1
	is_pallet_index::<moonbeam_runtime::ParachainInfo>(4);
411
1
	// Monetary
412
1
	is_pallet_index::<moonbeam_runtime::Balances>(10);
413
1
	is_pallet_index::<moonbeam_runtime::TransactionPayment>(11);
414
1
	// Consensus support
415
1
	is_pallet_index::<moonbeam_runtime::ParachainStaking>(20);
416
1
	is_pallet_index::<moonbeam_runtime::AuthorInherent>(21);
417
1
	is_pallet_index::<moonbeam_runtime::AuthorFilter>(22);
418
1
	is_pallet_index::<moonbeam_runtime::AuthorMapping>(23);
419
1
	is_pallet_index::<moonbeam_runtime::MoonbeamOrbiters>(24);
420
1
	// Handy utilities
421
1
	is_pallet_index::<moonbeam_runtime::Utility>(30);
422
1
	is_pallet_index::<moonbeam_runtime::Proxy>(31);
423
1
	is_pallet_index::<moonbeam_runtime::MaintenanceMode>(32);
424
1
	is_pallet_index::<moonbeam_runtime::Identity>(33);
425
1
	is_pallet_index::<moonbeam_runtime::ProxyGenesisCompanion>(35);
426
1
	is_pallet_index::<moonbeam_runtime::MoonbeamLazyMigrations>(37);
427
1
	// Ethereum compatibility
428
1
	is_pallet_index::<moonbeam_runtime::EthereumChainId>(50);
429
1
	is_pallet_index::<moonbeam_runtime::EVM>(51);
430
1
	is_pallet_index::<moonbeam_runtime::Ethereum>(52);
431
1
	// Governance
432
1
	is_pallet_index::<moonbeam_runtime::Scheduler>(60);
433
1
	// is_pallet_index::<moonbeam_runtime::Democracy>(61); Removed
434
1
	// Council
435
1
	// is_pallet_index::<moonbeam_runtime::CouncilCollective>(70); Removed
436
1
	// is_pallet_index::<moonbeam_runtime::TechCommitteeCollective>(71); Removed
437
1
	is_pallet_index::<moonbeam_runtime::TreasuryCouncilCollective>(72);
438
1
	is_pallet_index::<moonbeam_runtime::OpenTechCommitteeCollective>(73);
439
1
	// Treasury
440
1
	is_pallet_index::<moonbeam_runtime::Treasury>(80);
441
1
	// Crowdloan
442
1
	is_pallet_index::<moonbeam_runtime::CrowdloanRewards>(90);
443
1
	// XCM Stuff
444
1
	is_pallet_index::<moonbeam_runtime::XcmpQueue>(100);
445
1
	is_pallet_index::<moonbeam_runtime::CumulusXcm>(101);
446
1
	is_pallet_index::<moonbeam_runtime::PolkadotXcm>(103);
447
1
	// is_pallet_index::<moonbeam_runtime::Assets>(104); Removed
448
1
	// is_pallet_index::<moonbeam_runtime::AssetManager>(105); Removed
449
1
	// is_pallet_index::<moonbeam_runtime::XTokens>(106); Removed
450
1
	is_pallet_index::<moonbeam_runtime::XcmTransactor>(107);
451
1
	is_pallet_index::<moonbeam_runtime::BridgeKusamaGrandpa>(130);
452
1
	is_pallet_index::<moonbeam_runtime::BridgeKusamaParachains>(131);
453
1
	is_pallet_index::<moonbeam_runtime::BridgeKusamaMessages>(132);
454
1
	is_pallet_index::<moonbeam_runtime::BridgeXcmOverMoonriver>(133);
455
1
}
456

            
457
#[test]
458
1
fn verify_reserved_indices() {
459
1
	let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
460
1
		.build_storage()
461
1
		.unwrap()
462
1
		.into();
463
1

            
464
1
	t.execute_with(|| {
465
		use frame_metadata::*;
466
1
		let metadata = moonbeam_runtime::Runtime::metadata();
467
1
		let metadata = match metadata.1 {
468
1
			RuntimeMetadata::V14(metadata) => metadata,
469
			_ => panic!("metadata has been bumped, test needs to be updated"),
470
		};
471
		// 40: Sudo
472
		// 53: BaseFee
473
		// 108: pallet_assets::<Instance1>
474
1
		let reserved = vec![40, 53, 108];
475
1
		let existing = metadata
476
1
			.pallets
477
1
			.iter()
478
51
			.map(|p| p.index)
479
1
			.collect::<Vec<u8>>();
480
3
		assert!(reserved.iter().all(|index| !existing.contains(index)));
481
1
	});
482
1
}
483

            
484
#[test]
485
1
fn verify_proxy_type_indices() {
486
1
	assert_eq!(moonbeam_runtime::ProxyType::Any as u8, 0);
487
1
	assert_eq!(moonbeam_runtime::ProxyType::NonTransfer as u8, 1);
488
1
	assert_eq!(moonbeam_runtime::ProxyType::Governance as u8, 2);
489
1
	assert_eq!(moonbeam_runtime::ProxyType::Staking as u8, 3);
490
1
	assert_eq!(moonbeam_runtime::ProxyType::CancelProxy as u8, 4);
491
1
	assert_eq!(moonbeam_runtime::ProxyType::Balances as u8, 5);
492
1
	assert_eq!(moonbeam_runtime::ProxyType::AuthorMapping as u8, 6);
493
1
	assert_eq!(moonbeam_runtime::ProxyType::IdentityJudgement as u8, 7);
494
1
}
495

            
496
// This test ensure that we not filter out pure proxy calls
497
#[test]
498
1
fn verify_normal_filter_allow_pure_proxy() {
499
1
	ExtBuilder::default().build().execute_with(|| {
500
1
		assert!(NormalFilter::contains(&RuntimeCall::Proxy(
501
1
			pallet_proxy::Call::<Runtime>::create_pure {
502
1
				proxy_type: ProxyType::Any,
503
1
				delay: 0,
504
1
				index: 0,
505
1
			}
506
1
		)));
507
1
		assert!(NormalFilter::contains(&RuntimeCall::Proxy(
508
1
			pallet_proxy::Call::<Runtime>::kill_pure {
509
1
				spawner: AccountId::from(ALICE),
510
1
				proxy_type: ProxyType::Any,
511
1
				index: 0,
512
1
				height: 0,
513
1
				ext_index: 0,
514
1
			}
515
1
		)));
516
1
	});
517
1
}
518

            
519
#[test]
520
1
fn join_collator_candidates() {
521
1
	ExtBuilder::default()
522
1
		.with_balances(vec![
523
1
			(AccountId::from(ALICE), 10_000_000 * GLMR),
524
1
			(AccountId::from(BOB), 10_000_000 * GLMR),
525
1
			(AccountId::from(CHARLIE), 10_000_000 * GLMR),
526
1
			(AccountId::from(DAVE), 10_000_000 * GLMR),
527
1
		])
528
1
		.with_collators(vec![
529
1
			(AccountId::from(ALICE), 2_000_000 * GLMR),
530
1
			(AccountId::from(BOB), 2_000_000 * GLMR),
531
1
		])
532
1
		.with_delegations(vec![
533
1
			(
534
1
				AccountId::from(CHARLIE),
535
1
				AccountId::from(ALICE),
536
1
				5_000 * GLMR,
537
1
			),
538
1
			(AccountId::from(CHARLIE), AccountId::from(BOB), 5_000 * GLMR),
539
1
		])
540
1
		.build()
541
1
		.execute_with(|| {
542
1
			assert_noop!(
543
1
				ParachainStaking::join_candidates(
544
1
					origin_of(AccountId::from(ALICE)),
545
1
					2_000_000 * GLMR,
546
1
					2u32
547
1
				),
548
1
				pallet_parachain_staking::Error::<Runtime>::CandidateExists
549
1
			);
550
1
			assert_noop!(
551
1
				ParachainStaking::join_candidates(
552
1
					origin_of(AccountId::from(CHARLIE)),
553
1
					2_000_000 * GLMR,
554
1
					2u32
555
1
				),
556
1
				pallet_parachain_staking::Error::<Runtime>::DelegatorExists
557
1
			);
558
1
			assert!(System::events().is_empty());
559
1
			assert_ok!(ParachainStaking::join_candidates(
560
1
				origin_of(AccountId::from(DAVE)),
561
1
				2_000_000 * GLMR,
562
1
				2u32
563
1
			));
564
1
			assert_eq!(
565
1
				last_event(),
566
1
				RuntimeEvent::ParachainStaking(
567
1
					pallet_parachain_staking::Event::JoinedCollatorCandidates {
568
1
						account: AccountId::from(DAVE),
569
1
						amount_locked: 2_000_000 * GLMR,
570
1
						new_total_amt_locked: 6_010_000 * GLMR
571
1
					}
572
1
				)
573
1
			);
574
1
			let candidates = ParachainStaking::candidate_pool();
575
1
			assert_eq!(candidates.0[0].owner, AccountId::from(ALICE));
576
1
			assert_eq!(candidates.0[0].amount, 2_005_000 * GLMR);
577
1
			assert_eq!(candidates.0[1].owner, AccountId::from(BOB));
578
1
			assert_eq!(candidates.0[1].amount, 2_005_000 * GLMR);
579
1
			assert_eq!(candidates.0[2].owner, AccountId::from(DAVE));
580
1
			assert_eq!(candidates.0[2].amount, 2_000_000 * GLMR);
581
1
		});
582
1
}
583

            
584
#[test]
585
1
fn transfer_through_evm_to_stake() {
586
1
	ExtBuilder::default()
587
1
		.with_balances(vec![(AccountId::from(ALICE), 10_000_000 * GLMR)])
588
1
		.build()
589
1
		.execute_with(|| {
590
1
			// Charlie has no balance => fails to stake
591
1
			assert_noop!(
592
1
				ParachainStaking::join_candidates(
593
1
					origin_of(AccountId::from(CHARLIE)),
594
1
					2_000_000 * GLMR,
595
1
					2u32
596
1
				),
597
1
				DispatchError::Module(ModuleError {
598
1
					index: 20,
599
1
					error: [8, 0, 0, 0],
600
1
					message: Some("InsufficientBalance")
601
1
				})
602
1
			);
603
			// Alice transfer from free balance 3_000_000 GLMR to Bob
604
1
			assert_ok!(Balances::transfer_allow_death(
605
1
				origin_of(AccountId::from(ALICE)),
606
1
				AccountId::from(BOB),
607
1
				3_000_000 * GLMR,
608
1
			));
609
1
			assert_eq!(
610
1
				Balances::free_balance(AccountId::from(BOB)),
611
1
				3_000_000 * GLMR
612
1
			);
613

            
614
1
			let gas_limit = 100000u64;
615
1
			let gas_price: U256 = BASE_FEE_GENESIS.into();
616
1
			// Bob transfers 2_000_000 GLMR to Charlie via EVM
617
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
618
1
				source: H160::from(BOB),
619
1
				target: H160::from(CHARLIE),
620
1
				input: vec![],
621
1
				value: (2_000_000 * GLMR).into(),
622
1
				gas_limit,
623
1
				max_fee_per_gas: gas_price,
624
1
				max_priority_fee_per_gas: None,
625
1
				nonce: None,
626
1
				access_list: Vec::new(),
627
1
				authorization_list: Vec::new(),
628
1
			})
629
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
630
1
			assert_eq!(
631
1
				Balances::free_balance(AccountId::from(CHARLIE)),
632
1
				2_000_000 * GLMR,
633
1
			);
634

            
635
			// Charlie can stake now
636
1
			assert_ok!(ParachainStaking::join_candidates(
637
1
				origin_of(AccountId::from(CHARLIE)),
638
1
				2_000_000 * GLMR,
639
1
				2u32
640
1
			),);
641
1
			let candidates = ParachainStaking::candidate_pool();
642
1
			assert_eq!(candidates.0[0].owner, AccountId::from(CHARLIE));
643
1
			assert_eq!(candidates.0[0].amount, 2_000_000 * GLMR);
644
1
		});
645
1
}
646

            
647
#[test]
648
1
fn reward_block_authors() {
649
1
	ExtBuilder::default()
650
1
		.with_balances(vec![
651
1
			// Alice gets 10k extra tokens for her mapping deposit
652
1
			(AccountId::from(ALICE), 10_010_000 * GLMR),
653
1
			(AccountId::from(BOB), 10_000_000 * GLMR),
654
1
		])
655
1
		.with_collators(vec![(AccountId::from(ALICE), 2_000_000 * GLMR)])
656
1
		.with_delegations(vec![(
657
1
			AccountId::from(BOB),
658
1
			AccountId::from(ALICE),
659
1
			50_000 * GLMR,
660
1
		)])
661
1
		.with_mappings(vec![(
662
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
663
1
			AccountId::from(ALICE),
664
1
		)])
665
1
		.build()
666
1
		.execute_with(|| {
667
1
			increase_last_relay_slot_number(1);
668
1
			// Just before round 3
669
1
			run_to_block(7199, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
670
1
			// no rewards doled out yet
671
1
			assert_eq!(
672
1
				Balances::usable_balance(AccountId::from(ALICE)),
673
1
				8_010_000 * GLMR,
674
1
			);
675
1
			assert_eq!(
676
1
				Balances::usable_balance(AccountId::from(BOB)),
677
1
				9_950_000 * GLMR,
678
1
			);
679
1
			run_to_block(7201, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
680
1
			// rewards minted and distributed
681
1
			assert_eq!(
682
1
				Balances::usable_balance(AccountId::from(ALICE)),
683
1
				8990978048702400000000000,
684
1
			);
685
1
			assert_eq!(
686
1
				Balances::usable_balance(AccountId::from(BOB)),
687
1
				9969521950497200000000000,
688
1
			);
689
1
		});
690
1
}
691

            
692
#[test]
693
1
fn reward_block_authors_with_parachain_bond_reserved() {
694
1
	ExtBuilder::default()
695
1
		.with_balances(vec![
696
1
			// Alice gets 10k extra tokens for her mapping deposit
697
1
			(AccountId::from(ALICE), 10_010_000 * GLMR),
698
1
			(AccountId::from(BOB), 10_000_000 * GLMR),
699
1
			(AccountId::from(CHARLIE), 10_000 * GLMR),
700
1
		])
701
1
		.with_collators(vec![(AccountId::from(ALICE), 2_000_000 * GLMR)])
702
1
		.with_delegations(vec![(
703
1
			AccountId::from(BOB),
704
1
			AccountId::from(ALICE),
705
1
			50_000 * GLMR,
706
1
		)])
707
1
		.with_mappings(vec![(
708
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
709
1
			AccountId::from(ALICE),
710
1
		)])
711
1
		.build()
712
1
		.execute_with(|| {
713
1
			increase_last_relay_slot_number(1);
714
1
			assert_ok!(ParachainStaking::set_inflation_distribution_config(
715
1
				root_origin(),
716
1
				[
717
1
					InflationDistributionAccount {
718
1
						account: AccountId::from(CHARLIE),
719
1
						percent: Percent::from_percent(30),
720
1
					},
721
1
					InflationDistributionAccount::default(),
722
1
				]
723
1
				.into()
724
1
			));
725

            
726
			// Stop just before round 3
727
1
			run_to_block(7199, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
728
1
			// no collators rewards doled out yet
729
1
			assert_eq!(
730
1
				Balances::usable_balance(AccountId::from(ALICE)),
731
1
				8_010_000 * GLMR,
732
1
			);
733
1
			assert_eq!(
734
1
				Balances::usable_balance(AccountId::from(BOB)),
735
1
				9_950_000 * GLMR,
736
1
			);
737
			// 30% reserved for parachain bond
738
1
			assert_eq!(
739
1
				Balances::usable_balance(AccountId::from(CHARLIE)),
740
1
				310300000000000000000000,
741
1
			);
742

            
743
			// Go to round 3
744
1
			run_to_block(7201, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
745
1

            
746
1
			// collators rewards minted and distributed
747
1
			assert_eq!(
748
1
				Balances::usable_balance(AccountId::from(ALICE)),
749
1
				8698492682878000000000000,
750
1
			);
751
1
			assert_eq!(
752
1
				Balances::usable_balance(AccountId::from(BOB)),
753
1
				9962207316621500000000000,
754
1
			);
755
			// 30% reserved for parachain bond again
756
1
			assert_eq!(
757
1
				Balances::usable_balance(AccountId::from(CHARLIE)),
758
1
				615104500000000000000000,
759
1
			);
760
1
		});
761
1
}
762

            
763
1
fn run_with_system_weight<F>(w: Weight, mut assertions: F)
764
1
where
765
1
	F: FnMut() -> (),
766
1
{
767
1
	let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
768
1
		.build_storage()
769
1
		.unwrap()
770
1
		.into();
771
1
	t.execute_with(|| {
772
1
		System::set_block_consumed_resources(w, 0);
773
1
		assertions()
774
1
	});
775
1
}
776

            
777
#[test]
778
#[rustfmt::skip]
779
1
fn length_fee_is_sensible() {
780
	use sp_runtime::testing::TestXt;
781

            
782
	// tests that length fee is sensible for a few hypothetical transactions
783
1
	ExtBuilder::default().build().execute_with(|| {
784
1
		let call = frame_system::Call::remark::<Runtime> { remark: vec![] };
785
1
		let uxt: TestXt<_, ()> = TestXt::new_signed(RuntimeCall::System(call), 1u64, (), ());
786
1

            
787
9
		let calc_fee = |len: u32| -> Balance {
788
9
			moonbeam_runtime::TransactionPayment::query_fee_details(uxt.clone(), len)
789
9
				.inclusion_fee
790
9
				.expect("fee should be calculated")
791
9
				.len_fee
792
9
		};
793

            
794
		//                  left: cost of length fee, right: size in bytes
795
		//                             /------------- proportional component: O(N * 1B)
796
		//                             |           /- exponential component: O(N ** 3)
797
		//                             |           |
798
1
		assert_eq!(                    100_000_000_100, calc_fee(1));
799
1
		assert_eq!(                  1_000_000_100_000, calc_fee(10));
800
1
		assert_eq!(                 10_000_100_000_000, calc_fee(100));
801
1
		assert_eq!(                100_100_000_000_000, calc_fee(1_000));
802
1
		assert_eq!(              1_100_000_000_000_000, calc_fee(10_000)); // inflection point
803
1
		assert_eq!(            110_000_000_000_000_000, calc_fee(100_000));
804
1
		assert_eq!(        100_100_000_000_000_000_000, calc_fee(1_000_000)); // 100 GLMR, ~ 1MB
805
1
		assert_eq!(    100_001_000_000_000_000_000_000, calc_fee(10_000_000));
806
1
		assert_eq!(100_000_010_000_000_000_000_000_000, calc_fee(100_000_000));
807
1
	});
808
1
}
809

            
810
#[test]
811
1
fn multiplier_can_grow_from_zero() {
812
	use frame_support::traits::Get;
813

            
814
1
	let minimum_multiplier = moonbeam_runtime::MinimumMultiplier::get();
815
1
	let target = moonbeam_runtime::TargetBlockFullness::get()
816
1
		* RuntimeBlockWeights::get()
817
1
			.get(DispatchClass::Normal)
818
1
			.max_total
819
1
			.unwrap();
820
1
	// if the min is too small, then this will not change, and we are doomed forever.
821
1
	// the weight is 1/100th bigger than target.
822
1
	run_with_system_weight(target * 101 / 100, || {
823
1
		let next = moonbeam_runtime::SlowAdjustingFeeUpdate::<Runtime>::convert(minimum_multiplier);
824
1
		assert!(
825
1
			next > minimum_multiplier,
826
			"{:?} !>= {:?}",
827
			next,
828
			minimum_multiplier
829
		);
830
1
	})
831
1
}
832

            
833
#[test]
834
1
fn ethereum_invalid_transaction() {
835
1
	ExtBuilder::default().build().execute_with(|| {
836
1
		set_parachain_inherent_data();
837
1
		// Ensure an extrinsic not containing enough gas limit to store the transaction
838
1
		// on chain is rejected.
839
1
		assert_eq!(
840
1
			Executive::apply_extrinsic(unchecked_eth_tx(INVALID_ETH_TX)),
841
1
			Err(
842
1
				sp_runtime::transaction_validity::TransactionValidityError::Invalid(
843
1
					sp_runtime::transaction_validity::InvalidTransaction::Custom(0u8)
844
1
				)
845
1
			)
846
1
		);
847
1
	});
848
1
}
849

            
850
#[test]
851
1
fn initial_gas_fee_is_correct() {
852
	use fp_evm::FeeCalculator;
853

            
854
1
	ExtBuilder::default().build().execute_with(|| {
855
1
		let multiplier = TransactionPayment::next_fee_multiplier();
856
1
		assert_eq!(multiplier, Multiplier::from(1u128));
857

            
858
1
		assert_eq!(
859
1
			TransactionPaymentAsGasPrice::min_gas_price(),
860
1
			(
861
1
				31_250_000_000u128.into(),
862
1
				Weight::from_parts(<Runtime as frame_system::Config>::DbWeight::get().read, 0)
863
1
			)
864
1
		);
865
1
	});
866
1
}
867

            
868
#[test]
869
1
fn min_gas_fee_is_correct() {
870
	use fp_evm::FeeCalculator;
871
	use frame_support::traits::Hooks;
872

            
873
1
	ExtBuilder::default().build().execute_with(|| {
874
1
		pallet_transaction_payment::NextFeeMultiplier::<Runtime>::put(Multiplier::from(0));
875
1
		TransactionPayment::on_finalize(System::block_number()); // should trigger min to kick in
876
1

            
877
1
		let multiplier = TransactionPayment::next_fee_multiplier();
878
1
		assert_eq!(multiplier, Multiplier::from(1u128));
879

            
880
1
		assert_eq!(
881
1
			TransactionPaymentAsGasPrice::min_gas_price(),
882
1
			(
883
1
				31_250_000_000u128.into(),
884
1
				Weight::from_parts(<Runtime as frame_system::Config>::DbWeight::get().read, 0)
885
1
			)
886
1
		);
887
1
	});
888
1
}
889

            
890
#[test]
891
1
fn transfer_ed_0_substrate() {
892
1
	ExtBuilder::default()
893
1
		.with_balances(vec![
894
1
			(AccountId::from(ALICE), (1 * GLMR) + (1 * WEI)),
895
1
			(AccountId::from(BOB), existential_deposit()),
896
1
		])
897
1
		.build()
898
1
		.execute_with(|| {
899
1
			// Substrate transfer
900
1
			assert_ok!(Balances::transfer_allow_death(
901
1
				origin_of(AccountId::from(ALICE)),
902
1
				AccountId::from(BOB),
903
1
				1 * GLMR,
904
1
			));
905
			// 1 WEI is left in the account
906
1
			assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 1 * WEI);
907
1
		});
908
1
}
909

            
910
#[test]
911
1
fn transfer_ed_0_evm() {
912
1
	ExtBuilder::default()
913
1
		.with_balances(vec![
914
1
			(
915
1
				AccountId::from(ALICE),
916
1
				((1 * GLMR) + (21_000 * BASE_FEE_GENESIS)) + (1 * WEI),
917
1
			),
918
1
			(AccountId::from(BOB), existential_deposit()),
919
1
		])
920
1
		.build()
921
1
		.execute_with(|| {
922
1
			set_parachain_inherent_data();
923
1
			// EVM transfer
924
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
925
1
				source: H160::from(ALICE),
926
1
				target: H160::from(BOB),
927
1
				input: Vec::new(),
928
1
				value: (1 * GLMR).into(),
929
1
				gas_limit: 21_000u64,
930
1
				max_fee_per_gas: BASE_FEE_GENESIS.into(),
931
1
				max_priority_fee_per_gas: Some(BASE_FEE_GENESIS.into()),
932
1
				nonce: Some(U256::from(0)),
933
1
				access_list: Vec::new(),
934
1
				authorization_list: Vec::new(),
935
1
			})
936
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
937
			// 1 WEI is left in the account
938
1
			assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 1 * WEI,);
939
1
		});
940
1
}
941

            
942
#[test]
943
1
fn refund_ed_0_evm() {
944
1
	ExtBuilder::default()
945
1
		.with_balances(vec![
946
1
			(
947
1
				AccountId::from(ALICE),
948
1
				((1 * GLMR) + (21_777 * BASE_FEE_GENESIS) + existential_deposit()),
949
1
			),
950
1
			(AccountId::from(BOB), existential_deposit()),
951
1
		])
952
1
		.build()
953
1
		.execute_with(|| {
954
1
			set_parachain_inherent_data();
955
1
			// EVM transfer that zeroes ALICE
956
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
957
1
				source: H160::from(ALICE),
958
1
				target: H160::from(BOB),
959
1
				input: Vec::new(),
960
1
				value: (1 * GLMR).into(),
961
1
				gas_limit: 21_777u64,
962
1
				max_fee_per_gas: BASE_FEE_GENESIS.into(),
963
1
				max_priority_fee_per_gas: Some(BASE_FEE_GENESIS.into()),
964
1
				nonce: Some(U256::from(0)),
965
1
				access_list: Vec::new(),
966
1
				authorization_list: Vec::new(),
967
1
			})
968
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
969
			// ALICE is refunded
970
1
			assert_eq!(
971
1
				Balances::free_balance(AccountId::from(ALICE)),
972
1
				777 * BASE_FEE_GENESIS + existential_deposit(),
973
1
			);
974
1
		});
975
1
}
976

            
977
#[test]
978
1
fn author_does_receive_priority_fee() {
979
1
	ExtBuilder::default()
980
1
		.with_balances(vec![(
981
1
			AccountId::from(BOB),
982
1
			(1 * GLMR) + (21_000 * (500 * GIGAWEI)),
983
1
		)])
984
1
		.build()
985
1
		.execute_with(|| {
986
1
			// Some block author as seen by pallet-evm.
987
1
			let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
988
1
			pallet_author_inherent::Author::<Runtime>::put(author);
989
1
			// Currently the default impl of the evm uses `deposit_into_existing`.
990
1
			// If we were to use this implementation, and for an author to receive eventual tips,
991
1
			// the account needs to be somehow initialized, otherwise the deposit would fail.
992
1
			Balances::make_free_balance_be(&author, 100 * GLMR);
993
1

            
994
1
			// EVM transfer.
995
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
996
1
				source: H160::from(BOB),
997
1
				target: H160::from(ALICE),
998
1
				input: Vec::new(),
999
1
				value: (1 * GLMR).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: U256::from(300 * GIGAWEI),
1
				max_priority_fee_per_gas: Some(U256::from(200 * GIGAWEI)),
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
				authorization_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let priority_fee = 200 * GIGAWEI * 21_000;
1
			// Author free balance increased by priority fee.
1
			assert_eq!(Balances::free_balance(author), 100 * GLMR + priority_fee,);
1
		});
1
}
#[test]
1
fn total_issuance_after_evm_transaction_with_priority_fee() {
	use fp_evm::FeeCalculator;
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(
1
				AccountId::from(BOB),
1
				(1 * GLMR) + (21_000 * (200 * GIGAWEI) + existential_deposit()),
1
			),
1
			(
1
				<pallet_treasury::TreasuryAccountId<Runtime> as sp_core::TypedGet>::get(),
1
				existential_deposit(),
1
			),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			let issuance_before = <Runtime as pallet_evm::Config>::Currency::total_issuance();
1
			let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
1
			pallet_author_inherent::Author::<Runtime>::put(author);
1
			// EVM transfer.
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
1
				source: H160::from(BOB),
1
				target: H160::from(ALICE),
1
				input: Vec::new(),
1
				value: (1 * GLMR).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: U256::from(125 * GIGAWEI),
1
				max_priority_fee_per_gas: Some(U256::from(100 * GIGAWEI)),
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
				authorization_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let issuance_after = <Runtime as pallet_evm::Config>::Currency::total_issuance();
1

            
1
			let base_fee = TransactionPaymentAsGasPrice::min_gas_price().0.as_u128();
1

            
1
			let base_fee: Balance = base_fee * 21_000;
1

            
1
			let treasury_proportion = dynamic_params::runtime_config::FeesTreasuryProportion::get();
1

            
1
			// only base fee is split between being burned and sent to treasury
1
			let treasury_base_fee_part: Balance = treasury_proportion.mul_floor(base_fee);
1
			let burnt_base_fee_part: Balance = base_fee - treasury_base_fee_part;
1

            
1
			assert_eq!(issuance_after, issuance_before - burnt_base_fee_part);
1
			assert_eq!(moonbeam_runtime::Treasury::pot(), treasury_base_fee_part);
1
		});
1
}
#[test]
1
fn total_issuance_after_evm_transaction_without_priority_fee() {
	use fp_evm::FeeCalculator;
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(
1
				AccountId::from(BOB),
1
				(1 * GLMR) + (21_000 * BASE_FEE_GENESIS + existential_deposit()),
1
			),
1
			(
1
				<pallet_treasury::TreasuryAccountId<Runtime> as sp_core::TypedGet>::get(),
1
				existential_deposit(),
1
			),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			set_parachain_inherent_data();
1
			let issuance_before = <Runtime as pallet_evm::Config>::Currency::total_issuance();
1
			// EVM transfer.
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
1
				source: H160::from(BOB),
1
				target: H160::from(ALICE),
1
				input: Vec::new(),
1
				value: (1 * GLMR).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: BASE_FEE_GENESIS.into(),
1
				max_priority_fee_per_gas: Some(BASE_FEE_GENESIS.into()),
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
				authorization_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let issuance_after = <Runtime as pallet_evm::Config>::Currency::total_issuance();
1

            
1
			let base_fee = TransactionPaymentAsGasPrice::min_gas_price().0.as_u128();
1

            
1
			let base_fee: Balance = base_fee * 21_000;
1

            
1
			let treasury_proportion = dynamic_params::runtime_config::FeesTreasuryProportion::get();
1

            
1
			// only base fee is split between being burned and sent to treasury
1
			let treasury_base_fee_part: Balance = treasury_proportion.mul_floor(base_fee);
1
			let burnt_base_fee_part: Balance = base_fee - treasury_base_fee_part;
1

            
1
			assert_eq!(issuance_after, issuance_before - burnt_base_fee_part);
1
			assert_eq!(moonbeam_runtime::Treasury::pot(), treasury_base_fee_part);
1
		});
1
}
#[test]
1
fn root_can_change_default_xcm_vers() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_id: 1,
1
			xcm_location: AssetHubLocation::get(),
1
			name: "Dot",
1
			symbol: "Dot",
1
			decimals: 12,
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let source_id: moonbeam_runtime::AssetId = 1;
1
			let currency_id = moonbeam_runtime::xcm_config::CurrencyId::ForeignAsset(source_id);
1
			let asset = Asset {
1
				id: AssetId(
1
					<Runtime as pallet_xcm_transactor::Config>::CurrencyIdToLocation::convert(
1
						currency_id,
1
					)
1
					.unwrap(),
1
				),
1
				fun: Fungibility::Fungible(100_000_000_000_000),
1
			};
1
			// Default XCM version is not set yet, so xtokens should fail because it does not
1
			// know with which version to send
1
			assert_noop!(
1
				PolkadotXcm::transfer_assets(
1
					origin_of(AccountId::from(ALICE)),
1
					Box::new(VersionedLocation::from(Location::parent())),
1
					Box::new(VersionedLocation::from(Location {
1
						parents: 0,
1
						interior: [AccountId32 {
1
							network: None,
1
							id: [1u8; 32],
1
						}]
1
						.into(),
1
					})),
1
					Box::new(VersionedAssets::from(asset.clone())),
1
					0,
1
					WeightLimit::Unlimited
1
				),
1
				pallet_xcm::Error::<Runtime>::LocalExecutionIncomplete
1
			);
			// Root sets the defaultXcm
1
			assert_ok!(PolkadotXcm::force_default_xcm_version(
1
				root_origin(),
1
				Some(5)
1
			));
			// Now transferring does not fail
1
			assert_ok!(PolkadotXcm::transfer_assets(
1
				origin_of(AccountId::from(ALICE)),
1
				Box::new(VersionedLocation::from(Location::parent())),
1
				Box::new(VersionedLocation::from(Location {
1
					parents: 0,
1
					interior: [AccountId32 {
1
						network: None,
1
						id: [1u8; 32],
1
					}]
1
					.into(),
1
				})),
1
				Box::new(VersionedAssets::from(asset)),
1
				0,
1
				WeightLimit::Unlimited
1
			));
1
		})
1
}
#[test]
1
fn asset_can_be_registered() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		let source_location = Location::parent();
1
		let source_id = 1;
1

            
1
		assert_ok!(EvmForeignAssets::create_foreign_asset(
1
			moonbeam_runtime::RuntimeOrigin::root(),
1
			source_id,
1
			source_location.clone(),
1
			12,
1
			b"Relay".to_vec().try_into().unwrap(),
1
			b"RelayToken".to_vec().try_into().unwrap(),
1
		));
		// Check that the asset was created
		// First check if the asset ID exists
1
		let location = EvmForeignAssets::assets_by_id(source_id).expect("Asset should exist");
1
		assert_eq!(location.clone(), source_location);
		// Then check the status using AssetsByLocation
1
		let (asset_id, status) =
1
			EvmForeignAssets::assets_by_location(&location).expect("Asset location should exist");
1
		assert_eq!(asset_id, source_id);
1
		assert_eq!(status, AssetStatus::Active);
1
	});
1
}
// The precoompile asset-erc20 is deprecated and not used anymore for new evm foreign assets
// We don't have testing tools in rust test to call real evm smart contract, so we rely on ts tests.
/*
#[test]
fn xcm_asset_erc20_precompiles_supply_and_balance() {
	ExtBuilder::default()
		.with_xcm_assets(vec![XcmAssetInitialization {
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
			metadata: AssetRegistrarMetadata {
				name: b"RelayToken".to_vec(),
				symbol: b"Relay".to_vec(),
				decimals: 12,
				is_frozen: false,
			},
			balances: vec![(AccountId::from(ALICE), 1_000 * GLMR)],
			is_sufficient: true,
		}])
		.with_balances(vec![
			(AccountId::from(ALICE), 2_000 * GLMR),
			(AccountId::from(BOB), 1_000 * GLMR),
		])
		.build()
		.execute_with(|| {
			// We have the assetId that corresponds to the relay chain registered
			let relay_asset_id: moonbeam_runtime::AssetId =
				AssetType::Xcm(xcm::v3::Location::parent()).into();
			// Its address is
			let asset_precompile_address = Runtime::asset_id_to_account(
				FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
				relay_asset_id,
			);
			// Assert the asset has been created with the correct supply
			assert_eq!(
				moonbeam_runtime::Assets::total_supply(relay_asset_id),
				1_000 * GLMR
			);
			// Access totalSupply through precompile. Important that the context is correct
			Precompiles::new()
				.prepare_test(
					ALICE,
					asset_precompile_address,
					ForeignAssetsPCall::total_supply {},
				)
				.expect_cost(5007)
				.expect_no_logs()
				.execute_returns(U256::from(1000 * GLMR));
			// Access balanceOf through precompile
			Precompiles::new()
				.prepare_test(
					ALICE,
					asset_precompile_address,
					ForeignAssetsPCall::balance_of {
						who: Address(ALICE.into()),
					},
				)
				.expect_cost(5007)
				.expect_no_logs()
				.execute_returns(U256::from(1000 * GLMR));
		});
}
#[test]
fn xcm_asset_erc20_precompiles_transfer() {
	ExtBuilder::default()
		.with_xcm_assets(vec![XcmAssetInitialization {
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
			metadata: AssetRegistrarMetadata {
				name: b"RelayToken".to_vec(),
				symbol: b"Relay".to_vec(),
				decimals: 12,
				is_frozen: false,
			},
			balances: vec![(AccountId::from(ALICE), 1_000 * GLMR)],
			is_sufficient: true,
		}])
		.with_balances(vec![
			(AccountId::from(ALICE), 2_000 * GLMR),
			(AccountId::from(BOB), 1_000 * GLMR),
		])
		.build()
		.execute_with(|| {
			// We have the assetId that corresponds to the relay chain registered
			let relay_asset_id: moonbeam_runtime::AssetId =
				AssetType::Xcm(xcm::v3::Location::parent()).into();
			// Its address is
			let asset_precompile_address = Runtime::asset_id_to_account(
				FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
				relay_asset_id,
			);
			// Transfer tokens from Aice to Bob, 400 GLMR.
			Precompiles::new()
				.prepare_test(
					ALICE,
					asset_precompile_address,
					ForeignAssetsPCall::transfer {
						to: Address(BOB.into()),
						value: { 400 * GLMR }.into(),
					},
				)
				.expect_cost(26580)
				.expect_log(log3(
					asset_precompile_address,
					SELECTOR_LOG_TRANSFER,
					H160::from(ALICE),
					H160::from(BOB),
					solidity::encode_event_data(U256::from(400 * GLMR)),
				))
				.execute_returns(true);
			// Make sure BOB has 400 GLMR
			Precompiles::new()
				.prepare_test(
					BOB,
					asset_precompile_address,
					ForeignAssetsPCall::balance_of {
						who: Address(BOB.into()),
					},
				)
				.expect_cost(5007)
				.expect_no_logs()
				.execute_returns(U256::from(400 * GLMR));
		});
}
#[test]
fn xcm_asset_erc20_precompiles_approve() {
	ExtBuilder::default()
		.with_xcm_assets(vec![XcmAssetInitialization {
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
			metadata: AssetRegistrarMetadata {
				name: b"RelayToken".to_vec(),
				symbol: b"Relay".to_vec(),
				decimals: 12,
				is_frozen: false,
			},
			balances: vec![(AccountId::from(ALICE), 1_000 * GLMR)],
			is_sufficient: true,
		}])
		.with_balances(vec![
			(AccountId::from(ALICE), 2_000 * GLMR),
			(AccountId::from(BOB), 1_000 * GLMR),
		])
		.build()
		.execute_with(|| {
			// We have the assetId that corresponds to the relay chain registered
			let relay_asset_id: moonbeam_runtime::AssetId =
				AssetType::Xcm(xcm::v3::Location::parent()).into();
			// Its address is
			let asset_precompile_address = Runtime::asset_id_to_account(
				FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
				relay_asset_id,
			);
			// Aprove Bob for spending 400 GLMR from Alice
			Precompiles::new()
				.prepare_test(
					ALICE,
					asset_precompile_address,
					ForeignAssetsPCall::approve {
						spender: Address(BOB.into()),
						value: { 400 * GLMR }.into(),
					},
				)
				.expect_cost(17323)
				.expect_log(log3(
					asset_precompile_address,
					SELECTOR_LOG_APPROVAL,
					H160::from(ALICE),
					H160::from(BOB),
					solidity::encode_event_data(U256::from(400 * GLMR)),
				))
				.execute_returns(true);
			// Transfer tokens from Alice to Charlie by using BOB as origin
			Precompiles::new()
				.prepare_test(
					BOB,
					asset_precompile_address,
					ForeignAssetsPCall::transfer_from {
						from: Address(ALICE.into()),
						to: Address(CHARLIE.into()),
						value: { 400 * GLMR }.into(),
					},
				)
				.expect_cost(31887)
				.expect_log(log3(
					asset_precompile_address,
					SELECTOR_LOG_TRANSFER,
					H160::from(ALICE),
					H160::from(CHARLIE),
					solidity::encode_event_data(U256::from(400 * GLMR)),
				))
				.execute_returns(true);
			// Make sure CHARLIE has 400 GLMR
			Precompiles::new()
				.prepare_test(
					CHARLIE,
					asset_precompile_address,
					ForeignAssetsPCall::balance_of {
						who: Address(CHARLIE.into()),
					},
				)
				.expect_cost(5007)
				.expect_no_logs()
				.execute_returns(U256::from(400 * GLMR));
		});
}*/
#[test]
1
fn make_sure_glmr_can_be_transferred_precompile() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * GLMR)])
1
		.with_mappings(vec![(
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
1
			AccountId::from(ALICE),
1
		)])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			assert_ok!(PolkadotXcm::transfer_assets(
1
				origin_of(AccountId::from(ALICE)),
1
				Box::new(VersionedLocation::from(Location::parent())),
1
				Box::new(VersionedLocation::from(Location {
1
					parents: 0,
1
					interior: [AccountId32 {
1
						network: None,
1
						id: [1u8; 32],
1
					}]
1
					.into(),
1
				})),
1
				Box::new(VersionedAssets::from(Asset {
1
					id: AssetId(moonbeam_runtime::xcm_config::SelfReserve::get()),
1
					fun: Fungible(1000)
1
				})),
1
				0,
1
				WeightLimit::Limited(40000.into())
1
			));
1
		});
1
}
#[test]
1
fn make_sure_glmr_can_be_transferred() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * GLMR)])
1
		.with_mappings(vec![(
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
1
			AccountId::from(ALICE),
1
		)])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			let dest = Location {
1
				parents: 1,
1
				interior: [AccountId32 {
1
					network: None,
1
					id: [1u8; 32],
1
				}]
1
				.into(),
1
			};
1
			assert_ok!(PolkadotXcm::transfer_assets(
1
				origin_of(AccountId::from(ALICE)),
1
				Box::new(VersionedLocation::from(Location::parent())),
1
				Box::new(VersionedLocation::from(dest)),
1
				Box::new(VersionedAssets::from(Asset {
1
					id: AssetId(moonbeam_runtime::xcm_config::SelfReserve::get()),
1
					fun: Fungible(100)
1
				})),
1
				0,
1
				WeightLimit::Limited(40000.into())
1
			));
1
		});
1
}
#[test]
1
fn make_sure_polkadot_xcm_cannot_be_called() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * GLMR)])
1
		.with_mappings(vec![(
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
1
			AccountId::from(ALICE),
1
		)])
1
		.build()
1
		.execute_with(|| {
1
			let dest = Location {
1
				parents: 1,
1
				interior: [AccountId32 {
1
					network: None,
1
					id: [1u8; 32],
1
				}]
1
				.into(),
1
			};
1
			let assets: Assets = [Asset {
1
				id: AssetId(moonbeam_runtime::xcm_config::SelfLocation::get()),
1
				fun: Fungible(1000),
1
			}]
1
			.to_vec()
1
			.into();
1
			assert_noop!(
1
				RuntimeCall::PolkadotXcm(pallet_xcm::Call::<Runtime>::reserve_transfer_assets {
1
					dest: Box::new(VersionedLocation::from(dest.clone())),
1
					beneficiary: Box::new(VersionedLocation::from(dest)),
1
					assets: Box::new(VersionedAssets::from(assets)),
1
					fee_asset_item: 0,
1
				})
1
				.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::signed(
1
					AccountId::from(ALICE)
1
				)),
1
				frame_system::Error::<Runtime>::CallFiltered
1
			);
1
		});
1
}
#[test]
1
fn transact_through_signed_precompile_works_v2() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			// Destination
1
			let dest = Location::parent();
1

            
1
			let fee_payer_asset = Location::parent();
1

            
1
			let bytes = vec![1u8, 2u8, 3u8];
1

            
1
			let total_weight = 1_000_000_000u64;
1

            
1
			let xcm_transactor_v2_precompile_address = H160::from_low_u64_be(2061);
1

            
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					xcm_transactor_v2_precompile_address,
1
					XcmTransactorV2PCall::transact_through_signed_multilocation {
1
						dest,
1
						fee_asset: fee_payer_asset,
1
						weight: 4_000_000,
1
						call: bytes.into(),
1
						fee_amount: u128::from(total_weight).into(),
1
						overall_weight: total_weight,
1
					},
1
				)
1
				.expect_cost(31045)
1
				.expect_no_logs()
1
				.execute_returns(());
1
		});
1
}
#[test]
1
fn transact_through_signed_cannot_send_to_local_chain() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			// Destination
1
			let dest = Location::here();
1

            
1
			let fee_payer_asset = Location::parent();
1

            
1
			let bytes = vec![1u8, 2u8, 3u8];
1

            
1
			let total_weight = 1_000_000_000u64;
1

            
1
			let xcm_transactor_v2_precompile_address = H160::from_low_u64_be(2061);
1

            
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					xcm_transactor_v2_precompile_address,
1
					XcmTransactorV2PCall::transact_through_signed_multilocation {
1
						dest,
1
						fee_asset: fee_payer_asset,
1
						weight: 4_000_000,
1
						call: bytes.into(),
1
						fee_amount: u128::from(total_weight).into(),
1
						overall_weight: total_weight,
1
					},
1
				)
1
				.execute_reverts(|output| {
1
					from_utf8(&output)
1
						.unwrap()
1
						.contains("Dispatched call failed with error:")
1
						&& from_utf8(&output).unwrap().contains("ErrorValidating")
1
				});
1
		});
1
}
#[test]
1
fn transactor_cannot_use_more_than_max_weight() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_id: 1,
1
			xcm_location: xcm::v5::Location::parent(),
1
			name: "RelayToken",
1
			symbol: "Relay",
1
			decimals: 12,
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let source_id: moonbeam_runtime::AssetId = 1;
1
			assert_ok!(XcmTransactor::register(
1
				root_origin(),
1
				AccountId::from(ALICE),
1
				0,
1
			));
			// Root can set transact info
1
			assert_ok!(XcmTransactor::set_transact_info(
1
				root_origin(),
1
				Box::new(xcm::VersionedLocation::from(Location::parent())),
1
				// Relay charges 1000 for every instruction, and we have 3, so 3000
1
				3000.into(),
1
				20000.into(),
1
				None
1
			));
			// Root can set transact info
1
			assert_ok!(XcmTransactor::set_fee_per_second(
1
				root_origin(),
1
				Box::new(xcm::VersionedLocation::from(Location::parent())),
1
				1,
1
			));
1
			assert_noop!(
1
				XcmTransactor::transact_through_derivative(
1
					origin_of(AccountId::from(ALICE)),
1
					moonbeam_runtime::xcm_config::Transactors::Relay,
1
					0,
1
					CurrencyPayment {
1
						currency: Currency::AsMultiLocation(Box::new(
1
							xcm::VersionedLocation::from(Location::parent())
1
						)),
1
						fee_amount: None
1
					},
1
					vec![],
1
					// 20000 is the max
1
					TransactWeights {
1
						transact_required_weight_at_most: 17001.into(),
1
						overall_weight: None
1
					},
1
					false
1
				),
1
				pallet_xcm_transactor::Error::<Runtime>::MaxWeightTransactReached
1
			);
1
			assert_noop!(
1
				XcmTransactor::transact_through_derivative(
1
					origin_of(AccountId::from(ALICE)),
1
					moonbeam_runtime::xcm_config::Transactors::Relay,
1
					0,
1
					CurrencyPayment {
1
						currency: Currency::AsCurrencyId(
1
							moonbeam_runtime::xcm_config::CurrencyId::ForeignAsset(source_id)
1
						),
1
						fee_amount: None
1
					},
1
					vec![],
1
					// 20000 is the max
1
					TransactWeights {
1
						transact_required_weight_at_most: 17001.into(),
1
						overall_weight: None
1
					},
1
					false
1
				),
1
				pallet_xcm_transactor::Error::<Runtime>::MaxWeightTransactReached
1
			);
1
		})
1
}
// TODO: Unify all "call_pallet_xcm_with_fee" prefixed tests after the asset hub migration
#[test]
1
fn call_pallet_xcm_with_fee() {
1
	let asset_id = 1;
1

            
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_safe_xcm_version(3)
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_id,
1
			xcm_location: Location::parent(),
1
			name: "RelayToken",
1
			symbol: "Relay",
1
			decimals: 12,
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let dest = Location {
1
				parents: 1,
1
				interior: [AccountId32 {
1
					network: None,
1
					id: [1u8; 32],
1
				}]
1
				.into(),
1
			};
1

            
1
			let before_balance =
1
				EvmForeignAssets::balance(asset_id, AccountId::from(ALICE)).unwrap();
1
			let (chain_part, beneficiary) =
1
				split_location_into_chain_part_and_beneficiary(dest).unwrap();
1
			let asset_amount = 100_000_000_000_000u128;
1
			let asset_fee_amount = 100u128;
1
			let asset = currency_to_asset(CurrencyId::ForeignAsset(asset_id), asset_amount);
1
			let asset_fee = currency_to_asset(CurrencyId::ForeignAsset(asset_id), asset_fee_amount);
1
			// We are able to transfer with fee
1
			assert_ok!(PolkadotXcm::transfer_assets(
1
				origin_of(AccountId::from(ALICE)),
1
				Box::new(VersionedLocation::from(chain_part)),
1
				Box::new(VersionedLocation::from(beneficiary)),
1
				Box::new(VersionedAssets::from(vec![asset_fee, asset])),
1
				0,
1
				WeightLimit::Limited(4000000000.into())
1
			));
1
			let after_balance =
1
				EvmForeignAssets::balance(asset_id, AccountId::from(ALICE)).unwrap();
1
			// At least these much (plus fees) should have been charged
1
			assert_eq!(
1
				before_balance
1
					.saturating_sub(asset_amount.into())
1
					.saturating_sub(asset_fee_amount.into()),
1
				after_balance
1
			);
1
		});
1
}
// TODO: Unify all "call_pallet_xcm_with_fee" prefixed tests after the asset hub migration
#[test]
1
fn call_pallet_xcm_with_fee_after_ahm() {
1
	let asset_id = 1;
1
	ExtBuilder::default()
1
		.asset_hub_migration_has_started()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_safe_xcm_version(3)
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_id,
1
			xcm_location: Location::parent(),
1
			name: "RelayToken",
1
			symbol: "Relay",
1
			decimals: 12,
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let dest = Location {
1
				parents: 1,
1
				interior: [AccountId32 {
1
					network: None,
1
					id: [1u8; 32],
1
				}]
1
				.into(),
1
			};
1

            
1
			let before_balance =
1
				EvmForeignAssets::balance(asset_id, AccountId::from(ALICE)).unwrap();
1
			let (chain_part, beneficiary) =
1
				split_location_into_chain_part_and_beneficiary(dest).unwrap();
1
			let asset = currency_to_asset(CurrencyId::ForeignAsset(asset_id), 100_000_000_000_000);
1
			let asset_fee = currency_to_asset(CurrencyId::ForeignAsset(asset_id), 100);
1

            
1
			// Once the AH migration starts, we should no longer be able to use the parent location as reserve.
1
			assert_noop!(
1
				PolkadotXcm::transfer_assets(
1
					origin_of(AccountId::from(ALICE)),
1
					Box::new(VersionedLocation::from(chain_part)),
1
					Box::new(VersionedLocation::from(beneficiary)),
1
					Box::new(VersionedAssets::from(vec![asset_fee, asset])),
1
					0,
1
					WeightLimit::Limited(4000000000.into())
1
				),
1
				pallet_xcm::Error::<Runtime>::InvalidAssetUnknownReserve
1
			);
1
			let after_balance =
1
				EvmForeignAssets::balance(asset_id, AccountId::from(ALICE)).unwrap();
1
			// At least these much (plus fees) should have been charged
1
			assert_eq!(before_balance, after_balance);
1
		});
1
}
// TODO: Unify all "call_pallet_xcm_with_fee" prefixed tests after the asset hub migration
#[test]
1
fn call_pallet_xcm_with_fee_before_ahm() {
1
	let asset_id = 1;
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * GLMR),
1
			(AccountId::from(BOB), 1_000 * GLMR),
1
		])
1
		.with_safe_xcm_version(3)
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_id,
1
			xcm_location: Location::parent(),
1
			name: "RelayToken",
1
			symbol: "Relay",
1
			decimals: 12,
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let dest = Location {
1
				parents: 1,
1
				interior: [AccountId32 {
1
					network: None,
1
					id: [1u8; 32],
1
				}]
1
				.into(),
1
			};
1
			let before_balance =
1
				EvmForeignAssets::balance(asset_id, AccountId::from(ALICE)).unwrap();
1
			let (chain_part, beneficiary) =
1
				split_location_into_chain_part_and_beneficiary(dest).unwrap();
1
			let asset = currency_to_asset(CurrencyId::ForeignAsset(asset_id), 100_000_000_000_000);
1
			let asset_fee = currency_to_asset(CurrencyId::ForeignAsset(asset_id), 100);
1
			// We are able to transfer with fee
1
			assert_ok!(PolkadotXcm::transfer_assets(
1
				origin_of(AccountId::from(ALICE)),
1
				Box::new(VersionedLocation::from(chain_part)),
1
				Box::new(VersionedLocation::from(beneficiary)),
1
				Box::new(VersionedAssets::from(vec![asset_fee, asset])),
1
				0,
1
				WeightLimit::Limited(4000000000.into())
1
			));
1
			let after_balance =
1
				EvmForeignAssets::balance(asset_id, AccountId::from(ALICE)).unwrap();
1
			// At least these much (plus fees) should have been charged
1
			assert_eq!(
1
				before_balance - 100_000_000_000_000u128 - 100u128,
1
				after_balance
1
			);
1
		});
1
}
#[test]
1
fn test_xcm_utils_ml_tp_account() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		let xcm_utils_precompile_address = H160::from_low_u64_be(2060);
1
		let expected_address_parent: H160 =
1
			ParentIsPreset::<AccountId>::convert_location(&Location::parent())
1
				.unwrap()
1
				.into();
1

            
1
		Precompiles::new()
1
			.prepare_test(
1
				ALICE,
1
				xcm_utils_precompile_address,
1
				XcmUtilsPCall::multilocation_to_address {
1
					location: Location::parent(),
1
				},
1
			)
1
			.expect_cost(
1
				<Runtime as frame_system::Config>::DbWeight::get()
1
					.read
1
					.saturating_div(WEIGHT_PER_GAS)
1
					.saturating_mul(2),
1
			)
1
			.expect_no_logs()
1
			.execute_returns(Address(expected_address_parent));
1

            
1
		let parachain_2000_location = Location::new(1, [Parachain(2000)]);
1
		let expected_address_parachain: H160 =
1
			SiblingParachainConvertsVia::<Sibling, AccountId>::convert_location(
1
				&parachain_2000_location,
1
			)
1
			.unwrap()
1
			.into();
1

            
1
		Precompiles::new()
1
			.prepare_test(
1
				ALICE,
1
				xcm_utils_precompile_address,
1
				XcmUtilsPCall::multilocation_to_address {
1
					location: parachain_2000_location,
1
				},
1
			)
1
			.expect_cost(
1
				<Runtime as frame_system::Config>::DbWeight::get()
1
					.read
1
					.saturating_div(WEIGHT_PER_GAS)
1
					.saturating_mul(2),
1
			)
1
			.expect_no_logs()
1
			.execute_returns(Address(expected_address_parachain));
1

            
1
		let alice_in_parachain_2000_location = Location::new(
1
			1,
1
			[
1
				Parachain(2000),
1
				AccountKey20 {
1
					network: None,
1
					key: ALICE,
1
				},
1
			],
1
		);
1
		let expected_address_alice_in_parachain_2000 =
1
			xcm_builder::HashedDescription::<
1
				AccountId,
1
				xcm_builder::DescribeFamily<xcm_builder::DescribeAllTerminal>,
1
			>::convert_location(&alice_in_parachain_2000_location)
1
			.unwrap()
1
			.into();
1

            
1
		Precompiles::new()
1
			.prepare_test(
1
				ALICE,
1
				xcm_utils_precompile_address,
1
				XcmUtilsPCall::multilocation_to_address {
1
					location: alice_in_parachain_2000_location,
1
				},
1
			)
1
			.expect_cost(
1
				<Runtime as frame_system::Config>::DbWeight::get()
1
					.read
1
					.saturating_div(WEIGHT_PER_GAS)
1
					.saturating_mul(2),
1
			)
1
			.expect_no_logs()
1
			.execute_returns(Address(expected_address_alice_in_parachain_2000));
1
	});
1
}
#[test]
1
fn test_xcm_utils_weight_message() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		let xcm_utils_precompile_address = H160::from_low_u64_be(2060);
1
		let expected_weight =
1
			XcmWeight::<moonbeam_runtime::Runtime, RuntimeCall>::clear_origin().ref_time();
1

            
1
		let message: Vec<u8> = xcm::VersionedXcm::<()>::V5(Xcm(vec![ClearOrigin])).encode();
1

            
1
		let input = XcmUtilsPCall::weight_message {
1
			message: message.into(),
1
		};
1

            
1
		Precompiles::new()
1
			.prepare_test(ALICE, xcm_utils_precompile_address, input)
1
			.expect_cost(
1
				<Runtime as frame_system::Config>::DbWeight::get()
1
					.read
1
					.saturating_div(WEIGHT_PER_GAS),
1
			)
1
			.expect_no_logs()
1
			.execute_returns(expected_weight);
1
	});
1
}
#[test]
1
fn test_nested_batch_calls_from_xcm_transact() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		// This ensures we notice if MAX_XCM_DECODE_DEPTH changes
1
		// in a future polkadot-sdk version
1
		assert_eq!(xcm::MAX_XCM_DECODE_DEPTH, 8);
1
		let mut valid_nested_calls =
1
			RuntimeCall::System(frame_system::Call::remark { remark: vec![] });
9
		for _ in 0..xcm::MAX_XCM_DECODE_DEPTH {
8
			valid_nested_calls = RuntimeCall::Utility(pallet_utility::Call::batch {
8
				calls: vec![valid_nested_calls],
8
			});
8
		}
1
		let valid_message = Xcm(vec![Transact {
1
			origin_kind: OriginKind::SovereignAccount,
1
			fallback_max_weight: None,
1
			call: valid_nested_calls.encode().into(),
1
		}]);
1

            
1
		assert!(XcmExecutor::prepare(valid_message).is_ok());
1
		let excessive_nested_calls = RuntimeCall::Utility(pallet_utility::Call::batch {
1
			calls: vec![valid_nested_calls],
1
		});
1

            
1
		let invalid_message = Xcm(vec![Transact {
1
			origin_kind: OriginKind::SovereignAccount,
1
			fallback_max_weight: None,
1
			call: excessive_nested_calls.encode().into(),
1
		}]);
1
		// Expect to fail because we have too many nested calls
1
		assert!(XcmExecutor::prepare(invalid_message).is_err());
1
	});
1
}
#[test]
1
fn test_xcm_utils_get_units_per_second() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		let xcm_utils_precompile_address = H160::from_low_u64_be(2060);
1
		let location = SelfReserve::get();
1

            
1
		let input = XcmUtilsPCall::get_units_per_second { location };
1

            
1
		let expected_units =
1
			WEIGHT_REF_TIME_PER_SECOND as u128 * moonbeam_runtime::currency::WEIGHT_FEE;
1

            
1
		Precompiles::new()
1
			.prepare_test(ALICE, xcm_utils_precompile_address, input)
1
			.expect_cost(
1
				<Runtime as frame_system::Config>::DbWeight::get()
1
					.read
1
					.saturating_div(WEIGHT_PER_GAS)
1
					.saturating_mul(2),
1
			)
1
			.expect_no_logs()
1
			.execute_returns(expected_units);
1
	});
1
}
#[test]
1
fn precompile_existence() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		let precompiles = Precompiles::new();
1
		let precompile_addresses: std::collections::BTreeSet<_> = vec![
1
			1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 256, 1024, 1025, 1026, 2048,
1
			2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062,
1
			2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075,
1
		]
1
		.into_iter()
1
		.map(H160::from_low_u64_be)
1
		.collect();
3001
		for i in 0..3000 {
3000
			let address = H160::from_low_u64_be(i);
3000

            
3000
			if precompile_addresses.contains(&address) {
48
				assert!(
48
					is_precompile_or_fail::<Runtime>(address, 100_000u64).expect("to be ok"),
					"is_precompile({}) should return true",
					i
				);
48
				assert!(
48
					precompiles
48
						.execute(&mut MockHandle::new(
48
							address,
48
							Context {
48
								address,
48
								caller: H160::zero(),
48
								apparent_value: U256::zero()
48
							}
48
						),)
48
						.is_some(),
					"execute({},..) should return Some(_)",
					i
				);
			} else {
2952
				assert!(
2952
					!is_precompile_or_fail::<Runtime>(address, 100_000u64).expect("to be ok"),
					"is_precompile({}) should return false",
					i
				);
2952
				assert!(
2952
					precompiles
2952
						.execute(&mut MockHandle::new(
2952
							address,
2952
							Context {
2952
								address,
2952
								caller: H160::zero(),
2952
								apparent_value: U256::zero()
2952
							}
2952
						),)
2952
						.is_none(),
					"execute({},..) should return None",
					i
				);
			}
		}
1
	});
1
}
#[test]
1
fn removed_precompiles() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		let precompiles = Precompiles::new();
1
		let removed_precompiles = [1025, 1027, 2051, 2062, 2063];
3000
		for i in 1..3000 {
2999
			let address = H160::from_low_u64_be(i);
2999

            
2999
			if !is_precompile_or_fail::<Runtime>(address, 100_000u64).expect("to be ok") {
2951
				continue;
48
			}
48

            
48
			if !removed_precompiles.contains(&i) {
44
				assert!(
44
					match precompiles.is_active_precompile(address, 100_000u64) {
44
						IsPrecompileResult::Answer { is_precompile, .. } => is_precompile,
						_ => false,
					},
					"{i} should be an active precompile"
				);
44
				continue;
4
			}
4

            
4
			assert!(
4
				!match precompiles.is_active_precompile(address, 100_000u64) {
4
					IsPrecompileResult::Answer { is_precompile, .. } => is_precompile,
					_ => false,
				},
				"{i} shouldn't be an active precompile"
			);
4
			precompiles
4
				.prepare_test(Alice, address, [])
4
				.execute_reverts(|out| out == b"Removed precompile");
4
		}
1
	})
1
}
#[test]
1
fn deal_with_fees_handles_tip() {
	use frame_support::traits::OnUnbalanced;
	use moonbeam_runtime::Treasury;
	use moonbeam_runtime_common::deal_with_fees::DealWithSubstrateFeesAndTip;
1
	ExtBuilder::default().build().execute_with(|| {
1
		set_parachain_inherent_data();
1
		// This test validates the functionality of the `DealWithSubstrateFeesAndTip` trait implementation
1
		// in the Moonbeam runtime. It verifies that:
1
		// - The correct proportion of the fee is sent to the treasury.
1
		// - The remaining fee is burned (removed from the total supply).
1
		// - The entire tip is sent to the block author.
1

            
1
		// The test details:
1
		// 1. Simulate issuing a `fee` of 100 and a `tip` of 1000.
1
		// 2. Confirm the initial total supply is 1,100 (equal to the sum of the issued fee and tip).
1
		// 3. Confirm the treasury's balance is initially 0.
1
		// 4. Execute the `DealWithSubstrateFeesAndTip::on_unbalanceds` function with the `fee` and `tip`.
1
		// 5. Validate that the treasury's balance has increased by 20% of the fee (based on FeesTreasuryProportion).
1
		// 6. Validate that 80% of the fee is burned, and the total supply decreases accordingly.
1
		// 7. Validate that the entire tip (100%) is sent to the block author (collator).
1

            
1
		// Step 1: Issue the fee and tip amounts.
1
		let fee = <pallet_balances::Pallet<Runtime> as frame_support::traits::fungible::Balanced<
1
			AccountId,
1
		>>::issue(100);
1
		let tip = <pallet_balances::Pallet<Runtime> as frame_support::traits::fungible::Balanced<
1
			AccountId,
1
		>>::issue(1000);
1

            
1
		// Step 2: Validate the initial supply and balances.
1
		let total_supply_before = Balances::total_issuance();
1
		let block_author = pallet_author_inherent::Pallet::<Runtime>::get();
1
		let block_author_balance_before = Balances::free_balance(&block_author);
1
		assert_eq!(total_supply_before, 1_100);
1
		assert_eq!(Balances::free_balance(&Treasury::account_id()), 0);
		// Step 3: Execute the fees handling logic.
1
		DealWithSubstrateFeesAndTip::<
1
			Runtime,
1
			dynamic_params::runtime_config::FeesTreasuryProportion,
1
		>::on_unbalanceds(vec![fee, tip].into_iter());
1

            
1
		// Step 4: Compute the split between treasury and burned fees based on FeesTreasuryProportion (20%).
1
		let treasury_proportion = dynamic_params::runtime_config::FeesTreasuryProportion::get();
1

            
1
		let treasury_fee_part: Balance = treasury_proportion.mul_floor(100);
1
		let burnt_fee_part: Balance = 100 - treasury_fee_part;
1

            
1
		// Step 5: Validate the treasury received 20% of the fee.
1
		assert_eq!(
1
			Balances::free_balance(&Treasury::account_id()),
1
			treasury_fee_part,
1
		);
		// Step 6: Verify that 80% of the fee was burned (removed from the total supply).
1
		let total_supply_after = Balances::total_issuance();
1
		assert_eq!(total_supply_before - total_supply_after, burnt_fee_part,);
		// Step 7: Validate that the block author (collator) received 100% of the tip.
1
		let block_author_balance_after = Balances::free_balance(&block_author);
1
		assert_eq!(
1
			block_author_balance_after - block_author_balance_before,
1
			1000,
1
		);
1
	});
1
}
#[test]
1
fn evm_revert_substrate_events() {
1
	ExtBuilder::default()
1
		.with_balances(vec![(AccountId::from(ALICE), 100_000 * GLMR)])
1
		.build()
1
		.execute_with(|| {
1
			let batch_precompile_address = H160::from_low_u64_be(2056);
1

            
1
			// Batch a transfer followed by an invalid call to batch.
1
			// Thus BatchAll will revert the transfer.
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::call {
1
				source: ALICE.into(),
1
				target: batch_precompile_address,
1

            
1
				input: BatchPCall::batch_all {
1
					to: vec![Address(BOB.into()), Address(batch_precompile_address)].into(),
1
					value: vec![U256::from(1 * GLMR), U256::zero()].into(),
1
					call_data: vec![].into(),
1
					gas_limit: vec![].into()
1
				}
1
				.into(),
1
				value: U256::zero(), // No value sent in EVM
1
				gas_limit: 500_000,
1
				max_fee_per_gas: BASE_FEE_GENESIS.into(),
1
				max_priority_fee_per_gas: None,
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
				authorization_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let transfer_count = System::events()
1
				.iter()
4
				.filter(|r| match r.event {
					RuntimeEvent::Balances(pallet_balances::Event::Transfer { .. }) => true,
6
					_ => false,
6
				})
1
				.count();
1

            
1
			assert_eq!(transfer_count, 0, "there should be no transfer event");
1
		});
1
}
#[test]
1
fn evm_success_keeps_substrate_events() {
1
	ExtBuilder::default()
1
		.with_balances(vec![(AccountId::from(ALICE), 100_000 * GLMR)])
1
		.build()
1
		.execute_with(|| {
1
			let batch_precompile_address = H160::from_low_u64_be(2056);
1

            
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::call {
1
				source: ALICE.into(),
1
				target: batch_precompile_address,
1
				input: BatchPCall::batch_all {
1
					to: vec![Address(BOB.into())].into(),
1
					value: vec![U256::from(1 * GLMR)].into(),
1
					call_data: vec![].into(),
1
					gas_limit: vec![].into()
1
				}
1
				.into(),
1
				value: U256::zero(), // No value sent in EVM
1
				gas_limit: 500_000,
1
				max_fee_per_gas: BASE_FEE_GENESIS.into(),
1
				max_priority_fee_per_gas: None,
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
				authorization_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let transfer_count = System::events()
1
				.iter()
6
				.filter(|r| match r.event {
1
					RuntimeEvent::Balances(pallet_balances::Event::Transfer { .. }) => true,
9
					_ => false,
10
				})
1
				.count();
1

            
1
			assert_eq!(transfer_count, 1, "there should be 1 transfer event");
1
		});
1
}
#[cfg(test)]
mod bridge_tests {
	use crate::common::{origin_of, root_origin, ExtBuilder, XcmAssetInitialization, ALICE, BOB};
	use crate::currency_to_asset;
	use bp_messages::target_chain::DispatchMessageData;
	use bp_messages::ReceptionResult;
	use bp_runtime::messages::MessageDispatchResult;
	use cumulus_primitives_core::AggregateMessageOrigin;
	use frame_support::assert_ok;
	use frame_support::pallet_prelude::{Hooks, PalletInfoAccess};
	use moonbeam_core_primitives::AccountId;
	use moonbeam_runtime::bridge_config::{
		KusamaGlobalConsensusNetwork, WithKusamaMessagesInstance,
	};
	use moonbeam_runtime::currency::GLMR;
	use moonbeam_runtime::xcm_config::CurrencyId;
	use moonbeam_runtime::{
		Balances, BridgeKusamaMessages, BridgeXcmOverMoonriver, MessageQueue, PolkadotXcm, Runtime,
		RuntimeEvent, System,
	};
	use pallet_bridge_messages::{LanesManager, StoredMessagePayload};
	use pallet_xcm_bridge::XcmBlobMessageDispatchResult::Dispatched;
	use parity_scale_codec::{Decode, Encode};
	use sp_core::H256;
	use xcm::latest::Junctions::X1;
	use xcm::latest::{Junctions, Location, NetworkId, WeightLimit, Xcm};
	use xcm::prelude::{
		AccountKey20, Asset, AssetFilter, AssetId, BuyExecution, ClearOrigin, DepositAsset,
		DescendOrigin, Fungible, GlobalConsensus, PalletInstance, Parachain, ReserveAssetDeposited,
		SetTopic, UniversalOrigin, XCM_VERSION,
	};
	use xcm::v5::WildAsset;
	use xcm::{VersionedAssets, VersionedInteriorLocation, VersionedLocation, VersionedXcm};
	use xcm_builder::BridgeMessage;
1
	fn next_block() {
1
		System::reset_events();
1
		System::set_block_number(System::block_number() + 1u32);
1
		System::on_initialize(System::block_number());
1
		MessageQueue::on_initialize(System::block_number());
1
	}
	#[test]
1
	fn transfer_asset_moonbeam_to_moonriver() {
1
		frame_support::__private::sp_tracing::init_for_tests();
1

            
1
		ExtBuilder::default()
1
			.with_balances(vec![
1
				(AccountId::from(ALICE), 2_000 * GLMR),
1
				(AccountId::from(BOB), 1_000 * GLMR),
1
			])
1
			.with_safe_xcm_version(XCM_VERSION)
1
			.with_open_bridges(vec![(
1
				Location::new(
1
					1,
1
					[Parachain(
1
						<bp_moonbeam::Moonbeam as bp_runtime::Parachain>::PARACHAIN_ID,
1
					)],
1
				),
1
				Junctions::from([
1
					NetworkId::Kusama.into(),
1
					Parachain(<bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID),
1
				]),
1
				Some(bp_moonbeam::LaneId::from_inner(H256([0u8; 32])))
1
			)])
1
			.build()
1
			.execute_with(|| {
1
				assert_ok!(PolkadotXcm::force_xcm_version(
1
					root_origin(),
1
					Box::new(bp_moonriver::GlobalConsensusLocation::get()),
1
					XCM_VERSION
1
				));
1
				let asset = currency_to_asset(CurrencyId::SelfReserve, 100 * GLMR);
1

            
1
				let message_data = BridgeKusamaMessages::outbound_message_data(
1
					bp_moonriver::LaneId::from_inner(H256([0u8; 32])),
1
					1u64,
1
				);
1
				assert!(message_data.is_none());
1
				assert_ok!(PolkadotXcm::transfer_assets(
1
					origin_of(AccountId::from(ALICE)),
1
					Box::new(VersionedLocation::V5(bp_moonriver::GlobalConsensusLocation::get())),
1
					Box::new(VersionedLocation::V5(Location {
1
						parents: 0,
1
						interior: [AccountKey20 {
1
							network: None,
1
							key: ALICE,
1
						}]
1
						.into(),
1
					})),
1
					Box::new(VersionedAssets::V5(asset.into())),
1
					0,
1
					WeightLimit::Unlimited
1
				));
1
				let message_data = BridgeKusamaMessages::outbound_message_data(
1
					bp_moonriver::LaneId::from_inner(H256([0u8; 32])),
1
					1u64,
1
				).unwrap();
1
				let decoded: StoredMessagePayload::<Runtime, WithKusamaMessagesInstance> = Decode::decode(&mut &message_data[..]).unwrap();
1

            
1
				let BridgeMessage { universal_dest, message } =
1
					Decode::decode(&mut &decoded[..]).unwrap();
1

            
1
				let expected_universal_dest: VersionedInteriorLocation = bp_moonriver::GlobalConsensusLocation::get().interior.into();
1
				assert_eq!(universal_dest, expected_universal_dest);
1
				assert_eq!(
1
					message,
1
					VersionedXcm::V5(
1
						Xcm(
1
							[
1
								UniversalOrigin(GlobalConsensus(NetworkId::Polkadot)),
1
								DescendOrigin(X1([Parachain(<bp_moonbeam::Moonbeam as bp_runtime::Parachain>::PARACHAIN_ID)].into())),
1
								ReserveAssetDeposited(
1
									vec![
1
										Asset {
1
											id: AssetId(
1
												Location::new(
1
													2,
1
													[
1
														GlobalConsensus(NetworkId::Polkadot),
1
														Parachain(<bp_moonbeam::Moonbeam as bp_runtime::Parachain>::PARACHAIN_ID),
1
														PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
1
													]
1
												)
1
											),
1
											fun: Fungible(100_000_000_000_000_000_000)
1
										}
1
									].into()
1
								),
1
								ClearOrigin,
1
								BuyExecution {
1
									fees: Asset {
1
										id: AssetId(
1
											Location::new(
1
												2,
1
												[
1
													GlobalConsensus(NetworkId::Polkadot),
1
													Parachain(<bp_moonbeam::Moonbeam as bp_runtime::Parachain>::PARACHAIN_ID),
1
													PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
1
												]
1
											)
1
										),
1
										fun: Fungible(100_000_000_000_000_000_000)
1
									},
1
									weight_limit: WeightLimit::Unlimited
1
								},
1
								DepositAsset {
1
									assets: AssetFilter::Wild(WildAsset::AllCounted(1)),
1
									beneficiary: Location::new(0, [AccountKey20 { network: None, key: ALICE}]),
1
								},
1
								SetTopic([24, 73, 92, 41, 231, 15, 196, 44, 136, 120, 145, 143, 224, 187, 112, 187, 47, 89, 154, 44, 193, 175, 174, 249, 30, 194, 97, 183, 171, 39, 87, 147])
1
							].into()
1
						)
1
					)
1
				);
1
			})
1
	}
	#[test]
1
	fn receive_message_from_moonriver() {
1
		frame_support::__private::sp_tracing::init_for_tests();
1

            
1
		ExtBuilder::default()
1
			.with_balances(vec![
1
				(AccountId::from(ALICE), 2_000 * GLMR),
1
				(AccountId::from(BOB), 1_000 * GLMR),
1
			])
1
			.with_xcm_assets(vec![XcmAssetInitialization {
1
				asset_id: 1,
1
				xcm_location: Location::new(
1
					2,
1
					[
1
						GlobalConsensus(KusamaGlobalConsensusNetwork::get()),
1
						Parachain(<bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID),
1
						PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
1
					]
1
				),
1
				name: "xcMOVR",
1
				symbol: "xcMOVR",
1
				decimals: 18,
1
				balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
			}])
1
			.with_safe_xcm_version(XCM_VERSION)
1
			.with_open_bridges(vec![(
1
				Location::new(
1
					1,
1
					[Parachain(
1
						<bp_moonbeam::Moonbeam as bp_runtime::Parachain>::PARACHAIN_ID,
1
					)],
1
				),
1
				Junctions::from([
1
					NetworkId::Kusama.into(),
1
					Parachain(<bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID),
1
				]),
1
				Some(bp_moonriver::LaneId::from_inner(H256([0u8; 32]))),
1
			)])
1
			.build()
1
			.execute_with(|| {
1
				assert_ok!(PolkadotXcm::force_xcm_version(
1
					root_origin(),
1
					Box::new(bp_moonriver::GlobalConsensusLocation::get()),
1
					XCM_VERSION
1
				));
1
				let bridge_message: BridgeMessage = BridgeMessage {
1
					universal_dest: VersionedInteriorLocation::V5(
1
						[
1
							GlobalConsensus(NetworkId::Polkadot),
1
							Parachain(<bp_moonbeam::Moonbeam as bp_runtime::Parachain>::PARACHAIN_ID)
1
						].into()
1
					),
1
					message: VersionedXcm::V5(
1
						Xcm(
1
							[
1
								UniversalOrigin(GlobalConsensus(NetworkId::Kusama)),
1
								DescendOrigin(X1([Parachain(<bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID)].into())),
1
								ReserveAssetDeposited(
1
									vec![
1
										Asset {
1
											id: AssetId(
1
												Location::new(
1
													2,
1
													[
1
														GlobalConsensus(NetworkId::Kusama),
1
														Parachain(<bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID),
1
														PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
1
													]
1
												)
1
											),
1
											fun: Fungible(10_000_000_000_000_000_000_000_000_000_000_000)
1
										}
1
									].into()
1
								),
1
								ClearOrigin,
1
								BuyExecution {
1
									fees: Asset {
1
										id: AssetId(
1
											Location::new(
1
												2,
1
												[
1
													GlobalConsensus(NetworkId::Kusama),
1
													Parachain(<bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID),
1
													PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
1
												]
1
											)
1
										),
1
										fun: Fungible(6_000_000_000_000_000_000_000_000_000_000_000)
1
									},
1
									weight_limit: WeightLimit::Unlimited
1
								},
1
								DepositAsset {
1
									assets: AssetFilter::Wild(WildAsset::AllCounted(1)),
1
									beneficiary: Location::new(0, [AccountKey20 { network: None, key: ALICE }]),
1
								},
1
								SetTopic([24, 73, 92, 41, 231, 15, 196, 44, 136, 120, 145, 143, 224, 187, 112, 187, 47, 89, 154, 44, 193, 175, 174, 249, 30, 194, 97, 183, 171, 39, 87, 147])
1
							].into()
1
						)
1
					)
1
				};
1

            
1
				let mut inbound_lane = LanesManager::<Runtime, WithKusamaMessagesInstance>::new()
1
					.active_inbound_lane(Default::default())
1
					.unwrap();
1

            
1
				let msg = DispatchMessageData { payload: Ok(bridge_message.encode()) };
1
	 			let result = inbound_lane.receive_message::<BridgeXcmOverMoonriver>(&AccountId::from(ALICE),
1
					1,
1
					msg,
1
				);
1

            
1
				assert_eq!(result, ReceptionResult::Dispatched(MessageDispatchResult { unspent_weight: Default::default(), dispatch_level_result: Dispatched }));
				// Produce next block
1
				next_block();
1
				// Confirm that the xcm message was successfully processed
7
				assert!(System::events().iter().any(|evt| {
1
					matches!(
1
						evt.event,
						RuntimeEvent::MessageQueue(
							pallet_message_queue::Event::Processed {
								origin: AggregateMessageOrigin::Here,
								success: true,
								..
							}
						)
					)
7
				}));
1
			});
1
	}
}
#[cfg(test)]
mod treasury_tests {
	use super::*;
	use frame_support::traits::fungible::NativeOrWithId;
	use moonbeam_runtime::XcmWeightTrader;
	use sp_core::bounded_vec;
	use sp_runtime::traits::Hash;
4
	fn expect_events(events: Vec<RuntimeEvent>) {
4
		let block_events: Vec<RuntimeEvent> =
29
			System::events().into_iter().map(|r| r.event).collect();
4

            
7
		assert!(events.iter().all(|evt| block_events.contains(evt)))
4
	}
7
	fn next_block() {
7
		System::reset_events();
7
		System::set_block_number(System::block_number() + 1u32);
7
		System::on_initialize(System::block_number());
7
		Treasury::on_initialize(System::block_number());
7
	}
3
	fn get_asset_balance(id: &u128, account: &AccountId) -> U256 {
3
		pallet_moonbeam_foreign_assets::Pallet::<Runtime>::balance(id.clone(), account.clone())
3
			.expect("failed to get account balance")
3
	}
	#[test]
1
	fn test_treasury_spend_local_with_council_origin() {
1
		let initial_treasury_balance = 1_000 * GLMR;
1
		ExtBuilder::default()
1
			.with_balances(vec![
1
				(AccountId::from(ALICE), 2_000 * GLMR),
1
				(Treasury::account_id(), initial_treasury_balance),
1
			])
1
			.build()
1
			.execute_with(|| {
1
				let spend_amount = 100u128 * GLMR;
1
				let spend_beneficiary = AccountId::from(BOB);
1

            
1
				next_block();
1

            
1
				// TreasuryCouncilCollective
1
				assert_ok!(TreasuryCouncilCollective::set_members(
1
					root_origin(),
1
					vec![AccountId::from(ALICE)],
1
					Some(AccountId::from(ALICE)),
1
					1
1
				));
1
				next_block();
1

            
1
				// Perform treasury spending
1
				let valid_from = System::block_number() + 5u32;
1
				let proposal = RuntimeCall::Treasury(pallet_treasury::Call::spend {
1
					amount: spend_amount,
1
					asset_kind: Box::new(NativeOrWithId::Native),
1
					beneficiary: Box::new(AccountId::from(BOB)),
1
					valid_from: Some(valid_from),
1
				});
1
				assert_ok!(TreasuryCouncilCollective::propose(
1
					origin_of(AccountId::from(ALICE)),
1
					1,
1
					Box::new(proposal.clone()),
1
					1_000
1
				));
1
				let payout_period =
1
					<<Runtime as pallet_treasury::Config>::PayoutPeriod as Get<u32>>::get();
1
				let expected_events = [
1
					RuntimeEvent::Treasury(pallet_treasury::Event::AssetSpendApproved {
1
						index: 0,
1
						asset_kind: NativeOrWithId::Native,
1
						amount: spend_amount,
1
						beneficiary: spend_beneficiary,
1
						valid_from,
1
						expire_at: payout_period + valid_from,
1
					}),
1
					RuntimeEvent::TreasuryCouncilCollective(pallet_collective::Event::Executed {
1
						proposal_hash: sp_runtime::traits::BlakeTwo256::hash_of(&proposal),
1
						result: Ok(()),
1
					}),
1
				]
1
				.to_vec();
1
				expect_events(expected_events);
6
				while System::block_number() < valid_from {
5
					next_block();
5
				}
1
				assert_ok!(Treasury::payout(origin_of(spend_beneficiary), 0));
1
				let expected_events = [
1
					RuntimeEvent::Treasury(pallet_treasury::Event::Paid {
1
						index: 0,
1
						payment_id: (),
1
					}),
1
					RuntimeEvent::Balances(pallet_balances::Event::Transfer {
1
						from: Treasury::account_id(),
1
						to: spend_beneficiary,
1
						amount: spend_amount,
1
					}),
1
				]
1
				.to_vec();
1
				expect_events(expected_events);
1
			});
1
	}
	#[test]
1
	fn test_treasury_spend_foreign_asset_with_council_origin() {
1
		let initial_treasury_balance = 1_000 * GLMR;
1
		let asset_id = 1000100010001000u128;
1
		ExtBuilder::default()
1
			.with_balances(vec![(AccountId::from(ALICE), 2_000 * GLMR)])
1
			.build()
1
			.execute_with(|| {
1
				let spend_amount = 100u128 * GLMR;
1
				let spend_beneficiary = AccountId::from(BOB);
1

            
1
				let asset_location: Location = Location {
1
					parents: 1,
1
					interior: Junctions::Here,
1
				};
1

            
1
				assert_ok!(EvmForeignAssets::create_foreign_asset(
1
					root_origin(),
1
					asset_id,
1
					asset_location.clone(),
1
					12,
1
					bounded_vec![b'M', b'T'],
1
					bounded_vec![b'M', b'y', b'T', b'o', b'k'],
1
				));
1
				assert_ok!(XcmWeightTrader::add_asset(
1
					root_origin(),
1
					asset_location,
1
					1u128
1
				));
1
				assert_ok!(EvmForeignAssets::mint_into(
1
					asset_id,
1
					Treasury::account_id(),
1
					initial_treasury_balance.into()
1
				));
1
				assert_eq!(
1
					get_asset_balance(&asset_id, &Treasury::account_id()),
1
					initial_treasury_balance.into(),
					"Treasury balance not updated"
				);
				// TreasuryCouncilCollective
1
				assert_ok!(TreasuryCouncilCollective::set_members(
1
					root_origin(),
1
					vec![AccountId::from(ALICE)],
1
					Some(AccountId::from(ALICE)),
1
					1
1
				));
				// Perform treasury spending
1
				let proposal = RuntimeCall::Treasury(pallet_treasury::Call::spend {
1
					amount: spend_amount,
1
					asset_kind: Box::new(NativeOrWithId::WithId(asset_id)),
1
					beneficiary: Box::new(spend_beneficiary),
1
					valid_from: None,
1
				});
1
				assert_ok!(TreasuryCouncilCollective::propose(
1
					origin_of(AccountId::from(ALICE)),
1
					1,
1
					Box::new(proposal.clone()),
1
					1_000
1
				));
1
				let payout_period =
1
					<<Runtime as pallet_treasury::Config>::PayoutPeriod as Get<u32>>::get();
1

            
1
				let current_block = System::block_number();
1
				let expected_events = [
1
					RuntimeEvent::Treasury(pallet_treasury::Event::AssetSpendApproved {
1
						index: 0,
1
						asset_kind: NativeOrWithId::WithId(asset_id),
1
						amount: spend_amount,
1
						beneficiary: spend_beneficiary,
1
						valid_from: current_block,
1
						expire_at: current_block + payout_period,
1
					}),
1
					RuntimeEvent::TreasuryCouncilCollective(pallet_collective::Event::Executed {
1
						proposal_hash: sp_runtime::traits::BlakeTwo256::hash_of(&proposal),
1
						result: Ok(()),
1
					}),
1
				]
1
				.to_vec();
1
				expect_events(expected_events);
1

            
1
				assert_ok!(Treasury::payout(origin_of(spend_beneficiary), 0));
1
				expect_events(vec![RuntimeEvent::Treasury(pallet_treasury::Event::Paid {
1
					index: 0,
1
					payment_id: (),
1
				})]);
1

            
1
				assert_eq!(
1
					get_asset_balance(&asset_id, &Treasury::account_id()),
1
					(initial_treasury_balance - spend_amount).into(),
					"Treasury balance not updated"
				);
1
				assert_eq!(
1
					get_asset_balance(&asset_id, &spend_beneficiary),
1
					spend_amount.into(),
					"Treasury payout failed"
				);
1
			});
1
	}
}
#[cfg(test)]
mod fee_tests {
	use super::*;
	use fp_evm::FeeCalculator;
	use frame_support::{
		traits::{ConstU128, OnFinalize},
		weights::{ConstantMultiplier, WeightToFee},
	};
	use moonbeam_runtime::{
		currency, LengthToFee, MinimumMultiplier, RuntimeBlockWeights, SlowAdjustingFeeUpdate,
		TargetBlockFullness, TransactionPaymentAsGasPrice, NORMAL_WEIGHT, WEIGHT_PER_GAS,
	};
	use sp_core::Get;
	use sp_runtime::{BuildStorage, FixedPointNumber, Perbill};
1
	fn run_with_system_weight<F>(w: Weight, mut assertions: F)
1
	where
1
		F: FnMut() -> (),
1
	{
1
		let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
1
			.build_storage()
1
			.unwrap()
1
			.into();
1
		t.execute_with(|| {
1
			System::set_block_consumed_resources(w, 0);
1
			assertions()
1
		});
1
	}
	#[test]
1
	fn test_multiplier_can_grow_from_zero() {
1
		let minimum_multiplier = MinimumMultiplier::get();
1
		let target = TargetBlockFullness::get()
1
			* RuntimeBlockWeights::get()
1
				.get(DispatchClass::Normal)
1
				.max_total
1
				.unwrap();
1
		// if the min is too small, then this will not change, and we are doomed forever.
1
		// the weight is 1/100th bigger than target.
1
		run_with_system_weight(target * 101 / 100, || {
1
			let next = SlowAdjustingFeeUpdate::<Runtime>::convert(minimum_multiplier);
1
			assert!(
1
				next > minimum_multiplier,
				"{:?} !>= {:?}",
				next,
				minimum_multiplier
			);
1
		})
1
	}
	#[test]
1
	fn test_fee_calculation() {
1
		let base_extrinsic = RuntimeBlockWeights::get()
1
			.get(DispatchClass::Normal)
1
			.base_extrinsic;
1
		let multiplier = sp_runtime::FixedU128::from_float(0.999000000000000000);
1
		let extrinsic_len = 100u32;
1
		let extrinsic_weight = 5_000u64;
1
		let tip = 42u128;
		type WeightToFeeImpl = ConstantMultiplier<u128, ConstU128<{ currency::WEIGHT_FEE }>>;
		type LengthToFeeImpl = LengthToFee;
		// base_fee + (multiplier * extrinsic_weight_fee) + extrinsic_length_fee + tip
1
		let expected_fee =
1
			WeightToFeeImpl::weight_to_fee(&base_extrinsic)
1
				+ multiplier.saturating_mul_int(WeightToFeeImpl::weight_to_fee(
1
					&Weight::from_parts(extrinsic_weight, 1),
1
				)) + LengthToFeeImpl::weight_to_fee(&Weight::from_parts(extrinsic_len as u64, 1))
1
				+ tip;
1

            
1
		let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
1
			.build_storage()
1
			.unwrap()
1
			.into();
1
		t.execute_with(|| {
1
			pallet_transaction_payment::NextFeeMultiplier::<Runtime>::set(multiplier);
1
			let actual_fee = TransactionPayment::compute_fee(
1
				extrinsic_len,
1
				&frame_support::dispatch::DispatchInfo {
1
					class: DispatchClass::Normal,
1
					pays_fee: frame_support::dispatch::Pays::Yes,
1
					call_weight: Weight::from_parts(extrinsic_weight, 1),
1
					extension_weight: Weight::zero(),
1
				},
1
				tip,
1
			);
1

            
1
			assert_eq!(
				expected_fee,
				actual_fee,
				"The actual fee did not match the expected fee, diff {}",
				actual_fee - expected_fee
			);
1
		});
1
	}
	#[test]
1
	fn test_min_gas_price_is_deterministic() {
1
		let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
1
			.build_storage()
1
			.unwrap()
1
			.into();
1
		t.execute_with(|| {
1
			let multiplier = sp_runtime::FixedU128::from_u32(1);
1
			pallet_transaction_payment::NextFeeMultiplier::<Runtime>::set(multiplier);
1
			let actual = TransactionPaymentAsGasPrice::min_gas_price().0;
1
			let expected: U256 = multiplier
1
				.saturating_mul_int(currency::WEIGHT_FEE.saturating_mul(WEIGHT_PER_GAS as u128))
1
				.into();
1

            
1
			assert_eq!(expected, actual);
1
		});
1
	}
	#[test]
1
	fn test_min_gas_price_has_no_precision_loss_from_saturating_mul_int() {
1
		let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
1
			.build_storage()
1
			.unwrap()
1
			.into();
1
		t.execute_with(|| {
1
			let multiplier_1 = sp_runtime::FixedU128::from_float(0.999593900000000000);
1
			let multiplier_2 = sp_runtime::FixedU128::from_float(0.999593200000000000);
1

            
1
			pallet_transaction_payment::NextFeeMultiplier::<Runtime>::set(multiplier_1);
1
			let a = TransactionPaymentAsGasPrice::min_gas_price();
1
			pallet_transaction_payment::NextFeeMultiplier::<Runtime>::set(multiplier_2);
1
			let b = TransactionPaymentAsGasPrice::min_gas_price();
1

            
1
			assert_ne!(
				a, b,
				"both gas prices were equal, unexpected precision loss incurred"
			);
1
		});
1
	}
	#[test]
1
	fn test_fee_scenarios() {
		use sp_runtime::FixedU128;
1
		let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
1
			.build_storage()
1
			.unwrap()
1
			.into();
1
		t.execute_with(|| {
1
			let weight_fee_per_gas = (currency::WEIGHT_FEE).saturating_mul(WEIGHT_PER_GAS as u128);
12
			let sim = |start_gas_price: u128, fullness: Perbill, num_blocks: u64| -> U256 {
12
				let start_multiplier =
12
					FixedU128::from_rational(start_gas_price, weight_fee_per_gas);
12
				pallet_transaction_payment::NextFeeMultiplier::<Runtime>::set(start_multiplier);
12

            
12
				let block_weight = NORMAL_WEIGHT * fullness;
60004
				for i in 0..num_blocks {
60004
					System::set_block_number(i as u32);
60004
					System::set_block_consumed_resources(block_weight, 0);
60004
					TransactionPayment::on_finalize(i as u32);
60004
				}
12
				TransactionPaymentAsGasPrice::min_gas_price().0
12
			};
			// The expected values are the ones observed during test execution,
			// they are expected to change when parameters that influence
			// the fee calculation are changed, and should be updated accordingly.
			// If a test fails when nothing specific to fees has changed,
			// it may indicate an unexpected collateral effect and should be investigated
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(0), 1),
1
				U256::from(31_250_000_000u128), // lower bound enforced
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(25), 1),
1
				U256::from(31_250_000_000u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(50), 1),
1
				U256::from(31_268_755_625u128), // slightly higher than lower bound
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(100), 1),
1
				U256::from(31_331_355_625u128), // a bit higher than before
1
			);
			// 1 "real" hour (at 12-second blocks)
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(0), 600),
1
				U256::from(31_250_000_000u128), // lower bound enforced
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(25), 600),
1
				U256::from(31_250_000_000u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(50), 600),
1
				U256::from(44_791_543_237u128), // a bit higher than lower bound
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(100), 600),
1
				U256::from(148_712_903_041u128), // a lot more
1
			);
			// 1 "real" day (at 12-second blocks)
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(0), 14400),
1
				U256::from(31_250_000_000u128), // lower bound enforced
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(25), 14400),
1
				U256::from(31_250_000_000u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(50), 14400),
1
				U256::from(176_666_465_470_908u128), // significantly higher
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(100), 14400),
1
				U256::from(3_125_000_000_000_000u128), // upper bound enforced
1
			);
1
		});
1
	}
}
#[cfg(test)]
mod balance_tests {
	use crate::common::{ExtBuilder, ALICE};
	use frame_support::assert_ok;
	use frame_support::traits::LockableCurrency;
	use frame_support::traits::{LockIdentifier, ReservableCurrency, WithdrawReasons};
	use moonbeam_core_primitives::AccountId;
	use moonbeam_runtime::{Balances, Runtime, System};
	#[test]
1
	fn reserve_should_work_for_frozen_balance() {
1
		let alice = AccountId::from(ALICE);
		const ID_1: LockIdentifier = *b"1       ";
1
		ExtBuilder::default()
1
			.with_balances(vec![(alice, 10)])
1
			.build()
1
			.execute_with(|| {
1
				// Check balances
1
				let account = System::account(&alice).data;
1
				assert_eq!(account.free, 10);
1
				assert_eq!(account.frozen, 0);
1
				assert_eq!(account.reserved, 0);
1
				Balances::set_lock(ID_1, &alice, 9, WithdrawReasons::RESERVE);
1

            
1
				let account = System::account(&alice).data;
1
				assert_eq!(account.free, 10);
1
				assert_eq!(account.frozen, 9);
1
				assert_eq!(account.reserved, 0);
1
				assert_ok!(Balances::reserve(&alice, 5));
1
				let account = System::account(&alice).data;
1
				assert_eq!(account.free, 5);
1
				assert_eq!(account.frozen, 9);
1
				assert_eq!(account.reserved, 5);
1
				let previous_reserved_amount = account.reserved;
1
				let ed: u128 = <Runtime as pallet_balances::Config>::ExistentialDeposit::get();
1
				let next_reserve = account.free.saturating_sub(ed);
1
				assert_ok!(Balances::reserve(&alice, next_reserve));
1
				let account = System::account(&alice).data;
1
				assert_eq!(account.free, ed);
1
				assert_eq!(account.frozen, 9);
1
				assert_eq!(
1
					account.reserved,
1
					previous_reserved_amount.saturating_add(next_reserve)
1
				);
1
			});
1
	}
}
moonbeam_runtime_common::generate_common_xcm_tests!(moonbeam_runtime);