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

            
19
#![cfg(test)]
20

            
21
mod common;
22

            
23
use common::*;
24
use std::cell::Cell;
25
use std::rc::Rc;
26

            
27
use fp_evm::{Context, IsPrecompileResult};
28
use frame_support::{
29
	assert_noop, assert_ok,
30
	dispatch::DispatchClass,
31
	traits::{
32
		fungible::Inspect, Currency as CurrencyT, EnsureOrigin, OnInitialize, PalletInfo,
33
		StorageInfo, StorageInfoTrait,
34
	},
35
	weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
36
	StorageHasher, Twox128,
37
};
38
use moonbeam_xcm_benchmarks::weights::XcmWeight;
39
use moonkit_xcm_primitives::AccountIdAssetIdConversion;
40
use moonriver_runtime::currency::{GIGAWEI, WEI};
41
use moonriver_runtime::runtime_params::dynamic_params;
42
use moonriver_runtime::{
43
	asset_config::ForeignAssetInstance,
44
	xcm_config::{CurrencyId, SelfReserve},
45
	AssetId, Balances, CrowdloanRewards, EvmForeignAssets, Executive, OpenTechCommitteeCollective,
46
	PolkadotXcm, Precompiles, RuntimeBlockWeights, TransactionPayment,
47
	TransactionPaymentAsGasPrice, Treasury, TreasuryCouncilCollective, XcmTransactor,
48
	FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX, WEEKS,
49
};
50
use nimbus_primitives::NimbusId;
51
use pallet_evm::PrecompileSet;
52
use pallet_evm_precompileset_assets_erc20::{SELECTOR_LOG_APPROVAL, SELECTOR_LOG_TRANSFER};
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 sha3::{Digest, Keccak256};
63
use sp_core::{ByteArray, Get, Pair, H160, U256};
64
use sp_runtime::{
65
	traits::{Convert, Dispatchable},
66
	BuildStorage, DispatchError, ModuleError,
67
};
68
use std::str::from_utf8;
69
use xcm::latest::prelude::*;
70
use xcm::{VersionedAssets, VersionedLocation};
71
use xcm_builder::{ParentIsPreset, SiblingParachainConvertsVia};
72
use xcm_executor::traits::ConvertLocation;
73
use xcm_primitives::split_location_into_chain_part_and_beneficiary;
74

            
75
type BatchPCall = pallet_evm_precompile_batch::BatchPrecompileCall<Runtime>;
76
type CrowdloanRewardsPCall =
77
	pallet_evm_precompile_crowdloan_rewards::CrowdloanRewardsPrecompileCall<Runtime>;
78
type XcmUtilsPCall = pallet_evm_precompile_xcm_utils::XcmUtilsPrecompileCall<
79
	Runtime,
80
	moonriver_runtime::xcm_config::XcmExecutorConfig,
81
>;
82
type XtokensPCall = pallet_evm_precompile_xtokens::XtokensPrecompileCall<Runtime>;
83
type ForeignAssetsPCall = pallet_evm_precompileset_assets_erc20::Erc20AssetsPrecompileSetCall<
84
	Runtime,
85
	ForeignAssetInstance,
86
>;
87
type XcmTransactorV2PCall =
88
	pallet_evm_precompile_xcm_transactor::v2::XcmTransactorPrecompileV2Call<Runtime>;
89

            
90
const BASE_FEE_GENESIS: u128 = 100 * GIGAWEI;
91

            
92
3
fn currency_to_asset(currency_id: CurrencyId, amount: u128) -> Asset {
93
3
	Asset {
94
3
		id: AssetId(
95
3
			<moonriver_runtime::Runtime as pallet_xcm_transactor::Config>::CurrencyIdToLocation::convert(
96
3
				currency_id,
97
3
			)
98
3
			.unwrap(),
99
3
		),
100
3
		fun: Fungibility::Fungible(amount),
101
3
	}
102
3
}
103

            
104
#[test]
105
1
fn xcmp_queue_controller_origin_is_root() {
106
1
	// important for the XcmExecutionManager impl of PauseExecution which uses root origin
107
1
	// to suspend/resume XCM execution in xcmp_queue::on_idle
108
1
	assert_ok!(
109
1
		<moonriver_runtime::Runtime as cumulus_pallet_xcmp_queue::Config
110
1
		>::ControllerOrigin::ensure_origin(root_origin())
111
1
	);
112
1
}
113

            
114
#[test]
115
1
fn verify_pallet_prefixes() {
116
30
	fn is_pallet_prefix<P: 'static>(name: &str) {
117
30
		// Compares the unhashed pallet prefix in the `StorageInstance` implementation by every
118
30
		// storage item in the pallet P. This pallet prefix is used in conjunction with the
119
30
		// item name to get the unique storage key: hash(PalletPrefix) + hash(StorageName)
120
30
		// https://github.com/paritytech/substrate/blob/master/frame/support/procedural/src/pallet/
121
30
		// expand/storage.rs#L389-L401
122
30
		assert_eq!(
123
30
			<moonriver_runtime::Runtime as frame_system::Config>::PalletInfo::name::<P>(),
124
30
			Some(name)
125
30
		);
126
30
	}
127
	// TODO: use StorageInfoTrait from https://github.com/paritytech/substrate/pull/9246
128
	// This is now available with polkadot-v0.9.9 dependencies
129
1
	is_pallet_prefix::<moonriver_runtime::System>("System");
130
1
	is_pallet_prefix::<moonriver_runtime::Utility>("Utility");
131
1
	is_pallet_prefix::<moonriver_runtime::ParachainSystem>("ParachainSystem");
132
1
	is_pallet_prefix::<moonriver_runtime::TransactionPayment>("TransactionPayment");
133
1
	is_pallet_prefix::<moonriver_runtime::ParachainInfo>("ParachainInfo");
134
1
	is_pallet_prefix::<moonriver_runtime::EthereumChainId>("EthereumChainId");
135
1
	is_pallet_prefix::<moonriver_runtime::EVM>("EVM");
136
1
	is_pallet_prefix::<moonriver_runtime::Ethereum>("Ethereum");
137
1
	is_pallet_prefix::<moonriver_runtime::ParachainStaking>("ParachainStaking");
138
1
	is_pallet_prefix::<moonriver_runtime::MaintenanceMode>("MaintenanceMode");
139
1
	is_pallet_prefix::<moonriver_runtime::Scheduler>("Scheduler");
140
1
	is_pallet_prefix::<moonriver_runtime::OpenTechCommitteeCollective>(
141
1
		"OpenTechCommitteeCollective",
142
1
	);
143
1
	is_pallet_prefix::<moonriver_runtime::Treasury>("Treasury");
144
1
	is_pallet_prefix::<moonriver_runtime::AuthorInherent>("AuthorInherent");
145
1
	is_pallet_prefix::<moonriver_runtime::AuthorFilter>("AuthorFilter");
146
1
	is_pallet_prefix::<moonriver_runtime::CrowdloanRewards>("CrowdloanRewards");
147
1
	is_pallet_prefix::<moonriver_runtime::AuthorMapping>("AuthorMapping");
148
1
	is_pallet_prefix::<moonriver_runtime::Identity>("Identity");
149
1
	is_pallet_prefix::<moonriver_runtime::XcmpQueue>("XcmpQueue");
150
1
	is_pallet_prefix::<moonriver_runtime::CumulusXcm>("CumulusXcm");
151
1
	is_pallet_prefix::<moonriver_runtime::PolkadotXcm>("PolkadotXcm");
152
1
	is_pallet_prefix::<moonriver_runtime::Assets>("Assets");
153
1
	is_pallet_prefix::<moonriver_runtime::AssetManager>("AssetManager");
154
1
	is_pallet_prefix::<moonriver_runtime::Migrations>("Migrations");
155
1
	is_pallet_prefix::<moonriver_runtime::XcmTransactor>("XcmTransactor");
156
1
	is_pallet_prefix::<moonriver_runtime::ProxyGenesisCompanion>("ProxyGenesisCompanion");
157
1
	is_pallet_prefix::<moonriver_runtime::MoonbeamOrbiters>("MoonbeamOrbiters");
158
1
	is_pallet_prefix::<moonriver_runtime::TreasuryCouncilCollective>("TreasuryCouncilCollective");
159
1
	is_pallet_prefix::<moonriver_runtime::MoonbeamLazyMigrations>("MoonbeamLazyMigrations");
160
1
	is_pallet_prefix::<moonriver_runtime::RelayStorageRoots>("RelayStorageRoots");
