1
// Copyright 2019-2022 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Moonriver Runtime Integration Tests
18

            
19
#![cfg(test)]
20

            
21
mod common;
22
use common::*;
23

            
24
use fp_evm::{Context, IsPrecompileResult};
25
use frame_support::traits::fungible::Inspect;
26
use frame_support::{
27
	assert_noop, assert_ok,
28
	dispatch::DispatchClass,
29
	traits::{Currency as CurrencyT, EnsureOrigin, PalletInfo, StorageInfo, StorageInfoTrait},
30
	weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
31
	StorageHasher, Twox128,
32
};
33
use moonbeam_xcm_benchmarks::weights::XcmWeight;
34
use moonkit_xcm_primitives::AccountIdAssetIdConversion;
35
use moonriver_runtime::currency::{GIGAWEI, WEI};
36
use moonriver_runtime::{
37
	asset_config::ForeignAssetInstance,
38
	xcm_config::{CurrencyId, SelfReserve},
39
	AssetId, Balances, CrowdloanRewards, Executive, OpenTechCommitteeCollective, PolkadotXcm,
40
	Precompiles, RuntimeBlockWeights, TransactionPayment, TransactionPaymentAsGasPrice,
41
	TreasuryCouncilCollective, XcmTransactor, FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX, WEEKS,
42
};
43
use nimbus_primitives::NimbusId;
44
use pallet_evm::PrecompileSet;
45
use pallet_evm_precompileset_assets_erc20::{SELECTOR_LOG_APPROVAL, SELECTOR_LOG_TRANSFER};
46
use pallet_transaction_payment::Multiplier;
47
use pallet_xcm_transactor::{Currency, CurrencyPayment, TransactWeights};
48
use parity_scale_codec::Encode;
49
use polkadot_parachain::primitives::Sibling;
50
use precompile_utils::{
51
	precompile_set::{is_precompile_or_fail, IsActivePrecompile},
52
	prelude::*,
53
	testing::*,
54
};
55
use sha3::{Digest, Keccak256};
56
use sp_core::{ByteArray, Pair, H160, U256};
57
use sp_runtime::{
58
	traits::{Convert, Dispatchable},
59
	BuildStorage, DispatchError, ModuleError,
60
};
61
use std::str::from_utf8;
62
use xcm::latest::prelude::*;
63
use xcm::{VersionedAssets, VersionedLocation};
64
use xcm_builder::{ParentIsPreset, SiblingParachainConvertsVia};
65
use xcm_executor::traits::ConvertLocation;
66
use xcm_primitives::split_location_into_chain_part_and_beneficiary;
67

            
68
type BatchPCall = pallet_evm_precompile_batch::BatchPrecompileCall<Runtime>;
69
type CrowdloanRewardsPCall =
70
	pallet_evm_precompile_crowdloan_rewards::CrowdloanRewardsPrecompileCall<Runtime>;
71
type XcmUtilsPCall = pallet_evm_precompile_xcm_utils::XcmUtilsPrecompileCall<
72
	Runtime,
73
	moonriver_runtime::xcm_config::XcmExecutorConfig,
74
>;
75
type XtokensPCall = pallet_evm_precompile_xtokens::XtokensPrecompileCall<Runtime>;
76
type ForeignAssetsPCall = pallet_evm_precompileset_assets_erc20::Erc20AssetsPrecompileSetCall<
77
	Runtime,
78
	ForeignAssetInstance,
79
>;
80
type XcmTransactorV2PCall =
81
	pallet_evm_precompile_xcm_transactor::v2::XcmTransactorPrecompileV2Call<Runtime>;