161
1

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

            
291
#[test]
292
1
fn test_collectives_storage_item_prefixes() {
293
7
	for StorageInfo { pallet_name, .. } in
294
8
		<moonriver_runtime::TreasuryCouncilCollective as StorageInfoTrait>::storage_info()
295
	{
296
7
		assert_eq!(pallet_name, b"TreasuryCouncilCollective".to_vec());
297
	}
298

            
299
7
	for StorageInfo { pallet_name, .. } in
300
8
		<moonriver_runtime::OpenTechCommitteeCollective as StorageInfoTrait>::storage_info()
301
	{
302
7
		assert_eq!(pallet_name, b"OpenTechCommitteeCollective".to_vec());
303
	}
304
1
}
305

            
306
#[test]
307
1
fn collective_set_members_root_origin_works() {
308
1
	ExtBuilder::default().build().execute_with(|| {
309
1
		// TreasuryCouncilCollective
310
1
		assert_ok!(TreasuryCouncilCollective::set_members(
311
1
			<Runtime as frame_system::Config>::RuntimeOrigin::root(),
312
1
			vec![AccountId::from(ALICE), AccountId::from(BOB)],
313
1
			Some(AccountId::from(ALICE)),
314
1
			2
315
1
		));
316
		// OpenTechCommitteeCollective
317
1
		assert_ok!(OpenTechCommitteeCollective::set_members(
318
1
			<Runtime as frame_system::Config>::RuntimeOrigin::root(),
319
1
			vec![AccountId::from(ALICE), AccountId::from(BOB)],
320
1
			Some(AccountId::from(ALICE)),
321
1
			2
322
1
		));
323
1
	});
324
1
}
325

            
326
#[test]
327
1
fn collective_set_members_general_admin_origin_works() {
328
	use moonriver_runtime::{
329
		governance::custom_origins::Origin as CustomOrigin, OriginCaller, Utility,
330
	};
331

            
332
1
	ExtBuilder::default().build().execute_with(|| {
333
1
		let root_caller = <Runtime as frame_system::Config>::RuntimeOrigin::root();
334
1
		let alice = AccountId::from(ALICE);
335
1

            
336
1
		// TreasuryCouncilCollective
337
1
		let _ = Utility::dispatch_as(
338
1
			root_caller.clone(),
339
1
			Box::new(OriginCaller::Origins(CustomOrigin::GeneralAdmin)),
340
1
			Box::new(
341
1
				pallet_collective::Call::<Runtime, pallet_collective::Instance3>::set_members {
342
1
					new_members: vec![alice, AccountId::from(BOB)],
343
1
					prime: Some(alice),
344
1
					old_count: 2,
345
1
				}
346
1
				.into(),
347
1
			),
348
1
		);
349
1
		// OpenTechCommitteeCollective
350
1
		let _ = Utility::dispatch_as(
351
1
			root_caller,
352
1
			Box::new(OriginCaller::Origins(CustomOrigin::GeneralAdmin)),
353
1
			Box::new(
354
1
				pallet_collective::Call::<Runtime, pallet_collective::Instance4>::set_members {
355
1
					new_members: vec![alice, AccountId::from(BOB)],
356
1
					prime: Some(alice),
357
1
					old_count: 2,
358
1
				}
359
1
				.into(),
360
1
			),
361
1
		);
362
1

            
363
1
		assert_eq!(
364
1
			System::events()
365
1
				.into_iter()
366
2
				.filter_map(|r| {
367
2
					match r.event {
368
2
						RuntimeEvent::Utility(pallet_utility::Event::DispatchedAs { result })
369
2
							if result.is_ok() =>
370
2
						{
371
2
							Some(true)
372
						}
373
						_ => None,
374
					}
375
2
				})
376
1
				.collect::<Vec<_>>()
377
1
				.len(),
378
1
			2
379
1
		)
380
1
	});
381
1
}
382

            
383
#[test]
384
1
fn collective_set_members_signed_origin_does_not_work() {
385
1
	let alice = AccountId::from(ALICE);
386
1
	ExtBuilder::default().build().execute_with(|| {
387
1
		// TreasuryCouncilCollective
388
1
		assert!(TreasuryCouncilCollective::set_members(
389
1
			<Runtime as frame_system::Config>::RuntimeOrigin::signed(alice),
390
1
			vec![AccountId::from(ALICE), AccountId::from(BOB)],
391
1
			Some(AccountId::from(ALICE)),
392
1
			2
393
1
		)
394
1
		.is_err());
395
		// OpenTechCommitteeCollective
396
1
		assert!(OpenTechCommitteeCollective::set_members(
397
1
			<Runtime as frame_system::Config>::RuntimeOrigin::signed(alice),
398
1
			vec![AccountId::from(ALICE), AccountId::from(BOB)],
399
1
			Some(AccountId::from(ALICE)),
400
1
			2
401
1
		)
402
1
		.is_err());
403
1
	});
404
1
}
405

            
406
#[test]
407
1
fn verify_pallet_indices() {
408
32
	fn is_pallet_index<P: 'static>(index: usize) {
409
32
		assert_eq!(
410
32
			<moonriver_runtime::Runtime as frame_system::Config>::PalletInfo::index::<P>(),
411
32
			Some(index)
412
32
		);
413
32
	}
414
	// System support
415
1
	is_pallet_index::<moonriver_runtime::System>(0);
416
1
	is_pallet_index::<moonriver_runtime::ParachainSystem>(1);
417
1
	is_pallet_index::<moonriver_runtime::Timestamp>(3);
418
1
	is_pallet_index::<moonriver_runtime::ParachainInfo>(4);
419
1
	// Monetary
420
1
	is_pallet_index::<moonriver_runtime::Balances>(10);
421
1
	is_pallet_index::<moonriver_runtime::TransactionPayment>(11);
422
1
	// Consensus support
423
1
	is_pallet_index::<moonriver_runtime::ParachainStaking>(20);
424
1
	is_pallet_index::<moonriver_runtime::AuthorInherent>(21);
425
1
	is_pallet_index::<moonriver_runtime::AuthorFilter>(22);
426
1
	is_pallet_index::<moonriver_runtime::AuthorMapping>(23);
427
1
	is_pallet_index::<moonriver_runtime::MoonbeamOrbiters>(24);
428
1
	// Handy utilities
429
1
	is_pallet_index::<moonriver_runtime::Utility>(30);
430
1
	is_pallet_index::<moonriver_runtime::Proxy>(31);
431
1
	is_pallet_index::<moonriver_runtime::MaintenanceMode>(32);
432
1
	is_pallet_index::<moonriver_runtime::Identity>(33);
433
1
	is_pallet_index::<moonriver_runtime::Migrations>(34);
434
1
	is_pallet_index::<moonriver_runtime::ProxyGenesisCompanion>(35);
435
1
	is_pallet_index::<moonriver_runtime::MoonbeamLazyMigrations>(37);
436
1
	// Ethereum compatibility
437
1
	is_pallet_index::<moonriver_runtime::EthereumChainId>(50);
438
1
	is_pallet_index::<moonriver_runtime::EVM>(51);
439
1
	is_pallet_index::<moonriver_runtime::Ethereum>(52);
440
1
	// Governance
441
1
	is_pallet_index::<moonriver_runtime::Scheduler>(60);
442
1
	// is_pallet_index::<moonriver_runtime::Democracy>(61); Removed
443
1
	// Council
444
1
	// is_pallet_index::<moonriver_runtime::CouncilCollective>(70); Removed
445
1
	// is_pallet_index::<moonriver_runtime::TechCommitteeCollective>(71); Removed
446
1
	is_pallet_index::<moonriver_runtime::TreasuryCouncilCollective>(72);
447
1
	is_pallet_index::<moonriver_runtime::OpenTechCommitteeCollective>(73);
448
1
	// Treasury
449
1
	is_pallet_index::<moonriver_runtime::Treasury>(80);
450
1
	// Crowdloan
451
1
	is_pallet_index::<moonriver_runtime::CrowdloanRewards>(90);
452
1
	// XCM Stuff
453
1
	is_pallet_index::<moonriver_runtime::XcmpQueue>(100);
454
1
	is_pallet_index::<moonriver_runtime::CumulusXcm>(101);
455
1
	is_pallet_index::<moonriver_runtime::PolkadotXcm>(103);
456
1
	is_pallet_index::<moonriver_runtime::Assets>(104);
457
1
	is_pallet_index::<moonriver_runtime::AssetManager>(105);
458
1
	// is_pallet_index::<moonriver_runtime::XTokens>(106); Removed
459
1
	is_pallet_index::<moonriver_runtime::XcmTransactor>(107);