82

            
83
const BASE_FEE_GENESIS: u128 = 100 * GIGAWEI;
84

            
85
3
fn currency_to_asset(currency_id: CurrencyId, amount: u128) -> Asset {
86
3
	Asset {
87
3
		id: AssetId(
88
3
			<moonriver_runtime::Runtime as pallet_xcm_transactor::Config>::CurrencyIdToLocation::convert(
89
3
				currency_id,
90
3
			)
91
3
			.unwrap(),
92
3
		),
93
3
		fun: Fungibility::Fungible(amount),
94
3
	}
95
3
}
96

            
97
#[test]
98
1
fn xcmp_queue_controller_origin_is_root() {
99
1
	// important for the XcmExecutionManager impl of PauseExecution which uses root origin
100
1
	// to suspend/resume XCM execution in xcmp_queue::on_idle
101
1
	assert_ok!(
102
1
		<moonriver_runtime::Runtime as cumulus_pallet_xcmp_queue::Config
103
1
		>::ControllerOrigin::ensure_origin(root_origin())
104
1
	);
105
1
}
106

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

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

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

            
292
6
	for StorageInfo { pallet_name, .. } in
293
7
		<moonriver_runtime::OpenTechCommitteeCollective as StorageInfoTrait>::storage_info()
294
	{
295
6
		assert_eq!(pallet_name, b"OpenTechCommitteeCollective".to_vec());
296
	}
297
1
}
298

            
299
#[test]
300
1
fn collective_set_members_root_origin_works() {
301
1
	ExtBuilder::default().build().execute_with(|| {
302
1
		// TreasuryCouncilCollective
303
1
		assert_ok!(TreasuryCouncilCollective::set_members(
304
1
			<Runtime as frame_system::Config>::RuntimeOrigin::root(),
305
1
			vec![AccountId::from(ALICE), AccountId::from(BOB)],
306
1
			Some(AccountId::from(ALICE)),
307
1
			2
308
1
		));
309
		// OpenTechCommitteeCollective
310
1
		assert_ok!(OpenTechCommitteeCollective::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
1
	});
317
1
}
318

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

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

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

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

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

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

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

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

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

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

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

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

            
602
			// Charlie can stake now
603
1
			assert_ok!(ParachainStaking::join_candidates(
604
1
				origin_of(AccountId::from(CHARLIE)),
605
1
				10_000 * MOVR,
606
1
				2u32,
607
1
			),);
608
1
			let candidates = ParachainStaking::candidate_pool();
609
1
			assert_eq!(candidates.0[0].owner, AccountId::from(CHARLIE));
610
1
			assert_eq!(candidates.0[0].amount, 10_000 * MOVR);
611
1
		});
612
1
}
613

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

            
636
1
			// Just before round 3
637
1
			run_to_block(2399, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
638
1

            
639
1
			// no rewards doled out yet
640
1
			assert_eq!(
641
1
				Balances::usable_balance(AccountId::from(ALICE)),
642
1
				10_100 * MOVR,
643
1
			);
644
1
			assert_eq!(Balances::usable_balance(AccountId::from(BOB)), 9500 * MOVR,);
645
1
			run_to_block(2401, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
646
1

            
647
1
			// rewards minted and distributed
648
1
			assert_eq!(
649
1
				Balances::usable_balance(AccountId::from(ALICE)),
650
1
				11547666666208000000000,
651
1
			);
652
1
			assert_eq!(
653
1
				Balances::usable_balance(AccountId::from(BOB)),
654
1
				9557333332588000000000,
655
1
			);
656
1
		});
657
1
}
658

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

            
686
			// Stop just before round 2
687
1
			run_to_block(1199, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
688
1

            
689
1
			// no collator rewards doled out yet
690
1
			assert_eq!(
691
1
				Balances::usable_balance(AccountId::from(ALICE)),
692
1
				10_100 * MOVR,
693
1
			);
694
1
			assert_eq!(Balances::usable_balance(AccountId::from(BOB)), 9500 * MOVR,);
695

            
696
			// Go to round 2
697
1
			run_to_block(1201, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
698
1

            
699
1
			// 30% reserved for parachain bond
700
1
			assert_eq!(
701
1
				Balances::usable_balance(AccountId::from(CHARLIE)),
702
1
				452515000000000000000,
703
1
			);
704

            
705
			// Go to round 3
706
1
			run_to_block(2401, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
707
1

            
708
1
			// rewards minted and distributed
709
1
			assert_eq!(
710
1
				Balances::usable_balance(AccountId::from(ALICE)),
711
1
				11117700475903800000000,
712
1
			);
713
1
			assert_eq!(
714
1
				Balances::usable_balance(AccountId::from(BOB)),
715
1
				9535834523343675000000,
716
1
			);
717
			// 30% reserved for parachain bond again
718
1
			assert_eq!(
719
1
				Balances::usable_balance(AccountId::from(CHARLIE)),
720
1
				910802725000000000000,
721
1
			);
722
1
		});
723
1
}
724

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

            
806
1
			let vesting_period = 48 * WEEKS as u128;