460
1
}
461

            
462
#[test]
463
1
fn verify_reserved_indices() {
464
1
	let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
465
1
		.build_storage()
466
1
		.unwrap()
467
1
		.into();
468
1

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

            
489
#[test]
490
1
fn verify_proxy_type_indices() {
491
1
	assert_eq!(moonriver_runtime::ProxyType::Any as u8, 0);
492
1
	assert_eq!(moonriver_runtime::ProxyType::NonTransfer as u8, 1);
493
1
	assert_eq!(moonriver_runtime::ProxyType::Governance as u8, 2);
494
1
	assert_eq!(moonriver_runtime::ProxyType::Staking as u8, 3);
495
1
	assert_eq!(moonriver_runtime::ProxyType::CancelProxy as u8, 4);
496
1
	assert_eq!(moonriver_runtime::ProxyType::Balances as u8, 5);
497
1
	assert_eq!(moonriver_runtime::ProxyType::AuthorMapping as u8, 6);
498
1
	assert_eq!(moonriver_runtime::ProxyType::IdentityJudgement as u8, 7);
499
1
}
500

            
501
#[test]
502
1
fn join_collator_candidates() {
503
1
	ExtBuilder::default()
504
1
		.with_balances(vec![
505
1
			(AccountId::from(ALICE), 20_000 * MOVR),
506
1
			(AccountId::from(BOB), 20_000 * MOVR),
507
1
			(AccountId::from(CHARLIE), 10_100 * MOVR),
508
1
			(AccountId::from(DAVE), 10_000 * MOVR),
509
1
		])
510
1
		.with_collators(vec![
511
1
			(AccountId::from(ALICE), 10_000 * MOVR),
512
1
			(AccountId::from(BOB), 10_000 * MOVR),
513
1
		])
514
1
		.with_delegations(vec![
515
1
			(AccountId::from(CHARLIE), AccountId::from(ALICE), 50 * MOVR),
516
1
			(AccountId::from(CHARLIE), AccountId::from(BOB), 50 * MOVR),
517
1
		])
518
1
		.build()
519
1
		.execute_with(|| {
520
1
			assert_noop!(
521
1
				ParachainStaking::join_candidates(
522
1
					origin_of(AccountId::from(ALICE)),
523
1
					10_000 * MOVR,
524
1
					2u32
525
1
				),
526
1
				pallet_parachain_staking::Error::<Runtime>::CandidateExists
527
1
			);
528
1
			assert_noop!(
529
1
				ParachainStaking::join_candidates(
530
1
					origin_of(AccountId::from(CHARLIE)),
531
1
					10_000 * MOVR,
532
1
					2u32
533
1
				),
534
1
				pallet_parachain_staking::Error::<Runtime>::DelegatorExists
535
1
			);
536
1
			assert!(System::events().is_empty());
537
1
			assert_ok!(ParachainStaking::join_candidates(
538
1
				origin_of(AccountId::from(DAVE)),
539
1
				10_000 * MOVR,
540
1
				2u32
541
1
			));
542
1
			assert_eq!(
543
1
				last_event(),
544
1
				RuntimeEvent::ParachainStaking(
545
1
					pallet_parachain_staking::Event::JoinedCollatorCandidates {
546
1
						account: AccountId::from(DAVE),
547
1
						amount_locked: 10_000 * MOVR,
548
1
						new_total_amt_locked: 30_100 * MOVR
549
1
					}
550
1
				)
551
1
			);
552
1
			let candidates = ParachainStaking::candidate_pool();
553
1
			assert_eq!(candidates.0[0].owner, AccountId::from(ALICE));
554
1
			assert_eq!(candidates.0[0].amount, 10_050 * MOVR);
555
1
			assert_eq!(candidates.0[1].owner, AccountId::from(BOB));
556
1
			assert_eq!(candidates.0[1].amount, 10_050 * MOVR);
557
1
			assert_eq!(candidates.0[2].owner, AccountId::from(DAVE));
558
1
			assert_eq!(candidates.0[2].amount, 10_000 * MOVR);
559
1
		});
560
1
}
561

            
562
#[test]
563
1
fn transfer_through_evm_to_stake() {
564
1
	ExtBuilder::default()
565
1
		.with_balances(vec![(AccountId::from(ALICE), 20_000 * MOVR)])
566
1
		.build()
567
1
		.execute_with(|| {
568
1
			// Charlie has no balance => fails to stake
569
1
			assert_noop!(
570
1
				ParachainStaking::join_candidates(
571
1
					origin_of(AccountId::from(CHARLIE)),
572
1
					10_000 * MOVR,
573
1
					2u32
574
1
				),
575
1
				DispatchError::Module(ModuleError {
576
1
					index: 20,
577
1
					error: [8, 0, 0, 0],
578
1
					message: Some("InsufficientBalance")
579
1
				})
580
1
			);
581
			// Alice transfer from free balance 20000 MOVR to Bob
582
1
			assert_ok!(Balances::transfer_allow_death(
583
1
				origin_of(AccountId::from(ALICE)),
584
1
				AccountId::from(BOB),
585
1
				20_000 * MOVR,
586
1
			));
587
1
			assert_eq!(Balances::free_balance(AccountId::from(BOB)), 20_000 * MOVR);
588

            
589
1
			let gas_limit = 100000u64;
590
1
			let gas_price: U256 = BASE_FEE_GENESIS.into();
591
1
			// Bob transfers 10000 MOVR to Charlie via EVM
592
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
593
1
				source: H160::from(BOB),
594
1
				target: H160::from(CHARLIE),
595
1
				input: vec![],
596
1
				value: (10_000 * MOVR).into(),
597
1
				gas_limit,
598
1
				max_fee_per_gas: gas_price,
599
1
				max_priority_fee_per_gas: None,
600
1
				nonce: None,
601
1
				access_list: Vec::new(),
602
1
			})
603
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
604
1
			assert_eq!(
605
1
				Balances::free_balance(AccountId::from(CHARLIE)),
606
1
				10_000 * MOVR,
607
1
			);
608

            
609
			// Charlie can stake now
610
1
			assert_ok!(ParachainStaking::join_candidates(
611
1
				origin_of(AccountId::from(CHARLIE)),
612
1
				10_000 * MOVR,
613
1
				2u32,
614
1
			),);
615
1
			let candidates = ParachainStaking::candidate_pool();
616
1
			assert_eq!(candidates.0[0].owner, AccountId::from(CHARLIE));
617
1
			assert_eq!(candidates.0[0].amount, 10_000 * MOVR);
618
1
		});
619
1
}
620

            
621
#[test]
622
1
fn reward_block_authors() {
623
1
	ExtBuilder::default()
624
1
		.with_balances(vec![
625
1
			// Alice gets 100 extra tokens for her mapping deposit
626
1
			(AccountId::from(ALICE), 20_100 * MOVR),
627
1
			(AccountId::from(BOB), 10_000 * MOVR),
628
1
		])
629
1
		.with_collators(vec![(AccountId::from(ALICE), 10_000 * MOVR)])
630
1
		.with_delegations(vec![(
631
1
			AccountId::from(BOB),
632
1
			AccountId::from(ALICE),
633
1
			500 * MOVR,
634
1
		)])
635
1
		.with_mappings(vec![(
636
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
637
1
			AccountId::from(ALICE),
638
1
		)])
639
1
		.build()
640
1
		.execute_with(|| {
641
1
			increase_last_relay_slot_number(1);
642
1

            
643
1
			// Just before round 3
644
1
			run_to_block(2399, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
645
1

            
646
1
			// no rewards doled out yet
647
1
			assert_eq!(
648
1
				Balances::usable_balance(AccountId::from(ALICE)),
649
1
				10_100 * MOVR,
650
1
			);
651
1
			assert_eq!(Balances::usable_balance(AccountId::from(BOB)), 9500 * MOVR,);
652
1
			run_to_block(2401, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
653
1

            
654
1
			// rewards minted and distributed
655
1
			assert_eq!(
656
1
				Balances::usable_balance(AccountId::from(ALICE)),
657
1
				11547666666208000000000,
658
1
			);
659
1
			assert_eq!(
660
1
				Balances::usable_balance(AccountId::from(BOB)),
661
1
				9557333332588000000000,
662
1
			);
663
1
		});
664
1
}
665

            
666
#[test]
667
1
fn reward_block_authors_with_parachain_bond_reserved() {
668
1
	ExtBuilder::default()
669
1
		.with_balances(vec![
670
1
			// Alice gets 100 extra tokens for her mapping deposit
671
1
			(AccountId::from(ALICE), 20_100 * MOVR),
672
1
			(AccountId::from(BOB), 10_000 * MOVR),
673
1
			(AccountId::from(CHARLIE), MOVR),
674
1
		])
675
1
		.with_collators(vec![(AccountId::from(ALICE), 10_000 * MOVR)])
676
1
		.with_delegations(vec![(
677
1
			AccountId::from(BOB),
678
1
			AccountId::from(ALICE),
679
1
			500 * MOVR,
680
1
		)])
681
1
		.with_mappings(vec![(
682
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
683
1
			AccountId::from(ALICE),
684
1
		)])
685
1
		.build()
686
1
		.execute_with(|| {
687
1
			increase_last_relay_slot_number(1);
688
1
			assert_ok!(ParachainStaking::set_parachain_bond_account(
689
1
				root_origin(),
690
1
				AccountId::from(CHARLIE),
691
1
			),);
692

            
693
			// Stop just before round 2
694
1
			run_to_block(1199, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
695
1

            
696
1
			// no collator rewards doled out yet
697
1
			assert_eq!(
698
1
				Balances::usable_balance(AccountId::from(ALICE)),
699
1
				10_100 * MOVR,
700
1
			);
701
1
			assert_eq!(Balances::usable_balance(AccountId::from(BOB)), 9500 * MOVR,);
702

            
703
			// Go to round 2
704
1
			run_to_block(1201, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
705
1

            
706
1
			// 30% reserved for parachain bond
707
1
			assert_eq!(
708
1
				Balances::usable_balance(AccountId::from(CHARLIE)),
709
1
				452515000000000000000,
710
1
			);
711

            
712
			// Go to round 3
713
1
			run_to_block(2401, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
714
1

            
715
1
			// rewards minted and distributed
716
1
			assert_eq!(
717
1
				Balances::usable_balance(AccountId::from(ALICE)),
718
1
				11117700475903800000000,
719
1
			);
720
1
			assert_eq!(
721
1
				Balances::usable_balance(AccountId::from(BOB)),
722
1
				9535834523343675000000,
723
1
			);
724
			// 30% reserved for parachain bond again
725
1
			assert_eq!(
726
1
				Balances::usable_balance(AccountId::from(CHARLIE)),
727
1
				910802725000000000000,
728
1
			);
729
1
		});
730
1
}
731

            
732
#[test]
733
1
fn initialize_crowdloan_addresses_with_batch_and_pay() {
734
1
	ExtBuilder::default()
735
1
		.with_balances(vec![
736
1
			(AccountId::from(ALICE), 2_000 * MOVR),
737
1
			(AccountId::from(BOB), 1_000 * MOVR),
738
1
		])
739
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * MOVR)])
740
1
		.with_mappings(vec![(
741
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
742
1
			AccountId::from(ALICE),
743
1
		)])
744
1
		.with_crowdloan_fund(3_000_000 * MOVR)
745
1
		.build()
746
1
		.execute_with(|| {
747
1
			// set parachain inherent data
748
1
			set_parachain_inherent_data();
749
1
			let init_block = CrowdloanRewards::init_vesting_block();
750
1
			// This matches the previous vesting
751
1
			let end_block = init_block + 48 * WEEKS;
752
1
			// Batch calls always succeed. We just need to check the inner event
753
1
			assert_ok!(
754
1
				RuntimeCall::Utility(pallet_utility::Call::<Runtime>::batch_all {
755
1
					calls: vec![
756
1
						RuntimeCall::CrowdloanRewards(
757
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
758
1
								rewards: vec![(
759
1
									[4u8; 32].into(),
760
1
									Some(AccountId::from(CHARLIE)),
761
1
									1_500_000 * MOVR
762
1
								)]
763
1
							}
764
1
						),
765
1
						RuntimeCall::CrowdloanRewards(
766
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
767
1
								rewards: vec![(
768
1
									[5u8; 32].into(),
769
1
									Some(AccountId::from(DAVE)),
770
1
									1_500_000 * MOVR
771
1
								)]
772
1
							}
773
1
						),
774
1
						RuntimeCall::CrowdloanRewards(
775
1
							pallet_crowdloan_rewards::Call::<Runtime>::complete_initialization {
776
1
								lease_ending_block: end_block
777
1
							}
778
1
						)
779
1
					]
780
1
				})
781
1
				.dispatch(root_origin())
782
1
			);
783
			// 30 percent initial payout
784
1
			assert_eq!(Balances::balance(&AccountId::from(CHARLIE)), 450_000 * MOVR);
785
			// 30 percent initial payout
786
1
			assert_eq!(Balances::balance(&AccountId::from(DAVE)), 450_000 * MOVR);
787
1
			let expected = RuntimeEvent::Utility(pallet_utility::Event::BatchCompleted);
788
1
			assert_eq!(last_event(), expected);
789
			// This one should fail, as we already filled our data
790
1
			assert_ok!(
791
1
				RuntimeCall::Utility(pallet_utility::Call::<Runtime>::batch {
792
1
					calls: vec![RuntimeCall::CrowdloanRewards(
793
1
						pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
794
1
							rewards: vec![([4u8; 32].into(), Some(AccountId::from(ALICE)), 432000)]
795
1
						}
796
1
					)]
797
1
				})
798
1
				.dispatch(root_origin())
799
1
			);
800
1
			let expected_fail = RuntimeEvent::Utility(pallet_utility::Event::BatchInterrupted {
801
1
				index: 0,
802
1
				error: DispatchError::Module(ModuleError {
803
1
					index: 90,
804
1
					error: [8, 0, 0, 0],
805
1
					message: None,
806
1
				}),
807
1
			});
808
1
			assert_eq!(last_event(), expected_fail);
809
			// Claim 1 block.
810
1
			assert_ok!(CrowdloanRewards::claim(origin_of(AccountId::from(CHARLIE))));
811
1
			assert_ok!(CrowdloanRewards::claim(origin_of(AccountId::from(DAVE))));
812

            
813
1
			let vesting_period = 48 * WEEKS as u128;
814
1
			let per_block = (1_050_000 * MOVR) / vesting_period;
815
1

            
816
1
			assert_eq!(
817
1
				CrowdloanRewards::accounts_payable(&AccountId::from(CHARLIE))
818
1
					.unwrap()
819
1
					.claimed_reward,
820
1
				(450_000 * MOVR) + per_block
821
1
			);
822
1
			assert_eq!(
823
1
				CrowdloanRewards::accounts_payable(&AccountId::from(DAVE))
824
1
					.unwrap()
825
1
					.claimed_reward,
826
1
				(450_000 * MOVR) + per_block
827
1
			);
828
			// The total claimed reward should be equal to the account balance at this point.
829
1
			assert_eq!(
830
1
				Balances::balance(&AccountId::from(CHARLIE)),
831
1
				(450_000 * MOVR) + per_block
832
1
			);
833
1
			assert_eq!(
834
1
				Balances::balance(&AccountId::from(DAVE)),
835
1
				(450_000 * MOVR) + per_block
836
1
			);
837
1
			assert_noop!(
838
1
				CrowdloanRewards::claim(origin_of(AccountId::from(ALICE))),
839
1
				pallet_crowdloan_rewards::Error::<Runtime>::NoAssociatedClaim
840
1
			);
841
1
		});
842
1
}
843

            
844
#[test]
845
1
fn initialize_crowdloan_address_and_change_with_relay_key_sig() {
846
1
	ExtBuilder::default()
847
1
		.with_balances(vec![
848
1
			(AccountId::from(ALICE), 2_000 * MOVR),
849
1
			(AccountId::from(BOB), 1_000 * MOVR),
850
1
		])
851
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * MOVR)])
852
1
		.with_mappings(vec![(
853
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
854
1
			AccountId::from(ALICE),
855
1
		)])
856
1
		.with_crowdloan_fund(3_000_000 * MOVR)
857
1
		.build()
858
1
		.execute_with(|| {
859
1
			// set parachain inherent data
860
1
			set_parachain_inherent_data();
861
1
			let init_block = CrowdloanRewards::init_vesting_block();
862
1
			// This matches the previous vesting
863
1
			let end_block = init_block + 4 * WEEKS;
864
1

            
865
1
			let (pair1, _) = sp_core::sr25519::Pair::generate();
866
1
			let (pair2, _) = sp_core::sr25519::Pair::generate();
867
1

            
868
1
			let public1 = pair1.public();
869
1
			let public2 = pair2.public();
870
1

            
871
1
			// signature:
872
1
			// WRAP_BYTES|| NetworkIdentifier|| new_account || previous_account || WRAP_BYTES
873
1
			let mut message = pallet_crowdloan_rewards::WRAPPED_BYTES_PREFIX.to_vec();
874
1
			message.append(&mut b"moonriver-".to_vec());
875
1
			message.append(&mut AccountId::from(DAVE).encode());
876
1
			message.append(&mut AccountId::from(CHARLIE).encode());
877
1
			message.append(&mut pallet_crowdloan_rewards::WRAPPED_BYTES_POSTFIX.to_vec());
878
1
			let signature1 = pair1.sign(&message);
879
1
			let signature2 = pair2.sign(&message);
880
1

            
881
1
			// Batch calls always succeed. We just need to check the inner event
882
1
			assert_ok!(
883
1
				// two relay accounts pointing at the same reward account
884
1
				RuntimeCall::Utility(pallet_utility::Call::<Runtime>::batch_all {
885
1
					calls: vec![
886
1
						RuntimeCall::CrowdloanRewards(
887
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
888
1
								rewards: vec![(
889
1
									public1.into(),
890
1
									Some(AccountId::from(CHARLIE)),
891
1
									1_500_000 * MOVR
892
1
								)]
893
1
							}
894
1
						),
895
1
						RuntimeCall::CrowdloanRewards(
896
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
897
1
								rewards: vec![(
898
1
									public2.into(),
899
1
									Some(AccountId::from(CHARLIE)),
900
1
									1_500_000 * MOVR
901
1
								)]
902
1
							}
903
1
						),
904
1
						RuntimeCall::CrowdloanRewards(
905
1
							pallet_crowdloan_rewards::Call::<Runtime>::complete_initialization {
906
1
								lease_ending_block: end_block
907
1
							}
908
1
						)
909
1
					]
910
1
				})
911
1
				.dispatch(root_origin())
912
1
			);
913
			// 30 percent initial payout
914
1
			assert_eq!(Balances::balance(&AccountId::from(CHARLIE)), 900_000 * MOVR);
915

            
916
			// this should fail, as we are only providing one signature
917
1
			assert_noop!(
918
1
				CrowdloanRewards::change_association_with_relay_keys(
919
1
					origin_of(AccountId::from(CHARLIE)),
920
1
					AccountId::from(DAVE),
921
1
					AccountId::from(CHARLIE),
922
1
					vec![(public1.into(), signature1.clone().into())]
923
1
				),
924
1
				pallet_crowdloan_rewards::Error::<Runtime>::InsufficientNumberOfValidProofs
925
1
			);
926

            
927
			// this should be valid
928
1
			assert_ok!(CrowdloanRewards::change_association_with_relay_keys(
929
1
				origin_of(AccountId::from(CHARLIE)),
930
1
				AccountId::from(DAVE),
931
1
				AccountId::from(CHARLIE),
932
1
				vec![
933
1
					(public1.into(), signature1.into()),
934
1
					(public2.into(), signature2.into())
935
1
				]
936
1
			));
937

            
938
1
			assert_eq!(
939
1
				CrowdloanRewards::accounts_payable(&AccountId::from(DAVE))
940
1
					.unwrap()
941
1
					.claimed_reward,
942
1
				(900_000 * MOVR)
943
1
			);
944
1
		});
945
1
}
946

            
947
#[test]
948
1
fn claim_via_precompile() {
949
1
	ExtBuilder::default()
950
1
		.with_balances(vec![
951
1
			(AccountId::from(ALICE), 2_000 * MOVR),
952
1
			(AccountId::from(BOB), 1_000 * MOVR),
953
1
		])
954
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * MOVR)])
955
1
		.with_mappings(vec![(
956
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
957
1
			AccountId::from(ALICE),
958
1
		)])
959
1
		.with_crowdloan_fund(3_000_000 * MOVR)
960
1
		.build()
961
1
		.execute_with(|| {
962
1
			// set parachain inherent data
963
1
			set_parachain_inherent_data();
964
1
			let init_block = CrowdloanRewards::init_vesting_block();
965
1
			// This matches the previous vesting
966
1
			let end_block = init_block + 4 * WEEKS;
967
1
			// Batch calls always succeed. We just need to check the inner event
968
1
			assert_ok!(
969
1
				RuntimeCall::Utility(pallet_utility::Call::<Runtime>::batch_all {
970
1
					calls: vec![
971
1
						RuntimeCall::CrowdloanRewards(
972
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
973
1
								rewards: vec![(
974
1
									[4u8; 32].into(),
975
1
									Some(AccountId::from(CHARLIE)),
976
1
									1_500_000 * MOVR
977
1
								)]
978
1
							}
979
1
						),
980
1
						RuntimeCall::CrowdloanRewards(
981
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
982
1
								rewards: vec![(
983
1
									[5u8; 32].into(),
984
1
									Some(AccountId::from(DAVE)),
985
1
									1_500_000 * MOVR
986
1
								)]
987
1
							}
988
1
						),
989
1
						RuntimeCall::CrowdloanRewards(
990
1
							pallet_crowdloan_rewards::Call::<Runtime>::complete_initialization {
991
1
								lease_ending_block: end_block
992
1
							}
993
1
						)
994
1
					]
995
1
				})
996
1
				.dispatch(root_origin())
997
1
			);