807
1
			let per_block = (1_050_000 * MOVR) / vesting_period;
808
1

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

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

            
858
1
			let (pair1, _) = sp_core::sr25519::Pair::generate();
859
1
			let (pair2, _) = sp_core::sr25519::Pair::generate();
860
1

            
861
1
			let public1 = pair1.public();
862
1
			let public2 = pair2.public();
863
1

            
864
1
			// signature:
865
1
			// WRAP_BYTES|| NetworkIdentifier|| new_account || previous_account || WRAP_BYTES
866
1
			let mut message = pallet_crowdloan_rewards::WRAPPED_BYTES_PREFIX.to_vec();
867
1
			message.append(&mut b"moonriver-".to_vec());
868
1
			message.append(&mut AccountId::from(DAVE).encode());
869
1
			message.append(&mut AccountId::from(CHARLIE).encode());
870
1
			message.append(&mut pallet_crowdloan_rewards::WRAPPED_BYTES_POSTFIX.to_vec());
871
1
			let signature1 = pair1.sign(&message);
872
1
			let signature2 = pair2.sign(&message);
873
1

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

            
909
			// this should fail, as we are only providing one signature
910
1
			assert_noop!(
911
1
				CrowdloanRewards::change_association_with_relay_keys(
912
1
					origin_of(AccountId::from(CHARLIE)),
913
1
					AccountId::from(DAVE),
914
1
					AccountId::from(CHARLIE),
915
1
					vec![(public1.into(), signature1.clone().into())]
916
1
				),
917
1
				pallet_crowdloan_rewards::Error::<Runtime>::InsufficientNumberOfValidProofs
918
1
			);
919

            
920
			// this should be valid
921
1
			assert_ok!(CrowdloanRewards::change_association_with_relay_keys(
922
1
				origin_of(AccountId::from(CHARLIE)),
923
1
				AccountId::from(DAVE),
924
1
				AccountId::from(CHARLIE),
925
1
				vec![
926
1
					(public1.into(), signature1.into()),
927
1
					(public2.into(), signature2.into())
928
1
				]
929
1
			));
930

            
931
1
			assert_eq!(
932
1
				CrowdloanRewards::accounts_payable(&AccountId::from(DAVE))
933
1
					.unwrap()
934
1
					.claimed_reward,
935
1
				(900_000 * MOVR)
936
1
			);
937
1
		});
938
1
}
939

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

            
992
1
			assert!(CrowdloanRewards::initialized());
993

            
994
			// 30 percent initial payout
995
1
			assert_eq!(Balances::balance(&AccountId::from(CHARLIE)), 450_000 * MOVR);
996
			// 30 percent initial payout
997
1
			assert_eq!(Balances::balance(&AccountId::from(DAVE)), 450_000 * MOVR);
998

            
999
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(1669)
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(1669)
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(1669)
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() {
1
	use sp_runtime::testing::TestXt;
1

            
1
	// 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(call, Some((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
		};
		// editorconfig-checker-disable
		//                  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));
		// editorconfig-checker-enable
1
	});
1
}
#[test]
1
fn multiplier_can_grow_from_zero() {
1
	use frame_support::traits::Get;
1

            
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() {
1
	use fp_evm::FeeCalculator;
1

            
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
				12_500_000_000u128.into(),
1
				Weight::from_parts(41_742_000u64, 0)
1
			)
1
		);
1
	});
1
}
#[test]
1
fn min_gas_fee_is_correct() {
1
	use fp_evm::FeeCalculator;
1
	use frame_support::traits::Hooks;
1

            
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
			(
1
				1_250_000_000u128.into(),
1
				Weight::from_parts(41_742_000u64, 0)
1
			)
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), 0),
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), 0),
1
		])
1
		.build()
1
		.execute_with(|| {
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)),
1
			),
1
			(AccountId::from(BOB), 0),