998

            
999
1
			assert!(CrowdloanRewards::initialized());
			// 30 percent initial payout
1
			assert_eq!(Balances::balance(&AccountId::from(CHARLIE)), 450_000 * MOVR);
			// 30 percent initial payout
1
			assert_eq!(Balances::balance(&AccountId::from(DAVE)), 450_000 * MOVR);
1
			let crowdloan_precompile_address = H160::from_low_u64_be(2049);
1

            
1
			// Alice uses the crowdloan precompile to claim through the EVM
1
			let gas_limit = 100000u64;
1
			let gas_price: U256 = BASE_FEE_GENESIS.into();
1

            
1
			// Construct the call data (selector, amount)
1
			let mut call_data = Vec::<u8>::from([0u8; 4]);
1
			call_data[0..4].copy_from_slice(&Keccak256::digest(b"claim()")[0..4]);
1

            
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
1
				source: H160::from(CHARLIE),
1
				target: crowdloan_precompile_address,
1
				input: call_data,
1
				value: U256::zero(), // No value sent in EVM
1
				gas_limit,
1
				max_fee_per_gas: gas_price,
1
				max_priority_fee_per_gas: None,
1
				nonce: None, // Use the next nonce
1
				access_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let vesting_period = 4 * WEEKS as u128;
1
			let per_block = (1_050_000 * MOVR) / vesting_period;
1

            
1
			assert_eq!(
1
				CrowdloanRewards::accounts_payable(&AccountId::from(CHARLIE))
1
					.unwrap()
1
					.claimed_reward,
1
				(450_000 * MOVR) + per_block
1
			);
1
		})
1
}
#[test]
1
fn is_contributor_via_precompile() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * MOVR)])
1
		.with_mappings(vec![(
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
1
			AccountId::from(ALICE),
1
		)])
1
		.with_crowdloan_fund(3_000_000 * MOVR)
1
		.build()
1
		.execute_with(|| {
1
			// set parachain inherent data
1
			set_parachain_inherent_data();
1
			let init_block = CrowdloanRewards::init_vesting_block();
1
			// This matches the previous vesting
1
			let end_block = init_block + 4 * WEEKS;
1
			// Batch calls always succeed. We just need to check the inner event
1
			assert_ok!(
1
				RuntimeCall::Utility(pallet_utility::Call::<Runtime>::batch_all {
1
					calls: vec![
1
						RuntimeCall::CrowdloanRewards(
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
1
								rewards: vec![(
1
									[4u8; 32].into(),
1
									Some(AccountId::from(CHARLIE)),
1
									1_500_000 * MOVR
1
								)]
1
							}
1
						),
1
						RuntimeCall::CrowdloanRewards(
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
1
								rewards: vec![(
1
									[5u8; 32].into(),
1
									Some(AccountId::from(DAVE)),
1
									1_500_000 * MOVR
1
								)]
1
							}
1
						),
1
						RuntimeCall::CrowdloanRewards(
1
							pallet_crowdloan_rewards::Call::<Runtime>::complete_initialization {
1
								lease_ending_block: end_block
1
							}
1
						)
1
					]
1
				})
1
				.dispatch(root_origin())
1
			);
1
			let crowdloan_precompile_address = H160::from_low_u64_be(2049);
1

            
1
			// Assert precompile reports Bob is not a contributor
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					crowdloan_precompile_address,
1
					CrowdloanRewardsPCall::is_contributor {
1
						contributor: Address(AccountId::from(BOB).into()),
1
					},
1
				)
1
				.expect_cost(3338)
1
				.expect_no_logs()
1
				.execute_returns(false);
1

            
1
			// Assert precompile reports Charlie is a nominator
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					crowdloan_precompile_address,
1
					CrowdloanRewardsPCall::is_contributor {
1
						contributor: Address(AccountId::from(CHARLIE).into()),
1
					},
1
				)
1
				.expect_cost(3338)
1
				.expect_no_logs()
1
				.execute_returns(true);
1
		})
1
}
#[test]
1
fn reward_info_via_precompile() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * MOVR)])
1
		.with_mappings(vec![(
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
1
			AccountId::from(ALICE),
1
		)])
1
		.with_crowdloan_fund(3_000_000 * MOVR)
1
		.build()
1
		.execute_with(|| {
1
			// set parachain inherent data
1
			set_parachain_inherent_data();
1
			let init_block = CrowdloanRewards::init_vesting_block();
1
			// This matches the previous vesting
1
			let end_block = init_block + 4 * WEEKS;
1
			// Batch calls always succeed. We just need to check the inner event
1
			assert_ok!(
1
				RuntimeCall::Utility(pallet_utility::Call::<Runtime>::batch_all {
1
					calls: vec![
1
						RuntimeCall::CrowdloanRewards(
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
1
								rewards: vec![(
1
									[4u8; 32].into(),
1
									Some(AccountId::from(CHARLIE)),
1
									1_500_000 * MOVR
1
								)]
1
							}
1
						),
1
						RuntimeCall::CrowdloanRewards(
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
1
								rewards: vec![(
1
									[5u8; 32].into(),
1
									Some(AccountId::from(DAVE)),
1
									1_500_000 * MOVR
1
								)]
1
							}
1
						),
1
						RuntimeCall::CrowdloanRewards(
1
							pallet_crowdloan_rewards::Call::<Runtime>::complete_initialization {
1
								lease_ending_block: end_block
1
							}
1
						)
1
					]
1
				})
1
				.dispatch(root_origin())
1
			);
1
			let crowdloan_precompile_address = H160::from_low_u64_be(2049);
1

            
1
			let expected_total: U256 = (1_500_000 * MOVR).into();
1
			let expected_claimed: U256 = (450_000 * MOVR).into();
1

            
1
			// Assert precompile reports correct Charlie reward info.
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					crowdloan_precompile_address,
1
					CrowdloanRewardsPCall::reward_info {
1
						contributor: Address(AccountId::from(CHARLIE).into()),
1
					},
1
				)
1
				.expect_cost(3338)
1
				.expect_no_logs()
1
				.execute_returns((expected_total, expected_claimed));
1
		})
1
}
#[test]
1
fn update_reward_address_via_precompile() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * MOVR)])
1
		.with_mappings(vec![(
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
1
			AccountId::from(ALICE),
1
		)])
1
		.with_crowdloan_fund(3_000_000 * MOVR)
1
		.build()
1
		.execute_with(|| {
1
			// set parachain inherent data
1
			set_parachain_inherent_data();
1
			let init_block = CrowdloanRewards::init_vesting_block();
1
			// This matches the previous vesting
1
			let end_block = init_block + 4 * WEEKS;
1
			// Batch calls always succeed. We just need to check the inner event
1
			assert_ok!(
1
				RuntimeCall::Utility(pallet_utility::Call::<Runtime>::batch_all {
1
					calls: vec![
1
						RuntimeCall::CrowdloanRewards(
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
1
								rewards: vec![(
1
									[4u8; 32].into(),
1
									Some(AccountId::from(CHARLIE)),
1
									1_500_000 * MOVR
1
								)]
1
							}
1
						),
1
						RuntimeCall::CrowdloanRewards(
1
							pallet_crowdloan_rewards::Call::<Runtime>::initialize_reward_vec {
1
								rewards: vec![(
1
									[5u8; 32].into(),
1
									Some(AccountId::from(DAVE)),
1
									1_500_000 * MOVR
1
								)]
1
							}
1
						),
1
						RuntimeCall::CrowdloanRewards(
1
							pallet_crowdloan_rewards::Call::<Runtime>::complete_initialization {
1
								lease_ending_block: end_block
1
							}
1
						)
1
					]
1
				})
1
				.dispatch(root_origin())
1
			);
1
			let crowdloan_precompile_address = H160::from_low_u64_be(2049);
1

            
1
			// Charlie uses the crowdloan precompile to update address through the EVM
1
			let gas_limit = 100000u64;
1
			let gas_price: U256 = BASE_FEE_GENESIS.into();
1

            
1
			// Construct the input data to check if Bob is a contributor
1
			let mut call_data = Vec::<u8>::from([0u8; 36]);
1
			call_data[0..4]
1
				.copy_from_slice(&Keccak256::digest(b"update_reward_address(address)")[0..4]);
1
			call_data[16..36].copy_from_slice(&ALICE);
1

            
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
1
				source: H160::from(CHARLIE),
1
				target: crowdloan_precompile_address,
1
				input: call_data,
1
				value: U256::zero(), // No value sent in EVM
1
				gas_limit,
1
				max_fee_per_gas: gas_price,
1
				max_priority_fee_per_gas: None,
1
				nonce: None, // Use the next nonce
1
				access_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			assert!(CrowdloanRewards::accounts_payable(&AccountId::from(CHARLIE)).is_none());
1
			assert_eq!(
1
				CrowdloanRewards::accounts_payable(&AccountId::from(ALICE))
1
					.unwrap()
1
					.claimed_reward,
1
				(450_000 * MOVR)
1
			);
1
		})
1
}
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]
#[rustfmt::skip]
1
fn length_fee_is_sensible() {
	use sp_runtime::testing::TestXt;
	// tests that length fee is sensible for a few hypothetical transactions
1
	ExtBuilder::default().build().execute_with(|| {
1
		let call = frame_system::Call::remark::<Runtime> { remark: vec![] };
1
		let uxt: TestXt<_, ()> = TestXt::new_signed(RuntimeCall::System(call), 1u64, (), ());
1

            
9
		let calc_fee = |len: u32| -> Balance {
9
			moonriver_runtime::TransactionPayment::query_fee_details(uxt.clone(), len)
9
				.inclusion_fee
9
				.expect("fee should be calculated")
9
				.len_fee
9
		};
		//                  left: cost of length fee, right: size in bytes
		//                             /------------- proportional component: O(N * 1B)
		//                             |           /- exponential component: O(N ** 3)
		//                             |           |
1
		assert_eq!(                    1_000_000_001, calc_fee(1));
1
		assert_eq!(                   10_000_001_000, calc_fee(10));
1
		assert_eq!(                  100_001_000_000, calc_fee(100));
1
		assert_eq!(                1_001_000_000_000, calc_fee(1_000));
1
		assert_eq!(               11_000_000_000_000, calc_fee(10_000)); // inflection point
1
		assert_eq!(            1_100_000_000_000_000, calc_fee(100_000));
1
		assert_eq!(        1_001_000_000_000_000_000, calc_fee(1_000_000)); // one MOVR, ~ 1MB
1
		assert_eq!(    1_000_010_000_000_000_000_000, calc_fee(10_000_000));
1
		assert_eq!(1_000_000_100_000_000_000_000_000, calc_fee(100_000_000));
1
	});
1
}
#[test]
1
fn multiplier_can_grow_from_zero() {
	use frame_support::traits::Get;
1
	let minimum_multiplier = moonriver_runtime::MinimumMultiplier::get();
1
	let target = moonriver_runtime::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 =
1
			moonriver_runtime::SlowAdjustingFeeUpdate::<Runtime>::convert(minimum_multiplier);
1
		assert!(
1
			next > minimum_multiplier,
			"{:?} !>= {:?}",
			next,
			minimum_multiplier
		);
1
	})
1
}
#[test]
1
fn ethereum_invalid_transaction() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		// Ensure an extrinsic not containing enough gas limit to store the transaction
1
		// on chain is rejected.
1
		assert_eq!(
1
			Executive::apply_extrinsic(unchecked_eth_tx(INVALID_ETH_TX)),
1
			Err(
1
				sp_runtime::transaction_validity::TransactionValidityError::Invalid(
1
					sp_runtime::transaction_validity::InvalidTransaction::Custom(0u8)
1
				)
1
			)
1
		);
1
	});
1
}
#[test]
1
fn initial_gas_fee_is_correct() {
	use fp_evm::FeeCalculator;
1
	ExtBuilder::default().build().execute_with(|| {
1
		let multiplier = TransactionPayment::next_fee_multiplier();
1
		assert_eq!(multiplier, Multiplier::from(10u128));
1
		assert_eq!(
1
			TransactionPaymentAsGasPrice::min_gas_price(),
1
			(
1
				3_125_000_000u128.into(),
1
				Weight::from_parts(41_742_000u64, 0)
1
			)
1
		);
1
	});
1
}
#[test]
1
fn min_gas_fee_is_correct() {
	use fp_evm::FeeCalculator;
	use frame_support::traits::Hooks;
1
	ExtBuilder::default().build().execute_with(|| {
1
		pallet_transaction_payment::NextFeeMultiplier::<Runtime>::put(Multiplier::from(0));
1
		TransactionPayment::on_finalize(System::block_number()); // should trigger min to kick in
1

            
1
		let multiplier = TransactionPayment::next_fee_multiplier();
1
		assert_eq!(multiplier, Multiplier::from(1u128));
1
		assert_eq!(
1
			TransactionPaymentAsGasPrice::min_gas_price(),
1
			(312_500_000u128.into(), Weight::from_parts(41_742_000u64, 0))
1
		);
1
	});
1
}
#[test]
1
fn transfer_ed_0_substrate() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), (1 * MOVR) + (1 * WEI)),
1
			(AccountId::from(BOB), existential_deposit()),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			// Substrate transfer
1
			assert_ok!(Balances::transfer_allow_death(
1
				origin_of(AccountId::from(ALICE)),
1
				AccountId::from(BOB),
1
				1 * MOVR,
1
			));
			// 1 WEI is left in the account
1
			assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 1 * WEI);
1
		});
1
}
#[test]
1
fn transfer_ed_0_evm() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(
1
				AccountId::from(ALICE),
1
				((1 * MOVR) + (21_000 * BASE_FEE_GENESIS)) + (1 * WEI),
1
			),
1
			(AccountId::from(BOB), existential_deposit()),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			set_parachain_inherent_data();
1
			// EVM transfer
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
1
				source: H160::from(ALICE),
1
				target: H160::from(BOB),
1
				input: Vec::new(),
1
				value: (1 * MOVR).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: U256::from(BASE_FEE_GENESIS),
1
				max_priority_fee_per_gas: Some(U256::from(BASE_FEE_GENESIS)),
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
			// 1 WEI is left in the account
1
			assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 1 * WEI,);
1
		});
1
}
#[test]
1
fn refund_ed_0_evm() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(
1
				AccountId::from(ALICE),
1
				((1 * MOVR) + (21_777 * BASE_FEE_GENESIS) + existential_deposit()),
1
			),
1
			(AccountId::from(BOB), existential_deposit()),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			set_parachain_inherent_data();
1
			// EVM transfer that zeroes ALICE
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
1
				source: H160::from(ALICE),
1
				target: H160::from(BOB),
1
				input: Vec::new(),
1
				value: (1 * MOVR).into(),
1
				gas_limit: 21_777u64,
1
				max_fee_per_gas: U256::from(BASE_FEE_GENESIS),
1
				max_priority_fee_per_gas: Some(U256::from(BASE_FEE_GENESIS)),
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
			// ALICE is refunded
1
			assert_eq!(
1
				Balances::free_balance(AccountId::from(ALICE)),
1
				777 * BASE_FEE_GENESIS + existential_deposit(),
1
			);
1
		});
1
}
#[test]
1
fn author_does_receive_priority_fee() {
1
	ExtBuilder::default()
1
		.with_balances(vec![(
1
			AccountId::from(BOB),
1
			(1 * MOVR) + (21_000 * (500 * GIGAWEI)),
1
		)])
1
		.build()
1
		.execute_with(|| {
1
			// Some block author as seen by pallet-evm.
1
			let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
1
			pallet_author_inherent::Author::<Runtime>::put(author);
1
			// Currently the default impl of the evm uses `deposit_into_existing`.
1
			// If we were to use this implementation, and for an author to receive eventual tips,
1
			// the account needs to be somehow initialized, otherwise the deposit would fail.
1
			Balances::make_free_balance_be(&author, 100 * MOVR);
1

            
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 * MOVR).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
			})
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 * MOVR + 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 * MOVR) + (21_000 * (2 * 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
			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 * MOVR).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: U256::from(2u128 * BASE_FEE_GENESIS),
1
				max_priority_fee_per_gas: Some(U256::from(2u128 * BASE_FEE_GENESIS)),
1
				nonce: Some(U256::from(0)),
1
				access_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!(moonriver_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 * MOVR) + (21_000 * (2 * 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
			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 * MOVR).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: U256::from(BASE_FEE_GENESIS),
1
				max_priority_fee_per_gas: None,
1
				nonce: Some(U256::from(0)),
1
				access_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!(moonriver_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 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
1
			metadata: AssetRegistrarMetadata {
1
				name: b"RelayToken".to_vec(),
1
				symbol: b"Relay".to_vec(),
1
				decimals: 12,
1
				is_frozen: false,
1
			},
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
			is_sufficient: true,
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let source_location = AssetType::Xcm(xcm::v3::Location::parent());
1
			let dest = Location {
1
				parents: 1,
1
				interior: [AccountId32 {
1
					network: None,
1
					id: [1u8; 32],
1
				}]
1
				.into(),
1
			};
1
			let source_id: moonriver_runtime::AssetId = source_location.clone().into();
1
			let asset = currency_to_asset(CurrencyId::ForeignAsset(source_id), 100_000_000_000_000);
1
			let (chain_part, beneficiary) =
1
				split_location_into_chain_part_and_beneficiary(dest).unwrap();
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(xcm::VersionedLocation::from(chain_part.clone())),
1
					Box::new(xcm::VersionedLocation::from(beneficiary.clone())),
1
					Box::new(VersionedAssets::from(asset.clone())),
1
					0,
1
					WeightLimit::Limited(4000000000.into())
1
				),
1
				pallet_xcm::Error::<Runtime>::SendFailure
1
			);
			// Root sets the defaultXcm
1
			assert_ok!(PolkadotXcm::force_default_xcm_version(
1
				root_origin(),
1
				Some(3)
1
			));
			// Now transferring does not fail
1
			assert_ok!(PolkadotXcm::transfer_assets(
1
				origin_of(AccountId::from(ALICE)),
1
				Box::new(xcm::VersionedLocation::from(chain_part)),
1
				Box::new(xcm::VersionedLocation::from(beneficiary)),
1
				Box::new(VersionedAssets::from(asset.clone())),
1
				0,
1
				WeightLimit::Limited(4000000000.into())
1
			));
1
		})
1
}
#[test]
1
fn asset_can_be_registered() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		let source_location = AssetType::Xcm(xcm::v3::Location::parent());
1
		let source_id: moonriver_runtime::AssetId = source_location.clone().into();