1
		])
1
		.build()
1
		.execute_with(|| {
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,
1
			);
1
		});
1
}
#[test]
1
fn author_does_not_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
			// 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()));
			// Author free balance didn't change.
1
			assert_eq!(Balances::free_balance(author), 100 * MOVR,);
1
		});
1
}
#[test]
1
fn total_issuance_after_evm_transaction_with_priority_fee() {
1
	ExtBuilder::default()
1
		.with_balances(vec![(
1
			AccountId::from(BOB),
1
			(1 * MOVR) + (21_000 * (2 * BASE_FEE_GENESIS)),
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(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
			let fee = ((2 * BASE_FEE_GENESIS) * 21_000) as f64;
1
			// 80% was burned.
1
			let expected_burn = (fee * 0.8) as u128;
1
			assert_eq!(issuance_after, issuance_before - expected_burn,);
			// 20% was sent to treasury.
1
			let expected_treasury = (fee * 0.2) as u128;
1
			assert_eq!(moonriver_runtime::Treasury::pot(), expected_treasury);
1
		});
1
}
#[test]
1
fn total_issuance_after_evm_transaction_without_priority_fee() {
1
	ExtBuilder::default()
1
		.with_balances(vec![(
1
			AccountId::from(BOB),
1
			(1 * MOVR) + (21_000 * (2 * BASE_FEE_GENESIS)),
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: 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
			let issuance_after = <Runtime as pallet_evm::Config>::Currency::total_issuance();
1
			let fee = ((1 * BASE_FEE_GENESIS) * 21_000) as f64;
1
			// 80% was burned.
1
			let expected_burn = (fee * 0.8) as u128;
1
			assert_eq!(issuance_after, issuance_before - expected_burn,);
			// 20% was sent to treasury.
1
			let expected_treasury = (fee * 0.2) as u128;
1
			assert_eq!(moonriver_runtime::Treasury::pot(), expected_treasury);
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::V4(chain_part.clone())),
1
					Box::new(xcm::VersionedLocation::V4(beneficiary.clone())),
1
					Box::new(VersionedAssets::V4(asset.clone().into())),
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(2)
1
			));
			// Now transferring does not fail
1
			assert_ok!(PolkadotXcm::transfer_assets(
1
				origin_of(AccountId::from(ALICE)),
1
				Box::new(xcm::VersionedLocation::V4(chain_part)),
1
				Box::new(xcm::VersionedLocation::V4(beneficiary)),
1
				Box::new(VersionedAssets::V4(asset.clone().into())),
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(3338)
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(3338)
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(24684)
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(3338)
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(15573)
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(29947)
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(3338)
1
				.expect_no_logs()
1
				.execute_returns(U256::from(400 * MOVR));
1
		});
1
}
#[test]
1
fn xtokens_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_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(2)
1
		.build()
1
		.execute_with(|| {
1
			let xtokens_precompile_address = H160::from_low_u64_be(2052);
1

            
1
			// We have the assetId that corresponds to the relay chain registered
1
			let relay_asset_id: moonriver_runtime::AssetId =
1
				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
			// 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
			// We use the address of the asset as an identifier of the asset we want to transferS
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					xtokens_precompile_address,
1
					XtokensPCall::transfer {
1
						currency_address: Address(asset_precompile_address.into()),
1
						amount: 500_000_000_000_000u128.into(),
1
						destination,
1
						weight: 4_000_000,
1
					},
1
				)
1
				.expect_cost(24691)
1
				.expect_no_logs()
1
				.execute_returns(())
1
		})
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(2)
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(24691)
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::V4(dest.clone())),
1
					beneficiary: Box::new(VersionedLocation::V4(dest)),