1
		let asset_metadata = AssetRegistrarMetadata {
1
			name: b"RelayToken".to_vec(),
1
			symbol: b"Relay".to_vec(),
1
			decimals: 12,
1
			is_frozen: false,
1
		};
1
		assert_ok!(AssetManager::register_foreign_asset(
1
			moonriver_runtime::RuntimeOrigin::root(),
1
			source_location,
1
			asset_metadata,
1
			1u128,
1
			true
1
		));
1
		assert!(AssetManager::asset_id_type(source_id).is_some());
1
	});
1
}
#[test]
1
fn xcm_asset_erc20_precompiles_supply_and_balance() {
1
	ExtBuilder::default()
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
1
			metadata: AssetRegistrarMetadata {
1
				name: b"RelayToken".to_vec(),
1
				symbol: b"Relay".to_vec(),
1
				decimals: 12,
1
				is_frozen: false,
1
			},
1
			balances: vec![(AccountId::from(ALICE), 1_000 * MOVR)],
1
			is_sufficient: true,
1
		}])
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			// We have the assetId that corresponds to the relay chain registered
1
			let relay_asset_id: AssetId = AssetType::Xcm(xcm::v3::Location::parent()).into();
1

            
1
			// Its address is
1
			let asset_precompile_address = Runtime::asset_id_to_account(
1
				FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
1
				relay_asset_id,
1
			);
1

            
1
			// Assert the asset has been created with the correct supply
1
			assert_eq!(
1
				moonriver_runtime::Assets::total_supply(relay_asset_id),
1
				1_000 * MOVR
1
			);
			// Access totalSupply through precompile. Important that the context is correct
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					asset_precompile_address,
1
					ForeignAssetsPCall::total_supply {},
1
				)
1
				.expect_cost(5007)
1
				.expect_no_logs()
1
				.execute_returns(U256::from(1000 * MOVR));
1

            
1
			// Access balanceOf through precompile
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					asset_precompile_address,
1
					ForeignAssetsPCall::balance_of {
1
						who: Address(ALICE.into()),
1
					},
1
				)
1
				.expect_cost(5007)
1
				.expect_no_logs()
1
				.execute_returns(U256::from(1000 * MOVR));
1
		});
1
}
#[test]
1
fn xcm_asset_erc20_precompiles_transfer() {
1
	ExtBuilder::default()
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
1
			metadata: AssetRegistrarMetadata {
1
				name: b"RelayToken".to_vec(),
1
				symbol: b"Relay".to_vec(),
1
				decimals: 12,
1
				is_frozen: false,
1
			},
1
			balances: vec![(AccountId::from(ALICE), 1_000 * MOVR)],
1
			is_sufficient: true,
1
		}])
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			// We have the assetId that corresponds to the relay chain registered
1
			let relay_asset_id: AssetId = AssetType::Xcm(xcm::v3::Location::parent()).into();
1

            
1
			// Its address is
1
			let asset_precompile_address = Runtime::asset_id_to_account(
1
				FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
1
				relay_asset_id,
1
			);
1

            
1
			// Transfer tokens from Aice to Bob, 400 MOVR.
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					asset_precompile_address,
1
					ForeignAssetsPCall::transfer {
1
						to: Address(BOB.into()),
1
						value: { 400 * MOVR }.into(),
1
					},
1
				)
1
				.expect_cost(26682)
1
				.expect_log(log3(
1
					asset_precompile_address,
1
					SELECTOR_LOG_TRANSFER,
1
					H160::from(ALICE),
1
					H160::from(BOB),
1
					solidity::encode_event_data(U256::from(400 * MOVR)),
1
				))
1
				.execute_returns(true);
1

            
1
			// Make sure BOB has 400 MOVR
1
			Precompiles::new()
1
				.prepare_test(
1
					BOB,
1
					asset_precompile_address,
1
					ForeignAssetsPCall::balance_of {
1
						who: Address(BOB.into()),
1
					},
1
				)
1
				.expect_cost(5007)
1
				.expect_no_logs()
1
				.execute_returns(U256::from(400 * MOVR));
1
		});
1
}
#[test]
1
fn xcm_asset_erc20_precompiles_approve() {
1
	ExtBuilder::default()
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
1
			metadata: AssetRegistrarMetadata {
1
				name: b"RelayToken".to_vec(),
1
				symbol: b"Relay".to_vec(),
1
				decimals: 12,
1
				is_frozen: false,
1
			},
1
			balances: vec![(AccountId::from(ALICE), 1_000 * MOVR)],
1
			is_sufficient: true,
1
		}])
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			// We have the assetId that corresponds to the relay chain registered
1
			let relay_asset_id: AssetId = AssetType::Xcm(xcm::v3::Location::parent()).into();
1

            
1
			// Its address is
1
			let asset_precompile_address = Runtime::asset_id_to_account(
1
				FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
1
				relay_asset_id,
1
			);
1

            
1
			// Aprove Bob for spending 400 MOVR from Alice
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					asset_precompile_address,
1
					ForeignAssetsPCall::approve {
1
						spender: Address(BOB.into()),
1
						value: { 400 * MOVR }.into(),
1
					},
1
				)
1
				.expect_cost(17333)
1
				.expect_log(log3(
1
					asset_precompile_address,
1
					SELECTOR_LOG_APPROVAL,
1
					H160::from(ALICE),
1
					H160::from(BOB),
1
					solidity::encode_event_data(U256::from(400 * MOVR)),
1
				))
1
				.execute_returns(true);
1

            
1
			// Transfer tokens from Alice to Charlie by using BOB as origin
1
			Precompiles::new()
1
				.prepare_test(
1
					BOB,
1
					asset_precompile_address,
1
					ForeignAssetsPCall::transfer_from {
1
						from: Address(ALICE.into()),
1
						to: Address(CHARLIE.into()),
1
						value: { 400 * MOVR }.into(),
1
					},
1
				)
1
				.expect_cost(31980)
1
				.expect_log(log3(
1
					asset_precompile_address,
1
					SELECTOR_LOG_TRANSFER,
1
					H160::from(ALICE),
1
					H160::from(CHARLIE),
1
					solidity::encode_event_data(U256::from(400 * MOVR)),
1
				))
1
				.execute_returns(true);
1

            
1
			// Make sure CHARLIE has 400 MOVR
1
			Precompiles::new()
1
				.prepare_test(
1
					CHARLIE,
1
					asset_precompile_address,
1
					ForeignAssetsPCall::balance_of {
1
						who: Address(CHARLIE.into()),
1
					},
1
				)
1
				.expect_cost(5007)
1
				.expect_no_logs()
1
				.execute_returns(U256::from(400 * MOVR));
1
		});
1
}
#[test]
1
fn xtokens_precompiles_transfer() {
2
	fn run_test_variant(evm_native: bool) {
2
		let mut builder = ExtBuilder::default();
2

            
2
		if evm_native {
1
			builder = builder.with_evm_native_foreign_assets();
1
		}
2
		let asset_type = AssetType::Xcm(xcm::v3::Location::parent());
2
		builder
2
			.with_xcm_assets(vec![XcmAssetInitialization {
2
				asset_type: asset_type.clone(),
2
				metadata: AssetRegistrarMetadata {
2
					name: b"RelayToken".to_vec(),
2
					symbol: b"Relay".to_vec(),
2
					decimals: 12,
2
					is_frozen: false,
2
				},
2
				balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
2
				is_sufficient: true,
2
			}])
2
			.with_balances(vec![
2
				(AccountId::from(ALICE), 2_000 * MOVR),
2
				(AccountId::from(BOB), 1_000 * MOVR),
2
			])
2
			.with_safe_xcm_version(3)
2
			.build()
2
			.execute_with(|| {
2
				let xtokens_precompile_address = H160::from_low_u64_be(2052);
2

            
2
				// We have the assetId that corresponds to the relay chain registered
2
				let relay_asset_id: AssetId = AssetType::Xcm(xcm::v3::Location::parent()).into();
2

            
2
				// Its address is
2
				let asset_precompile_address = Runtime::asset_id_to_account(
2
					FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
2
					relay_asset_id,
2
				);
2

            
2
				// Alice has 1000 tokens. She should be able to send through precompile
2
				let destination = Location::new(
2
					1,
2
					[Junction::AccountId32 {
2
						network: None,
2
						id: [1u8; 32],
2
					}],
2
				);
2

            
2
				let inside = Rc::new(Cell::new(false));
2
				let inside2 = inside.clone();
2

            
2
				// We use the address of the asset as an identifier of the asset we want to transfer
2
				Precompiles::new()
2
					.prepare_test(
2
						ALICE,
2
						xtokens_precompile_address,
2
						XtokensPCall::transfer {
2
							currency_address: Address(asset_precompile_address.into()),
2
							amount: 500_000_000_000_000u128.into(),
2
							destination,
2
							weight: 4_000_000,
2
						},
2
					)
2
					.expect_cost(if evm_native { 178519 } else { 26919 })
2
					.expect_no_logs()
2
					// We expect an evm subcall ERC20.burnFrom
2
					.with_subcall_handle(move |subcall| {
1
						let Subcall {
1
							address,
1
							transfer,
1
							input,
1
							target_gas: _,
1
							is_static,
1
							context,
1
						} = subcall;
1

            
1
						assert_eq!(context.caller, EvmForeignAssets::account_id().into());
1
						let asset_id: u128 = asset_type.clone().into();
1
						let expected_address: H160 = Runtime::asset_id_to_account(
1
							FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
1
							asset_id,
1
						)
1
						.into();
1
						assert_eq!(address, expected_address);
1
						assert_eq!(is_static, false);
1
						assert!(transfer.is_none());
1
						assert_eq!(context.address, expected_address);
1
						assert_eq!(context.apparent_value, 0u8.into());
1
						assert_eq!(&input[..4], &keccak256!("burnFrom(address,uint256)")[..4]);
1
						assert_eq!(&input[4..16], &[0u8; 12]);
1
						assert_eq!(&input[16..36], ALICE);
1
						inside2.set(true);
1

            
1
						SubcallOutput {
1
							output: Default::default(),
1
							cost: 149_000,
1
							logs: vec![],
1
							..SubcallOutput::succeed()
1
						}
2
					})
2
					.execute_returns(())
2
			})
2
	}
1
	run_test_variant(false);
1
	run_test_variant(true);
1
}
#[test]
1
fn xtokens_precompiles_transfer_multiasset() {
1
	ExtBuilder::default()
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
1
			metadata: AssetRegistrarMetadata {
1
				name: b"RelayToken".to_vec(),
1
				symbol: b"Relay".to_vec(),
1
				decimals: 12,
1
				is_frozen: false,
1
			},
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
			is_sufficient: true,
1
		}])
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			let xtokens_precompile_address = H160::from_low_u64_be(2052);
1

            
1
			// Alice has 1000 tokens. She should be able to send through precompile