1
					assets: Box::new(VersionedAssets::V4(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::V4(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::V4(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(xcm::VersionedLocation::V4(
1
							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(2)
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(23275)
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(2)
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(2)
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::V4(chain_part)),
1
				Box::new(VersionedLocation::V4(beneficiary)),
1
				Box::new(VersionedAssets::V4(vec![asset_fee, asset].into())),
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(1669)
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(1669)
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(1669)
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::<()>::V4(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(0)
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(1669)
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, 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");
		}
1
	})
1
}
#[test]
1
fn deal_with_fees_handles_tip() {
1
	use frame_support::traits::OnUnbalanced;
1
	use moonriver_runtime::{DealWithFees, Treasury};
1

            
1
	ExtBuilder::default().build().execute_with(|| {
1
		// This test checks the functionality of the `DealWithFees` trait implementation in the runtime.
1
		// It simulates a scenario where a fee and a tip are issued to an account and ensures that the
1
		// treasury receives the correct amount (20% of the total), and the rest is burned (80%).
1
		//
1
		// The test follows these steps:
1
		// 1. It issues a fee of 100 and a tip of 1000.
1
		// 2. It checks the total supply before the fee and tip are dealt with, which should be 1_100.
1
		// 3. It checks that the treasury's balance is initially 0.
1
		// 4. It calls `DealWithFees::on_unbalanceds` with the fee and tip.
1
		// 5. It checks that the treasury's balance is now 220 (20% of the fee and tip).
1
		// 6. It checks that the total supply has decreased by 880 (80% of the fee and tip), indicating
1
		//    that this amount was burned.
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
		let total_supply_before = Balances::total_issuance();
1
		assert_eq!(total_supply_before, 1_100);
1
		assert_eq!(Balances::free_balance(&Treasury::account_id()), 0);
1
		DealWithFees::on_unbalanceds(vec![fee, tip].into_iter());
1

            
1
		// treasury should have received 20%
1
		assert_eq!(Balances::free_balance(&Treasury::account_id()), 220);
		// verify 80% burned
1
		let total_supply_after = Balances::total_issuance();
1
		assert_eq!(total_supply_before - total_supply_after, 880);
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 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;
1
		type WeightToFeeImpl = ConstantMultiplier<u128, ConstU128<{ currency::WEIGHT_FEE }>>;
1
		type LengthToFeeImpl = LengthToFee;
1

            
1
		// 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
					weight: extrinsic_weight,
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(
1
					(currency::WEIGHT_FEE * 4).saturating_mul(WEIGHT_PER_GAS as u128),
1
				)
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() {
1
		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 =
1
				(currency::WEIGHT_FEE * 4).saturating_mul(WEIGHT_PER_GAS as u128);
12
			let sim = |start_gas_price: u128, fullness: Perbill, num_blocks: u64| -> U256 {
12
				let start_multiplier =
12
					FixedU128::from_rational(start_gas_price, weight_fee_per_gas);
12
				pallet_transaction_payment::NextFeeMultiplier::<Runtime>::set(start_multiplier);
12

            
12
				let block_weight = NORMAL_WEIGHT * fullness;
60004
				for i in 0..num_blocks {
60004
					System::set_block_number(i as u32);
60004
					System::set_block_consumed_resources(block_weight, 0);
60004
					TransactionPayment::on_finalize(i as u32);
60004
				}
12
				TransactionPaymentAsGasPrice::min_gas_price().0
12
			};
			// The expected values are the ones observed during test execution,
			// they are expected to change when parameters that influence
			// the fee calculation are changed, and should be updated accordingly.
			// If a test fails when nothing specific to fees has changed,
			// it may indicate an unexpected collateral effect and should be investigated
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(0), 1),
1
				U256::from(1_250_000_000u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(25), 1),
1
				U256::from(1_250_000_000u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(50), 1),
1
				U256::from(1_250_750_225u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(100), 1),
1
				U256::from(1_253_254_225u128),
1
			);
			// 1 "real" hour (at 6-second blocks)
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(0), 600),
1
				U256::from(1_250_000_000u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(25), 600),
1
				U256::from(1_250_000_000u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(50), 600),
1
				U256::from(1_791_661_729u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(100), 600),
1
				U256::from(5_948_516_121u128),
1
			);
			// 1 "real" day (at 6-second blocks)
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(0), 14400),
1
				U256::from(1_250_000_000u128), // lower bound enforced
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(25), 14400),
1
				U256::from(1_250_000_000u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(50), 14400),
1
				U256::from(7_066_658_618_836u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(100), 14400),
1
				U256::from(125_000_000_000_000u128), // upper bound enforced
1
			);
1
		});
1
	}
}