1
			let destination = Location::new(
1
				1,
1
				[Junction::AccountId32 {
1
					network: None,
1
					id: [1u8; 32],
1
				}],
1
			);
1

            
1
			// This time we transfer it through TransferMultiAsset
1
			// Instead of the address, we encode directly the multilocation referencing the asset
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					xtokens_precompile_address,
1
					XtokensPCall::transfer_multiasset {
1
						// We want to transfer the relay token
1
						asset: Location::parent(),
1
						amount: 500_000_000_000_000u128.into(),
1
						destination,
1
						weight: 4_000_000,
1
					},
1
				)
1
				.expect_cost(26919)
1
				.expect_no_logs()
1
				.execute_returns(());
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 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * MOVR)])
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(moonriver_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 transactor_cannot_use_more_than_max_weight() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
1
			metadata: AssetRegistrarMetadata {
1
				name: b"RelayToken".to_vec(),
1
				symbol: b"Relay".to_vec(),
1
				decimals: 12,
1
				is_frozen: false,
1
			},
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
			is_sufficient: true,
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let source_location = AssetType::Xcm(xcm::v3::Location::parent());
1
			let source_id: moonriver_runtime::AssetId = source_location.clone().into();
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
					moonriver_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
					// 2000 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
					moonriver_runtime::xcm_config::Transactors::Relay,
1
					0,
1
					CurrencyPayment {
1
						currency: Currency::AsCurrencyId(CurrencyId::ForeignAsset(source_id)),
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
}
#[test]
1
fn transact_through_signed_precompile_works_v2() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
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(25383)
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 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
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 call_xtokens_with_fee() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * MOVR),
1
			(AccountId::from(BOB), 1_000 * MOVR),
1
		])
1
		.with_safe_xcm_version(3)
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_type: AssetType::Xcm(xcm::v3::Location::parent()),
1
			metadata: AssetRegistrarMetadata {
1
				name: b"RelayToken".to_vec(),
1
				symbol: b"Relay".to_vec(),
1
				decimals: 12,
1
				is_frozen: false,
1
			},
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
			is_sufficient: true,
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let source_location = AssetType::Xcm(xcm::v3::Location::parent());
1
			let dest = Location {
1
				parents: 1,
1
				interior: [AccountId32 {
1
					network: None,
1
					id: [1u8; 32],
1
				}]
1
				.into(),
1
			};
1
			let source_id: moonriver_runtime::AssetId = source_location.clone().into();
1

            
1
			let before_balance =
1
				moonriver_runtime::Assets::balance(source_id, &AccountId::from(ALICE));
1

            
1
			let asset = currency_to_asset(CurrencyId::ForeignAsset(source_id), 100_000_000_000_000);
1
			let asset_fee = currency_to_asset(CurrencyId::ForeignAsset(source_id), 100);
1
			let (chain_part, beneficiary) =
1
				split_location_into_chain_part_and_beneficiary(dest).unwrap();
1

            
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
				moonriver_runtime::Assets::balance(source_id, &AccountId::from(ALICE));
1
			// At least these much (plus fees) should have been charged
1
			assert_eq!(before_balance - 100_000_000_000_000 - 100, after_balance);
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(3338)
1
			.expect_no_logs()
1
			.execute_returns(Address(expected_address_parent));
1

            
1
		let parachain_2000_multilocation = Location::new(1, [Parachain(2000)]);
1
		let expected_address_parachain: H160 =
1
			SiblingParachainConvertsVia::<Sibling, AccountId>::convert_location(
1
				&parachain_2000_multilocation,
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_multilocation,
1
				},
1
			)
1
			.expect_cost(3338)
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(3338)
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::<moonriver_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(1669)
1
			.expect_no_logs()
1
			.execute_returns(expected_weight);
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 * moonriver_runtime::currency::WEIGHT_FEE;
1

            
1
		Precompiles::new()
1
			.prepare_test(ALICE, xcm_utils_precompile_address, input)
1
			.expect_cost(3338)
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, 256, 1024, 1025, 1026, 2048, 2049, 2050, 2051, 2052, 2053,
1
			2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067,
1
			2068, 2069, 2070, 2071, 2072, 2073, 2074,
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) {
40
				assert!(
40
					is_precompile_or_fail::<Runtime>(address, 100_000u64).expect("to be ok"),
					"is_precompile({}) should return true",
					i
				);
40
				assert!(
40
					precompiles
40
						.execute(&mut MockHandle::new(
40
							address,
40
							Context {
40
								address,
40
								caller: H160::zero(),
40
								apparent_value: U256::zero()
40
							}
40
						),)
40
						.is_some(),
					"execute({},..) should return Some(_)",
					i
				);
			} else {
2960
				assert!(
2960
					!is_precompile_or_fail::<Runtime>(address, 100_000u64).expect("to be ok"),
					"is_precompile({}) should return false",
					i
				);
2960
				assert!(
2960
					precompiles
2960
						.execute(&mut MockHandle::new(
2960
							address,
2960
							Context {
2960
								address,
2960
								caller: H160::zero(),
2960
								apparent_value: U256::zero()
2960
							}
2960
						),)
2960
						.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") {
2959
				continue;
40
			}
40

            
40
			if !removed_precompiles.contains(&i) {
36
				assert!(
36
					match precompiles.is_active_precompile(address, 100_000u64) {
36
						IsPrecompileResult::Answer { is_precompile, .. } => is_precompile,
						_ => false,
					},
					"{i} should be an active precompile"
				);
36
				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_common::deal_with_fees::DealWithSubstrateFeesAndTip;
	use moonriver_runtime::Treasury;
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 Moonriver 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), 1_000 * MOVR)])
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
				input: BatchPCall::batch_all {
1
					to: vec![Address(BOB.into()), Address(batch_precompile_address)].into(),
1
					value: vec![U256::from(1 * MOVR), 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: U256::from(BASE_FEE_GENESIS),
1
				max_priority_fee_per_gas: None,
1
				nonce: Some(U256::from(0)),
1
				access_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 {
					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), 1_000 * MOVR)])
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 * MOVR)].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: U256::from(BASE_FEE_GENESIS),
1
				max_priority_fee_per_gas: None,
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let transfer_count = System::events()
1
				.iter()
10
				.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 treasury_tests {
	use super::*;
	use frame_support::traits::fungible::NativeOrWithId;
	use moonriver_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 * MOVR;
1
		ExtBuilder::default()
1
			.with_balances(vec![
1
				(AccountId::from(ALICE), 2_000 * MOVR),
1
				(Treasury::account_id(), initial_treasury_balance),
1
			])
1
			.build()
1
			.execute_with(|| {
1
				let spend_amount = 100u128 * MOVR;
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 * MOVR;
1
		let asset_id = 1000100010001000u128;
1
		ExtBuilder::default()
1
			.with_balances(vec![(AccountId::from(ALICE), 2_000 * MOVR)])
1
			.build()
1
			.execute_with(|| {
1
				let spend_amount = 100u128 * MOVR;
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 moonriver_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 = Weight::from_parts(5_000u64, 1);
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 = WeightToFeeImpl::weight_to_fee(&base_extrinsic)
1
			+ multiplier.saturating_mul_int(WeightToFeeImpl::weight_to_fee(&extrinsic_weight))
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: extrinsic_weight,
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(100_000_000, Perbill::from_percent(0), 1),
1
				U256::from(312_500_000u128), // lower bound enforced
1
			);
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(25), 1),
1
				U256::from(312_500_000u128),
1
			);
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(50), 1),
1
				U256::from(312_687_556u128), // slightly higher than lower bound
1
			);
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(100), 1),
1
				U256::from(313_313_556u128),
1
			);
			// 1 "real" hour (at 6-second blocks)
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(0), 600),
1
				U256::from(312_500_000u128),
1
			);
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(25), 600),
1
				U256::from(312_500_000u128),
1
			);
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(50), 600),
1
				U256::from(447_915_432u128),
1
			);
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(100), 600),
1
				U256::from(1_487_129_030u128),
1
			);
			// 1 "real" day (at 6-second blocks)
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(0), 14400),
1
				U256::from(312_500_000u128), // lower bound enforced
1
			);
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(25), 14400),
1
				U256::from(312_500_000u128),
1
			);
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(50), 14400),
1
				U256::from(1_766_664_654_709u128),
1
			);
1
			assert_eq!(
1
				sim(100_000_000, Perbill::from_percent(100), 14400),
1
				U256::from(31_250_000_000_000u128), // upper bound enforced
1
			);
1
		});
1
	}
}