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

            
19
mod common;
20
use common::*;
21

            
22
use precompile_utils::{
23
	precompile_set::{is_precompile_or_fail, IsActivePrecompile},
24
	prelude::*,
25
	testing::*,
26
};
27

            
28
use fp_evm::{Context, IsPrecompileResult};
29
use frame_support::{
30
	assert_noop, assert_ok,
31
	dispatch::DispatchClass,
32
	traits::{
33
		fungible::Inspect, Currency as CurrencyT, EnsureOrigin, OnInitialize, PalletInfo,
34
		StorageInfo, StorageInfoTrait,
35
	},
36
	weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
37
	StorageHasher, Twox128,
38
};
39
use moonbase_runtime::{
40
	//asset_config::ForeignAssetInstance,
41
	xcm_config::SelfReserve,
42
	AccountId,
43
	AssetId,
44
	Balances,
45
	CrowdloanRewards,
46
	EvmForeignAssets,
47
	Executive,
48
	OpenTechCommitteeCollective,
49
	ParachainStaking,
50
	PolkadotXcm,
51
	Precompiles,
52
	Runtime,
53
	RuntimeBlockWeights,
54
	RuntimeCall,
55
	RuntimeEvent,
56
	System,
57
	TransactionPayment,
58
	TransactionPaymentAsGasPrice,
59
	Treasury,
60
	TreasuryCouncilCollective,
61
	XcmTransactor,
62
	FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
63
	WEEKS,
64
};
65
use polkadot_parachain::primitives::Sibling;
66
use precompile_utils::testing::MockHandle;
67
use sp_runtime::{
68
	traits::{Convert as XcmConvert, Dispatchable},
69
	BuildStorage,
70
};
71
use std::str::from_utf8;
72
use xcm_builder::{ParentIsPreset, SiblingParachainConvertsVia};
73
use xcm_executor::traits::ConvertLocation;
74

            
75
use moonbase_runtime::currency::{GIGAWEI, WEI};
76
use moonbeam_xcm_benchmarks::weights::XcmWeight;
77
use moonkit_xcm_primitives::AccountIdAssetIdConversion;
78
use nimbus_primitives::NimbusId;
79
use pallet_evm::PrecompileSet;
80
//use pallet_evm_precompileset_assets_erc20::{SELECTOR_LOG_APPROVAL, SELECTOR_LOG_TRANSFER};
81
use moonbase_runtime::runtime_params::dynamic_params;
82
use pallet_moonbeam_foreign_assets::AssetStatus;
83
use pallet_transaction_payment::Multiplier;
84
use pallet_xcm_transactor::{Currency, CurrencyPayment, HrmpOperation, TransactWeights};
85
use parity_scale_codec::Encode;
86
use sha3::{Digest, Keccak256};
87
use sp_core::{crypto::UncheckedFrom, ByteArray, Get, Pair, H160, H256, U256};
88
use sp_runtime::{bounded_vec, DispatchError, ModuleError};
89
use std::cell::Cell;
90
use std::rc::Rc;
91
use xcm::{latest::prelude::*, VersionedAssets, VersionedLocation};
92

            
93
type AuthorMappingPCall =
94
	pallet_evm_precompile_author_mapping::AuthorMappingPrecompileCall<Runtime>;
95
type BatchPCall = pallet_evm_precompile_batch::BatchPrecompileCall<Runtime>;
96
type CrowdloanRewardsPCall =
97
	pallet_evm_precompile_crowdloan_rewards::CrowdloanRewardsPrecompileCall<Runtime>;
98
type XcmUtilsPCall = pallet_evm_precompile_xcm_utils::XcmUtilsPrecompileCall<
99
	Runtime,
100
	moonbase_runtime::xcm_config::XcmExecutorConfig,
101
>;
102
type XtokensPCall = pallet_evm_precompile_xtokens::XtokensPrecompileCall<Runtime>;
103
/*type ForeignAssetsPCall = pallet_evm_precompileset_assets_erc20::Erc20AssetsPrecompileSetCall<
104
	Runtime,
105
	ForeignAssetInstance,
106
>;*/
107
type XcmTransactorV1PCall =
108
	pallet_evm_precompile_xcm_transactor::v1::XcmTransactorPrecompileV1Call<Runtime>;
109
type XcmTransactorV2PCall =
110
	pallet_evm_precompile_xcm_transactor::v2::XcmTransactorPrecompileV2Call<Runtime>;
111

            
112
// TODO: can we construct a const U256...?
113
const BASE_FEE_GENISIS: u128 = 10 * GIGAWEI / 4;
114

            
115
#[test]
116
1
fn xcmp_queue_controller_origin_is_root() {
117
1
	// important for the XcmExecutionManager impl of PauseExecution which uses root origin
118
1
	// to suspend/resume XCM execution in xcmp_queue::on_idle
119
1
	assert_ok!(
120
1
		<moonbase_runtime::Runtime as cumulus_pallet_xcmp_queue::Config
121
1
		>::ControllerOrigin::ensure_origin(root_origin())
122
1
	);
123
1
}
124

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

            
175
13
	let prefix = |pallet_name, storage_name| {
176
13
		let mut res = [0u8; 32];
177
13
		res[0..16].copy_from_slice(&Twox128::hash(pallet_name));
178
13
		res[16..32].copy_from_slice(&Twox128::hash(storage_name));
179
13
		res.to_vec()
180
13
	};
181
1
	assert_eq!(
182
1
		<moonbase_runtime::Balances as StorageInfoTrait>::storage_info(),
183
1
		vec![
184
1
			StorageInfo {
185
1
				pallet_name: b"Balances".to_vec(),
186
1
				storage_name: b"TotalIssuance".to_vec(),
187
1
				prefix: prefix(b"Balances", b"TotalIssuance"),
188
1
				max_values: Some(1),
189
1
				max_size: Some(16),
190
1
			},
191
1
			StorageInfo {
192
1
				pallet_name: b"Balances".to_vec(),
193
1
				storage_name: b"InactiveIssuance".to_vec(),
194
1
				prefix: prefix(b"Balances", b"InactiveIssuance"),
195
1
				max_values: Some(1),
196
1
				max_size: Some(16),
197
1
			},
198
1
			StorageInfo {
199
1
				pallet_name: b"Balances".to_vec(),
200
1
				storage_name: b"Account".to_vec(),
201
1
				prefix: prefix(b"Balances", b"Account"),
202
1
				max_values: None,
203
1
				max_size: Some(100),
204
1
			},
205
1
			StorageInfo {
206
1
				pallet_name: b"Balances".to_vec(),
207
1
				storage_name: b"Locks".to_vec(),
208
1
				prefix: prefix(b"Balances", b"Locks"),
209
1
				max_values: None,
210
1
				max_size: Some(1287),
211
1
			},
212
1
			StorageInfo {
213
1
				pallet_name: b"Balances".to_vec(),
214
1
				storage_name: b"Reserves".to_vec(),
215
1
				prefix: prefix(b"Balances", b"Reserves"),
216
1
				max_values: None,
217
1
				max_size: Some(1037),
218
1
			},
219
1
			StorageInfo {
220
1
				pallet_name: b"Balances".to_vec(),
221
1
				storage_name: b"Holds".to_vec(),
222
1
				prefix: prefix(b"Balances", b"Holds"),
223
1
				max_values: None,
224
1
				max_size: Some(55),
225
1
			},
226
1
			StorageInfo {
227
1
				pallet_name: b"Balances".to_vec(),
228
1
				storage_name: b"Freezes".to_vec(),
229
1
				prefix: prefix(b"Balances", b"Freezes"),
230
1
				max_values: None,
231
1
				max_size: Some(37),
232
1
			},
233
1
		]
234
1
	);
235
1
	assert_eq!(
236
1
		<moonbase_runtime::Sudo as StorageInfoTrait>::storage_info(),
237
1
		vec![StorageInfo {
238
1
			pallet_name: b"Sudo".to_vec(),
239
1
			storage_name: b"Key".to_vec(),
240
1
			prefix: prefix(b"Sudo", b"Key"),
241
1
			max_values: Some(1),
242
1
			max_size: Some(20),
243
1
		}]
244
1
	);
245
1
	assert_eq!(
246
1
		<moonbase_runtime::Proxy as StorageInfoTrait>::storage_info(),
247
1
		vec![
248
1
			StorageInfo {
249
1
				pallet_name: b"Proxy".to_vec(),
250
1
				storage_name: b"Proxies".to_vec(),
251
1
				prefix: prefix(b"Proxy", b"Proxies"),
252
1
				max_values: None,
253
1
				max_size: Some(845),
254
1
			},
255
1
			StorageInfo {
256
1
				pallet_name: b"Proxy".to_vec(),
257
1
				storage_name: b"Announcements".to_vec(),
258
1
				prefix: prefix(b"Proxy", b"Announcements"),
259
1
				max_values: None,
260
1
				max_size: Some(1837),
261
1
			}
262
1
		]
263
1
	);
264
1
	assert_eq!(
265
1
		<moonbase_runtime::MaintenanceMode as StorageInfoTrait>::storage_info(),
266
1
		vec![StorageInfo {
267
1
			pallet_name: b"MaintenanceMode".to_vec(),
268
1
			storage_name: b"MaintenanceMode".to_vec(),
269
1
			prefix: prefix(b"MaintenanceMode", b"MaintenanceMode"),
270
1
			max_values: Some(1),
271
1
			max_size: None,
272
1
		},]
273
1
	);
274

            
275
1
	assert_eq!(
276
1
		<moonbase_runtime::RelayStorageRoots as StorageInfoTrait>::storage_info(),
277
1
		vec![
278
1
			StorageInfo {
279
1
				pallet_name: b"RelayStorageRoots".to_vec(),
280
1
				storage_name: b"RelayStorageRoot".to_vec(),
281
1
				prefix: prefix(b"RelayStorageRoots", b"RelayStorageRoot"),
282
1
				max_values: None,
283
1
				max_size: Some(44),
284
1
			},
285
1
			StorageInfo {
286
1
				pallet_name: b"RelayStorageRoots".to_vec(),
287
1
				storage_name: b"RelayStorageRootKeys".to_vec(),
288
1
				prefix: prefix(b"RelayStorageRoots", b"RelayStorageRootKeys"),
289
1
				max_values: Some(1),
290
1
				max_size: Some(121),
291
1
			},
292
1
		]
293
1
	);
294
1
}
295

            
296
#[test]
297
1
fn test_collectives_storage_item_prefixes() {
298
6
	for StorageInfo { pallet_name, .. } in
299
7
		<moonbase_runtime::TreasuryCouncilCollective as StorageInfoTrait>::storage_info()
300
	{
301
6
		assert_eq!(pallet_name, b"TreasuryCouncilCollective".to_vec());
302
	}
303

            
304
6
	for StorageInfo { pallet_name, .. } in
305
7
		<moonbase_runtime::OpenTechCommitteeCollective as StorageInfoTrait>::storage_info()
306
	{
307
6
		assert_eq!(pallet_name, b"OpenTechCommitteeCollective".to_vec());
308
	}
309
1
}
310

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

            
331
#[test]
332
1
fn collective_set_members_general_admin_origin_works() {
333
1
	use moonbase_runtime::{
334
1
		governance::custom_origins::Origin as CustomOrigin, OriginCaller, Utility,
335
1
	};
336
1

            
337
1
	ExtBuilder::default().build().execute_with(|| {
338
1
		let root_caller = <Runtime as frame_system::Config>::RuntimeOrigin::root();
339
1
		let alice = AccountId::from(ALICE);
340
1

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

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

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

            
411
#[test]
412
1
fn verify_pallet_indices() {
413
34
	fn is_pallet_index<P: 'static>(index: usize) {
414
34
		assert_eq!(
415
34
			<moonbase_runtime::Runtime as frame_system::Config>::PalletInfo::index::<P>(),
416
34
			Some(index)
417
34
		);
418
34
	}
419
1
	is_pallet_index::<moonbase_runtime::System>(0);
420
1
	is_pallet_index::<moonbase_runtime::Utility>(1);
421
1
	is_pallet_index::<moonbase_runtime::Balances>(3);
422
1
	is_pallet_index::<moonbase_runtime::Sudo>(4);
423
1
	is_pallet_index::<moonbase_runtime::ParachainSystem>(6);
424
1
	is_pallet_index::<moonbase_runtime::TransactionPayment>(7);
425
1
	is_pallet_index::<moonbase_runtime::ParachainInfo>(8);
426
1
	is_pallet_index::<moonbase_runtime::EthereumChainId>(9);
427
1
	is_pallet_index::<moonbase_runtime::EVM>(10);
428
1
	is_pallet_index::<moonbase_runtime::Ethereum>(11);
429
1
	is_pallet_index::<moonbase_runtime::ParachainStaking>(12);
430
1
	is_pallet_index::<moonbase_runtime::Scheduler>(13);
431
1
	//is_pallet_index::<moonbase_runtime::Democracy>(14); Removed
432
1
	is_pallet_index::<moonbase_runtime::Treasury>(17);
433
1
	is_pallet_index::<moonbase_runtime::AuthorInherent>(18);
434
1
	is_pallet_index::<moonbase_runtime::AuthorFilter>(19);
435
1
	is_pallet_index::<moonbase_runtime::CrowdloanRewards>(20);
436
1
	is_pallet_index::<moonbase_runtime::AuthorMapping>(21);
437
1
	is_pallet_index::<moonbase_runtime::Proxy>(22);
438
1
	is_pallet_index::<moonbase_runtime::MaintenanceMode>(23);
439
1
	is_pallet_index::<moonbase_runtime::Identity>(24);
440
1
	is_pallet_index::<moonbase_runtime::XcmpQueue>(25);
441
1
	is_pallet_index::<moonbase_runtime::CumulusXcm>(26);
442
1
	is_pallet_index::<moonbase_runtime::PolkadotXcm>(28);
443
1
	is_pallet_index::<moonbase_runtime::Assets>(29);
444
1
	// is_pallet_index::<moonbase_runtime::XTokens>(30); Removed
445
1
	is_pallet_index::<moonbase_runtime::AssetManager>(31);
446
1
	is_pallet_index::<moonbase_runtime::Migrations>(32);
447
1
	is_pallet_index::<moonbase_runtime::XcmTransactor>(33);
448
1
	is_pallet_index::<moonbase_runtime::ProxyGenesisCompanion>(34);
449
1
	is_pallet_index::<moonbase_runtime::MoonbeamOrbiters>(37);
450
1
	is_pallet_index::<moonbase_runtime::EthereumXcm>(38);
451
1
	is_pallet_index::<moonbase_runtime::Randomness>(39);
452
1
	is_pallet_index::<moonbase_runtime::TreasuryCouncilCollective>(40);
453
1
	is_pallet_index::<moonbase_runtime::OpenTechCommitteeCollective>(46);
454
1
	is_pallet_index::<moonbase_runtime::MoonbeamLazyMigrations>(51);
455
1
}
456

            
457
#[test]
458
1
fn verify_reserved_indices() {
459
1
	use frame_metadata::*;
460
1

            
461
1
	let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
462
1
		.build_storage()
463
1
		.unwrap()
464
1
		.into();
465
1

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

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

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

            
557
#[test]
558
1
fn transfer_through_evm_to_stake() {
559
1
	ExtBuilder::default()
560
1
		.with_balances(vec![(AccountId::from(ALICE), 2_000 * UNIT)])
561
1
		.build()
562
1
		.execute_with(|| {
563
1
			// Charlie has no balance => fails to stake
564
1
			assert_noop!(
565
1
				ParachainStaking::join_candidates(
566
1
					origin_of(AccountId::from(CHARLIE)),
567
1
					1_000 * UNIT,
568
1
					0u32
569
1
				),
570
1
				DispatchError::Module(ModuleError {
571
1
					index: 12,
572
1
					error: [8, 0, 0, 0],
573
1
					message: Some("InsufficientBalance")
574
1
				})
575
1
			);
576

            
577
			// Alice transfer from free balance 2000 UNIT to Bob
578
1
			assert_ok!(Balances::transfer_allow_death(
579
1
				origin_of(AccountId::from(ALICE)),
580
1
				AccountId::from(BOB),
581
1
				2_000 * UNIT,
582
1
			));
583
1
			assert_eq!(Balances::free_balance(AccountId::from(BOB)), 2_000 * UNIT);
584

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

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

            
616
#[test]
617
1
fn reward_block_authors() {
618
1
	ExtBuilder::default()
619
1
		.with_balances(vec![
620
1
			// Alice gets 100 extra tokens for her mapping deposit
621
1
			(AccountId::from(ALICE), 2_100 * UNIT),
622
1
			(AccountId::from(BOB), 1_000 * UNIT),
623
1
		])
624
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * UNIT)])
625
1
		.with_delegations(vec![(
626
1
			AccountId::from(BOB),
627
1
			AccountId::from(ALICE),
628
1
			500 * UNIT,
629
1
		)])
630
1
		.with_mappings(vec![(
631
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
632
1
			AccountId::from(ALICE),
633
1
		)])
634
1
		.build()
635
1
		.execute_with(|| {
636
1
			increase_last_relay_slot_number(1);
637
1
			// Just before round 3
638
1
			run_to_block(2399, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
639
1
			// no rewards doled out yet
640
1
			assert_eq!(
641
1
				Balances::usable_balance(AccountId::from(ALICE)),
642
1
				1_100 * UNIT,
643
1
			);
644
1
			assert_eq!(Balances::usable_balance(AccountId::from(BOB)), 500 * UNIT,);
645
1
			run_to_block(2401, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
646
1
			// rewards minted and distributed
647
1
			assert_eq!(
648
1
				Balances::usable_balance(AccountId::from(ALICE)),
649
1
				1213666666584000000000,
650
1
			);
651
1
			assert_eq!(
652
1
				Balances::usable_balance(AccountId::from(BOB)),
653
1
				541333333292000000000,
654
1
			);
655
1
		});
656
1
}
657

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

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

            
688
1
			// no rewards doled out yet
689
1
			assert_eq!(
690
1
				Balances::usable_balance(AccountId::from(ALICE)),
691
1
				1_100 * UNIT,
692
1
			);
693
1
			assert_eq!(Balances::usable_balance(AccountId::from(BOB)), 500 * UNIT,);
694
1
			assert_eq!(Balances::usable_balance(AccountId::from(CHARLIE)), UNIT,);
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
				47515000000000000000,
703
1
			);
704

            
705
			// Go to round 3
706
1
			run_to_block(2401, Some(NimbusId::from_slice(&ALICE_NIMBUS).unwrap()));
707
1
			// rewards minted and distributed
708
1
			assert_eq!(
709
1
				Balances::usable_balance(AccountId::from(ALICE)),
710
1
				1182693333281650000000,
711
1
			);
712
1
			assert_eq!(
713
1
				Balances::usable_balance(AccountId::from(BOB)),
714
1
				525841666640825000000,
715
1
			);
716
			// 30% again reserved for parachain bond
717
1
			assert_eq!(
718
1
				Balances::usable_balance(AccountId::from(CHARLIE)),
719
1
				94727725000000000000,
720
1
			);
721
1
		});
722
1
}
723

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

            
805
1
			let vesting_period = 4 * WEEKS as u128;
806
1
			let per_block = (1_050_000 * UNIT) / vesting_period;
807
1

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

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

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

            
859
1
			let public1 = pair1.public();
860
1
			let public2 = pair2.public();
861
1

            
862
1
			// signature:
863
1
			// WRAP_BYTES|| NetworkIdentifier|| new_account || previous_account || WRAP_BYTES
864
1
			let mut message = pallet_crowdloan_rewards::WRAPPED_BYTES_PREFIX.to_vec();
865
1
			message.append(&mut b"moonbase-".to_vec());
866
1
			message.append(&mut AccountId::from(DAVE).encode());
867
1
			message.append(&mut AccountId::from(CHARLIE).encode());
868
1
			message.append(&mut pallet_crowdloan_rewards::WRAPPED_BYTES_POSTFIX.to_vec());
869
1

            
870
1
			let signature1 = pair1.sign(&message);
871
1
			let signature2 = pair2.sign(&message);
872
1

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

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

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

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

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

            
991
			// 30 percent initial payout
992
1
			assert_eq!(Balances::balance(&AccountId::from(CHARLIE)), 450_000 * UNIT);
993
			// 30 percent initial payout
994
1
			assert_eq!(Balances::balance(&AccountId::from(DAVE)), 450_000 * UNIT);
995

            
996
1
			let crowdloan_precompile_address = H160::from_low_u64_be(2049);
997
1

            
998
1
			// Alice uses the crowdloan precompile to claim through the EVM
999
1
			let gas_limit = 100000u64;
1
			let gas_price: U256 = BASE_FEE_GENISIS.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 * UNIT) / vesting_period;
1

            
1
			assert_eq!(
1
				CrowdloanRewards::accounts_payable(&AccountId::from(CHARLIE))
1
					.unwrap()
1
					.claimed_reward,
1
				(450_000 * UNIT) + 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 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * UNIT)])
1
		.with_mappings(vec![(
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
1
			AccountId::from(ALICE),
1
		)])
1
		.with_crowdloan_fund(3_000_000 * UNIT)
1
		.build()
1
		.execute_with(|| {
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 * UNIT
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 * UNIT
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(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(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 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * UNIT)])
1
		.with_mappings(vec![(
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
1
			AccountId::from(ALICE),
1
		)])
1
		.with_crowdloan_fund(3_000_000 * UNIT)
1
		.build()
1
		.execute_with(|| {
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 * UNIT
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 * UNIT
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 * UNIT).into();
1
			let expected_claimed: U256 = (450_000 * UNIT).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 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_collators(vec![(AccountId::from(ALICE), 1_000 * UNIT)])
1
		.with_mappings(vec![(
1
			NimbusId::from_slice(&ALICE_NIMBUS).unwrap(),
1
			AccountId::from(ALICE),
1
		)])
1
		.with_crowdloan_fund(3_000_000 * UNIT)
1
		.build()
1
		.execute_with(|| {
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 * UNIT
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 * UNIT
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_GENISIS.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 * UNIT)
1
			);
1
		})
1
}
#[test]
1
fn create_and_manipulate_foreign_asset() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		let source_location = xcm::v4::Location::parent();
1

            
1
		// Create foreign asset
1
		assert_ok!(EvmForeignAssets::create_foreign_asset(
1
			moonbase_runtime::RuntimeOrigin::root(),
1
			1,
1
			source_location.clone(),
1
			12,
1
			bounded_vec![b'M', b'T'],
1
			bounded_vec![b'M', b'y', b'T', b'o', b'k'],
1
		));
1
		assert_eq!(
1
			EvmForeignAssets::assets_by_id(1),
1
			Some(source_location.clone())
1
		);
1
		assert_eq!(
1
			EvmForeignAssets::assets_by_location(&source_location),
1
			Some((1, AssetStatus::Active))
1
		);
		// Freeze foreign asset
1
		assert_ok!(EvmForeignAssets::freeze_foreign_asset(
1
			moonbase_runtime::RuntimeOrigin::root(),
1
			1,
1
			true
1
		));
1
		assert_eq!(
1
			EvmForeignAssets::assets_by_location(&source_location),
1
			Some((1, AssetStatus::FrozenXcmDepositAllowed))
1
		);
		// Unfreeze foreign asset
1
		assert_ok!(EvmForeignAssets::unfreeze_foreign_asset(
1
			moonbase_runtime::RuntimeOrigin::root(),
1
			1,
1
		));
1
		assert_eq!(
1
			EvmForeignAssets::assets_by_location(&source_location),
1
			Some((1, AssetStatus::Active))
1
		);
1
	});
1
}
// The precoompile asset-erc20 is deprecated and not used anymore for new evm foreign assets
// We don't have testing tools in rust test to call real evm smart contract, so we rely on ts tests.
/*
#[test]
fn xcm_asset_erc20_precompiles_supply_and_balance() {
	ExtBuilder::default()
		.with_xcm_assets(vec![XcmAssetInitialization {
			asset_id: 1,
			xcm_location: xcm::v4::Location::parent(),
			name: "RelayToken",
			symbol: "Relay",
			decimals: 12,
			balances: vec![(AccountId::from(ALICE), 1_000 * UNIT)],
		}])
		.with_balances(vec![
			(AccountId::from(ALICE), 2_000 * UNIT),
			(AccountId::from(BOB), 1_000 * UNIT),
		])
		.build()
		.execute_with(|| {
			// We have the assetId that corresponds to the relay chain registered
			let relay_asset_id: AssetId = AssetType::Xcm(xcm::v3::Location::parent()).into();
			// Its address is
			let asset_precompile_address = Runtime::asset_id_to_account(
				FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
				relay_asset_id,
			);
			// Assert the asset has been created with the correct supply
			assert_eq!(Assets::total_supply(relay_asset_id), 1_000 * UNIT);
			// Access totalSupply through precompile. Important that the context is correct
			Precompiles::new()
				.prepare_test(
					ALICE,
					asset_precompile_address,
					ForeignAssetsPCall::total_supply {},
				)
				.expect_cost(3338)
				.expect_no_logs()
				.execute_returns(U256::from(1000 * UNIT));
			// Access balanceOf through precompile
			Precompiles::new()
				.prepare_test(
					ALICE,
					asset_precompile_address,
					ForeignAssetsPCall::balance_of {
						who: Address(ALICE.into()),
					},
				)
				.expect_cost(3338)
				.expect_no_logs()
				.execute_returns(U256::from(1000 * UNIT));
		});
}
#[test]
fn xcm_asset_erc20_precompiles_transfer() {
	ExtBuilder::default()
		.with_xcm_assets(vec![XcmAssetInitialization {
			asset_id: 1,
			xcm_location: xcm::v4::Location::parent(),
			name: "RelayToken",
			symbol: "Relay",
			decimals: 12,
			balances: vec![(AccountId::from(ALICE), 1_000 * UNIT)],
		}])
		.with_balances(vec![
			(AccountId::from(ALICE), 2_000 * UNIT),
			(AccountId::from(BOB), 1_000 * UNIT),
		])
		.build()
		.execute_with(|| {
			// We have the assetId that corresponds to the relay chain registered
			let relay_asset_id: AssetId = AssetType::Xcm(xcm::v3::Location::parent()).into();
			// Its address is
			let asset_precompile_address = Runtime::asset_id_to_account(
				FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
				relay_asset_id,
			);
			// Transfer tokens from Alice to Bob, 400 UNIT.
			Precompiles::new()
				.prepare_test(
					ALICE,
					asset_precompile_address,
					ForeignAssetsPCall::transfer {
						to: Address(BOB.into()),
						value: { 400 * UNIT }.into(),
					},
				)
				.expect_cost(24695)
				.expect_log(log3(
					asset_precompile_address,
					SELECTOR_LOG_TRANSFER,
					H160::from(ALICE),
					H160::from(BOB),
					solidity::encode_event_data(U256::from(400 * UNIT)),
				))
				.execute_returns(true);
			// Make sure BOB has 400 UNIT
			Precompiles::new()
				.prepare_test(
					BOB,
					asset_precompile_address,
					ForeignAssetsPCall::balance_of {
						who: Address(BOB.into()),
					},
				)
				.expect_cost(3338)
				.expect_no_logs()
				.execute_returns(U256::from(400 * UNIT));
		});
}
#[test]
fn xcm_asset_erc20_precompiles_approve() {
	ExtBuilder::default()
		.with_xcm_assets(vec![XcmAssetInitialization {
			asset_id: 1,
			xcm_location: xcm::v4::Location::parent(),
			name: "RelayToken",
			symbol: "Relay",
			decimals: 12,
			balances: vec![(AccountId::from(ALICE), 1_000 * UNIT)],
		}])
		.with_balances(vec![
			(AccountId::from(ALICE), 2_000 * UNIT),
			(AccountId::from(BOB), 1_000 * UNIT),
		])
		.build()
		.execute_with(|| {
			// We have the assetId that corresponds to the relay chain registered
			let relay_asset_id: AssetId = AssetType::Xcm(xcm::v3::Location::parent()).into();
			// Its address is
			let asset_precompile_address = Runtime::asset_id_to_account(
				FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
				relay_asset_id,
			);
			// Aprove Bob for spending 400 UNIT from Alice
			Precompiles::new()
				.prepare_test(
					ALICE,
					asset_precompile_address,
					ForeignAssetsPCall::approve {
						spender: Address(BOB.into()),
						value: { 400 * UNIT }.into(),
					},
				)
				.expect_cost(15604)
				.expect_log(log3(
					asset_precompile_address,
					SELECTOR_LOG_APPROVAL,
					H160::from(ALICE),
					H160::from(BOB),
					solidity::encode_event_data(U256::from(400 * UNIT)),
				))
				.execute_returns(true);
			// Transfer tokens from Alice to Charlie by using BOB as origin
			Precompiles::new()
				.prepare_test(
					BOB,
					asset_precompile_address,
					ForeignAssetsPCall::transfer_from {
						from: Address(ALICE.into()),
						to: Address(CHARLIE.into()),
						value: { 400 * UNIT }.into(),
					},
				)
				.expect_cost(29960)
				.expect_log(log3(
					asset_precompile_address,
					SELECTOR_LOG_TRANSFER,
					H160::from(ALICE),
					H160::from(CHARLIE),
					solidity::encode_event_data(U256::from(400 * UNIT)),
				))
				.execute_returns(true);
			// Make sure CHARLIE has 400 UNIT
			Precompiles::new()
				.prepare_test(
					CHARLIE,
					asset_precompile_address,
					ForeignAssetsPCall::balance_of {
						who: Address(CHARLIE.into()),
					},
				)
				.expect_cost(3338)
				.expect_no_logs()
				.execute_returns(U256::from(400 * UNIT));
		});
}*/
#[test]
1
fn xtokens_precompiles_transfer() {
1
	ExtBuilder::default()
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_id: 1,
1
			xcm_location: xcm::v4::Location::parent(),
1
			name: "RelayToken",
1
			symbol: "Relay",
1
			decimals: 12,
1
			balances: vec![(AccountId::from(ALICE), 1_000 * UNIT)],
1
		}])
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			let xtokens_precompile_address = H160::from_low_u64_be(2052);
1

            
1
			// We have the assetId that corresponds to the relay chain registered
1
			let relay_asset_id: AssetId = 1;
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
			let inside = Rc::new(Cell::new(false));
1
			let inside2 = inside.clone();
1

            
1
			// We use the address of the asset as an identifier of the asset we want to transfer
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(176605)
1
				.expect_no_logs()
1
				// We expect an evm subcall ERC20.burnFrom
1
				.with_subcall_handle(move |subcall| {
1
					let Subcall {
1
						address,
1
						transfer,
1
						input,
1
						target_gas: _,
1
						is_static,
1
						context,
1
					} = subcall;
1

            
1
					assert_eq!(context.caller, EvmForeignAssets::account_id().into());
1
					assert_eq!(
1
						address,
1
						[255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1].into()
1
					);
1
					assert_eq!(is_static, false);
1
					assert!(transfer.is_none());
1
					assert_eq!(
1
						context.address,
1
						[255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1].into()
1
					);
1
					assert_eq!(context.apparent_value, 0u8.into());
1
					assert_eq!(&input[..4], &keccak256!("burnFrom(address,uint256)")[..4]);
1
					assert_eq!(&input[4..16], &[0u8; 12]);
1
					assert_eq!(&input[16..36], ALICE);
1
					inside2.set(true);
1

            
1
					SubcallOutput {
1
						output: Default::default(),
1
						cost: 149_000,
1
						logs: vec![],
1
						..SubcallOutput::succeed()
1
					}
1
				})
1
				.execute_returns(())
1
		})
1
}
#[test]
1
fn xtokens_precompiles_transfer_multiasset() {
1
	ExtBuilder::default()
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_id: 1,
1
			xcm_location: xcm::v4::Location::parent(),
1
			name: "RelayToken",
1
			symbol: "Relay",
1
			decimals: 12,
1
			balances: vec![(AccountId::from(ALICE), 1_000 * UNIT)],
1
		}])
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			let xtokens_precompile_address = H160::from_low_u64_be(2052);
1

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

            
1
			let inside = Rc::new(Cell::new(false));
1
			let inside2 = inside.clone();
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(176605)
1
				.expect_no_logs()
1
				// We expect an evm subcall ERC20.burnFrom
1
				.with_subcall_handle(move |subcall| {
1
					let Subcall {
1
						address,
1
						transfer,
1
						input,
1
						target_gas: _,
1
						is_static,
1
						context,
1
					} = subcall;
1

            
1
					assert_eq!(context.caller, EvmForeignAssets::account_id().into());
1
					assert_eq!(
1
						address,
1
						[255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1].into()
1
					);
1
					assert_eq!(is_static, false);
1
					assert!(transfer.is_none());
1
					assert_eq!(
1
						context.address,
1
						[255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1].into()
1
					);
1
					assert_eq!(context.apparent_value, 0u8.into());
1
					assert_eq!(&input[..4], &keccak256!("burnFrom(address,uint256)")[..4]);
1
					assert_eq!(&input[4..16], &[0u8; 12]);
1
					assert_eq!(&input[16..36], ALICE);
1
					inside2.set(true);
1

            
1
					SubcallOutput {
1
						output: Default::default(),
1
						cost: 149_000,
1
						logs: vec![],
1
						..SubcallOutput::succeed()
1
					}
1
				})
1
				.execute_returns(());
1

            
1
			// Ensure that the subcall was actually called.
1
			assert!(inside.get(), "subcall not called");
1
		})
1
}
#[test]
1
fn xtokens_precompiles_transfer_native() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			let xtokens_precompile_address = H160::from_low_u64_be(2052);
1

            
1
			// Its address is
1
			let asset_precompile_address = H160::from_low_u64_be(2050);
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 transfer
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					xtokens_precompile_address,
1
					XtokensPCall::transfer {
1
						currency_address: Address(asset_precompile_address),
1
						amount: { 500 * UNIT }.into(),
1
						destination,
1
						weight: 4_000_000,
1
					},
1
				)
1
				.expect_cost(25005)
1
				.expect_no_logs()
1
				.execute_returns(());
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
			moonbase_runtime::TransactionPayment::query_fee_details(uxt.clone(), len)
9
				.inclusion_fee
9
				.expect("fee should be calculated")
9
				.len_fee
9
		};
		//                  left: cost of length fee, right: size in bytes
		//                             /------------- proportional component: O(N * 1B)
		//                             |           /- exponential component: O(N ** 3)
		//                             |           |
1
		assert_eq!(                    1_000_000_001, calc_fee(1));
1
		assert_eq!(                   10_000_001_000, calc_fee(10));
1
		assert_eq!(                  100_001_000_000, calc_fee(100));
1
		assert_eq!(                1_001_000_000_000, calc_fee(1_000));
1
		assert_eq!(               11_000_000_000_000, calc_fee(10_000)); // inflection point
1
		assert_eq!(            1_100_000_000_000_000, calc_fee(100_000));
1
		assert_eq!(        1_001_000_000_000_000_000, calc_fee(1_000_000)); // one UNIT, ~ 1MB
1
		assert_eq!(    1_000_010_000_000_000_000_000, calc_fee(10_000_000));
1
		assert_eq!(1_000_000_100_000_000_000_000_000, calc_fee(100_000_000));
1
	});
1
}
#[test]
1
fn multiplier_can_grow_from_zero() {
1
	use frame_support::traits::Get;
1

            
1
	let minimum_multiplier = moonbase_runtime::MinimumMultiplier::get();
1
	let target = moonbase_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 = moonbase_runtime::FastAdjustingFeeUpdate::<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 transfer_ed_0_substrate() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), (1 * UNIT) + (1 * WEI)),
1
			(AccountId::from(BOB), existential_deposit()),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			// Substrate transfer
1
			assert_ok!(Balances::transfer_allow_death(
1
				origin_of(AccountId::from(ALICE)),
1
				AccountId::from(BOB),
1
				1 * UNIT,
1
			));
			// 1 WEI is left in the account
1
			assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 1 * WEI);
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(8u128));
1
		assert_eq!(
1
			TransactionPaymentAsGasPrice::min_gas_price(),
1
			(
1
				2_500_000_000u128.into(),
1
				Weight::from_parts(41_742_000u64, 0)
1
			)
1
		);
1
	});
1
}
#[test]
1
fn transfer_ed_0_evm() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(
1
				AccountId::from(ALICE),
1
				((1 * UNIT) + (21_000 * BASE_FEE_GENISIS)) + (1 * WEI),
1
			),
1
			(AccountId::from(BOB), existential_deposit()),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			set_parachain_inherent_data();
1
			// EVM transfer
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
1
				source: H160::from(ALICE),
1
				target: H160::from(BOB),
1
				input: Vec::new(),
1
				value: (1 * UNIT).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: U256::from(BASE_FEE_GENISIS),
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 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 * UNIT) + (21_777 * BASE_FEE_GENISIS) + existential_deposit()),
1
			),
1
			(AccountId::from(BOB), existential_deposit()),
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 * UNIT).into(),
1
				gas_limit: 21_777u64,
1
				max_fee_per_gas: U256::from(BASE_FEE_GENISIS),
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()));
			// ALICE is refunded
1
			assert_eq!(
1
				Balances::free_balance(AccountId::from(ALICE)),
1
				777 * BASE_FEE_GENISIS + existential_deposit(),
1
			);
1
		});
1
}
#[test]
1
fn author_does_receive_priority_fee() {
1
	ExtBuilder::default()
1
		.with_balances(vec![(
1
			AccountId::from(BOB),
1
			(1 * UNIT) + (21_000 * (500 * GIGAWEI)),
1
		)])
1
		.build()
1
		.execute_with(|| {
1
			// Some block author as seen by pallet-evm.
1
			let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
1
			pallet_author_inherent::Author::<Runtime>::put(author);
1
			// Currently the default impl of the evm uses `deposit_into_existing`.
1
			// If we were to use this implementation, and for an author to receive eventual tips,
1
			// the account needs to be somehow initialized, otherwise the deposit would fail.
1
			Balances::make_free_balance_be(&author, 100 * UNIT);
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 * UNIT).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: U256::from(300 * GIGAWEI),
1
				max_priority_fee_per_gas: Some(U256::from(200 * GIGAWEI)),
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let priority_fee = 200 * GIGAWEI * 21_000;
1
			// Author free balance increased by priority fee.
1
			assert_eq!(Balances::free_balance(author), 100 * UNIT + priority_fee,);
1
		});
1
}
#[test]
1
fn total_issuance_after_evm_transaction_with_priority_fee() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(
1
				AccountId::from(BOB),
1
				(1 * UNIT) + (21_000 * (2 * BASE_FEE_GENISIS) + existential_deposit()),
1
			),
1
			(AccountId::from(ALICE), existential_deposit()),
1
			(
1
				<pallet_treasury::TreasuryAccountId<Runtime> as sp_core::TypedGet>::get(),
1
				existential_deposit(),
1
			),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			let issuance_before = <Runtime as pallet_evm::Config>::Currency::total_issuance();
1
			let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
1
			pallet_author_inherent::Author::<Runtime>::put(author);
1
			// EVM transfer.
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
1
				source: H160::from(BOB),
1
				target: H160::from(ALICE),
1
				input: Vec::new(),
1
				value: (1 * UNIT).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: U256::from(2 * BASE_FEE_GENISIS),
1
				max_priority_fee_per_gas: Some(U256::from(BASE_FEE_GENISIS)),
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let issuance_after = <Runtime as pallet_evm::Config>::Currency::total_issuance();
1

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

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

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

            
1
			assert_eq!(issuance_after, issuance_before - burnt_base_fee_part);
1
			assert_eq!(moonbase_runtime::Treasury::pot(), treasury_base_fee_part);
1
		});
1
}
#[test]
1
fn total_issuance_after_evm_transaction_without_priority_fee() {
1
	use fp_evm::FeeCalculator;
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(
1
				AccountId::from(BOB),
1
				(1 * UNIT) + (21_000 * (2 * BASE_FEE_GENISIS)),
1
			),
1
			(AccountId::from(ALICE), existential_deposit()),
1
			(
1
				<pallet_treasury::TreasuryAccountId<Runtime> as sp_core::TypedGet>::get(),
1
				existential_deposit(),
1
			),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			set_parachain_inherent_data();
1
			let issuance_before = <Runtime as pallet_evm::Config>::Currency::total_issuance();
1
			// EVM transfer.
1
			assert_ok!(RuntimeCall::EVM(pallet_evm::Call::<Runtime>::call {
1
				source: H160::from(BOB),
1
				target: H160::from(ALICE),
1
				input: Vec::new(),
1
				value: (1 * UNIT).into(),
1
				gas_limit: 21_000u64,
1
				max_fee_per_gas: U256::from(BASE_FEE_GENISIS),
1
				max_priority_fee_per_gas: None,
1
				nonce: Some(U256::from(0)),
1
				access_list: Vec::new(),
1
			})
1
			.dispatch(<Runtime as frame_system::Config>::RuntimeOrigin::root()));
1
			let issuance_after = <Runtime as pallet_evm::Config>::Currency::total_issuance();
1
			// Fee is 1 GWEI base fee.
1
			let base_fee = TransactionPaymentAsGasPrice::min_gas_price().0;
1
			assert_eq!(base_fee.as_u128(), BASE_FEE_GENISIS); // hint in case following asserts fail
1
			let base_fee: Balance = BASE_FEE_GENISIS * 21_000;
1

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

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

            
1
			assert_eq!(issuance_after, issuance_before - burnt_base_fee_part);
1
			assert_eq!(moonbase_runtime::Treasury::pot(), treasury_base_fee_part);
1
		});
1
}
#[test]
1
fn root_can_change_default_xcm_vers() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_id: 1,
1
			xcm_location: xcm::v4::Location::parent(),
1
			name: "RelayToken",
1
			symbol: "Relay",
1
			decimals: 12,
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let source_id: moonbase_runtime::AssetId = 1;
1
			let currency_id = moonbase_runtime::xcm_config::CurrencyId::ForeignAsset(source_id);
1
			let asset = Asset {
1
				id: AssetId(
1
					<Runtime as pallet_xcm_transactor::Config>::CurrencyIdToLocation::convert(
1
						currency_id,
1
					)
1
					.unwrap(),
1
				),
1
				fun: Fungibility::Fungible(100_000_000_000_000),
1
			};
1
			// Default XCM version is not set yet, so xtokens should fail because it does not
1
			// know with which version to send
1
			assert_noop!(
1
				PolkadotXcm::transfer_assets(
1
					origin_of(AccountId::from(ALICE)),
1
					Box::new(VersionedLocation::V4(Location::parent())),
1
					Box::new(VersionedLocation::V4(Location {
1
						parents: 0,
1
						interior: [AccountId32 {
1
							network: None,
1
							id: [1u8; 32],
1
						}]
1
						.into(),
1
					})),
1
					Box::new(VersionedAssets::V4(asset.clone().into())),
1
					0,
1
					WeightLimit::Unlimited
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(4)
1
			));
			// Now transferring does not fail
1
			assert_ok!(PolkadotXcm::transfer_assets(
1
				origin_of(AccountId::from(ALICE)),
1
				Box::new(VersionedLocation::V4(Location::parent())),
1
				Box::new(VersionedLocation::V4(Location {
1
					parents: 0,
1
					interior: [AccountId32 {
1
						network: None,
1
						id: [1u8; 32],
1
					}]
1
					.into(),
1
				})),
1
				Box::new(VersionedAssets::V4(asset.into())),
1
				0,
1
				WeightLimit::Unlimited
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 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_xcm_assets(vec![XcmAssetInitialization {
1
			asset_id: 1,
1
			xcm_location: xcm::v4::Location::parent(),
1
			name: "RelayToken",
1
			symbol: "Relay",
1
			decimals: 12,
1
			balances: vec![(AccountId::from(ALICE), 1_000_000_000_000_000)],
1
		}])
1
		.build()
1
		.execute_with(|| {
1
			let source_id: moonbase_runtime::AssetId = 1;
1
			assert_ok!(XcmTransactor::register(
1
				root_origin(),
1
				AccountId::from(ALICE),
1
				0,
1
			));
			// Root can set transact info
1
			assert_ok!(XcmTransactor::set_transact_info(
1
				root_origin(),
1
				Box::new(xcm::VersionedLocation::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
					moonbase_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
					// 20000 is the max
1
					TransactWeights {
1
						transact_required_weight_at_most: 17001.into(),
1
						overall_weight: None
1
					},
1
					false
1
				),
1
				pallet_xcm_transactor::Error::<Runtime>::MaxWeightTransactReached
1
			);
1
			assert_noop!(
1
				XcmTransactor::transact_through_derivative(
1
					origin_of(AccountId::from(ALICE)),
1
					moonbase_runtime::xcm_config::Transactors::Relay,
1
					0,
1
					CurrencyPayment {
1
						currency: Currency::AsCurrencyId(
1
							moonbase_runtime::xcm_config::CurrencyId::ForeignAsset(source_id)
1
						),
1
						fee_amount: None
1
					},
1
					vec![],
1
					// 20000 is the max
1
					TransactWeights {
1
						transact_required_weight_at_most: 17001.into(),
1
						overall_weight: None
1
					},
1
					false
1
				),
1
				pallet_xcm_transactor::Error::<Runtime>::MaxWeightTransactReached
1
			);
1
		})
1
}
#[test]
1
fn root_can_use_hrmp_manage() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.build()
1
		.execute_with(|| {
1
			// It fails sending, because the router does not work in test mode
1
			// But all rest checks pass
1
			assert_noop!(
1
				XcmTransactor::hrmp_manage(
1
					root_origin(),
1
					HrmpOperation::Accept {
1
						para_id: 2000u32.into()
1
					},
1
					CurrencyPayment {
1
						currency: Currency::AsMultiLocation(Box::new(xcm::VersionedLocation::V4(
1
							Location::parent()
1
						))),
1
						fee_amount: Some(10000)
1
					},
1
					// 20000 is the max
1
					TransactWeights {
1
						transact_required_weight_at_most: 17001.into(),
1
						overall_weight: Some(Limited(20000.into()))
1
					}
1
				),
1
				pallet_xcm_transactor::Error::<Runtime>::ErrorValidating
1
			);
1
		})
1
}
#[test]
1
fn transact_through_signed_precompile_works_v1() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			// Destination
1
			let dest = Location::parent();
1

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

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

            
1
			let xcm_transactor_v1_precompile_address = H160::from_low_u64_be(2054);
1

            
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
				Weight::from_parts(200_000, (xcm_primitives::DEFAULT_PROOF_SIZE) + 4000),
1
				Some(4000.into())
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
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					xcm_transactor_v1_precompile_address,
1
					XcmTransactorV1PCall::transact_through_signed_multilocation {
1
						dest,
1
						fee_asset: fee_payer_asset,
1
						weight: 15000,
1
						call: bytes.into(),
1
					},
1
				)
1
				.expect_cost(23664)
1
				.expect_no_logs()
1
				.execute_returns(());
1
		});
1
}
#[test]
1
fn transact_through_signed_precompile_works_v2() {
1
	ExtBuilder::default()
1
		.with_balances(vec![
1
			(AccountId::from(ALICE), 2_000 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			// Destination
1
			let dest = Location::parent();
1

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

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

            
1
			let total_weight = 1_000_000_000u64;
1

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

            
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					xcm_transactor_v2_precompile_address,
1
					XcmTransactorV2PCall::transact_through_signed_multilocation {
1
						dest,
1
						fee_asset: fee_payer_asset,
1
						weight: 4_000_000,
1
						call: bytes.into(),
1
						fee_amount: u128::from(total_weight).into(),
1
						overall_weight: total_weight,
1
					},
1
				)
1
				.expect_cost(23664)
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 * UNIT),
1
			(AccountId::from(BOB), 1_000 * UNIT),
1
		])
1
		.with_safe_xcm_version(3)
1
		.build()
1
		.execute_with(|| {
1
			// Destination
1
			let dest = Location::here();
1

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

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

            
1
			let total_weight = 1_000_000_000u64;
1

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

            
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					xcm_transactor_v2_precompile_address,
1
					XcmTransactorV2PCall::transact_through_signed_multilocation {
1
						dest,
1
						fee_asset: fee_payer_asset,
1
						weight: 4_000_000,
1
						call: bytes.into(),
1
						fee_amount: u128::from(total_weight).into(),
1
						overall_weight: total_weight,
1
					},
1
				)
1
				.execute_reverts(|output| {
1
					from_utf8(&output)
1
						.unwrap()
1
						.contains("Dispatched call failed with error:")
1
						&& from_utf8(&output).unwrap().contains("ErrorValidating")
1
				});
1
		});
1
}
// Test to ensure we can use either in crowdloan rewards without worrying for migrations
#[test]
1
fn account_id_32_encodes_like_32_byte_u8_slice() {
1
	let account_as_account_id_32: sp_runtime::AccountId32 = [1u8; 32].into();
1
	let account_as_slice = [1u8; 32];
1
	assert_eq!(account_as_account_id_32.encode(), account_as_slice.encode());
1
}
#[test]
1
fn author_mapping_precompile_associate_update_and_clear() {
1
	ExtBuilder::default()
1
		.with_balances(vec![(AccountId::from(ALICE), 1_000 * UNIT)])
1
		.build()
1
		.execute_with(|| {
1
			let author_mapping_precompile_address = H160::from_low_u64_be(2055);
1
			let first_nimbus_id: NimbusId =
1
				sp_core::sr25519::Public::unchecked_from([1u8; 32]).into();
1
			let first_vrf_id: session_keys_primitives::VrfId =
1
				sp_core::sr25519::Public::unchecked_from([1u8; 32]).into();
1
			let second_nimbus_id: NimbusId =
1
				sp_core::sr25519::Public::unchecked_from([2u8; 32]).into();
1
			let second_vrf_id: session_keys_primitives::VrfId =
1
				sp_core::sr25519::Public::unchecked_from([2u8; 32]).into();
1

            
1
			// Associate it
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					author_mapping_precompile_address,
1
					AuthorMappingPCall::add_association {
1
						nimbus_id: [1u8; 32].into(),
1
					},
1
				)
1
				.expect_cost(14404)
1
				.expect_no_logs()
1
				.execute_returns(());
1

            
1
			let expected_associate_event =
1
				RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRegistered {
1
					nimbus_id: first_nimbus_id.clone(),
1
					account_id: AccountId::from(ALICE),
1
					keys: first_vrf_id.clone(),
1
				});
1
			assert_eq!(last_event(), expected_associate_event);
			// Update it
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					author_mapping_precompile_address,
1
					AuthorMappingPCall::update_association {
1
						old_nimbus_id: [1u8; 32].into(),
1
						new_nimbus_id: [2u8; 32].into(),
1
					},
1
				)
1
				.expect_cost(13909)
1
				.expect_no_logs()
1
				.execute_returns(());
1

            
1
			let expected_update_event =
1
				RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRotated {
1
					new_nimbus_id: second_nimbus_id.clone(),
1
					account_id: AccountId::from(ALICE),
1
					new_keys: second_vrf_id.clone(),
1
				});
1
			assert_eq!(last_event(), expected_update_event);
			// Clear it
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					author_mapping_precompile_address,
1
					AuthorMappingPCall::clear_association {
1
						nimbus_id: [2u8; 32].into(),
1
					},
1
				)
1
				.expect_cost(14404)
1
				.expect_no_logs()
1
				.execute_returns(());
1

            
1
			let expected_clear_event =
1
				RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRemoved {
1
					nimbus_id: second_nimbus_id,
1
					account_id: AccountId::from(ALICE),
1
					keys: second_vrf_id,
1
				});
1
			assert_eq!(last_event(), expected_clear_event);
1
		});
1
}
#[test]
1
fn author_mapping_register_and_set_keys() {
1
	ExtBuilder::default()
1
		.with_balances(vec![(AccountId::from(ALICE), 1_000 * UNIT)])
1
		.build()
1
		.execute_with(|| {
1
			let author_mapping_precompile_address = H160::from_low_u64_be(2055);
1
			let first_nimbus_id: NimbusId =
1
				sp_core::sr25519::Public::unchecked_from([1u8; 32]).into();
1
			let first_vrf_key: session_keys_primitives::VrfId =
1
				sp_core::sr25519::Public::unchecked_from([3u8; 32]).into();
1
			let second_nimbus_id: NimbusId =
1
				sp_core::sr25519::Public::unchecked_from([2u8; 32]).into();
1
			let second_vrf_key: session_keys_primitives::VrfId =
1
				sp_core::sr25519::Public::unchecked_from([4u8; 32]).into();
1

            
1
			// Associate it
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					author_mapping_precompile_address,
1
					AuthorMappingPCall::set_keys {
1
						keys: solidity::encode_arguments((
1
							H256::from([1u8; 32]),
1
							H256::from([3u8; 32]),
1
						))
1
						.into(),
1
					},
1
				)
1
				.expect_cost(16184)
1
				.expect_no_logs()
1
				.execute_returns(());
1

            
1
			let expected_associate_event =
1
				RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRegistered {
1
					nimbus_id: first_nimbus_id.clone(),
1
					account_id: AccountId::from(ALICE),
1
					keys: first_vrf_key.clone(),
1
				});
1
			assert_eq!(last_event(), expected_associate_event);
			// Update it
1
			Precompiles::new()
1
				.prepare_test(
1
					ALICE,
1
					author_mapping_precompile_address,
1
					AuthorMappingPCall::set_keys {
1
						keys: solidity::encode_arguments((
1
							H256::from([2u8; 32]),
1
							H256::from([4u8; 32]),
1
						))
1
						.into(),
1
					},
1
				)
1
				.expect_cost(16184)
1
				.expect_no_logs()
1
				.execute_returns(());
1

            
1
			let expected_update_event =
1
				RuntimeEvent::AuthorMapping(pallet_author_mapping::Event::KeysRotated {
1
					new_nimbus_id: second_nimbus_id.clone(),
1
					account_id: AccountId::from(ALICE),
1
					new_keys: second_vrf_key.clone(),
1
				});
1
			assert_eq!(last_event(), expected_update_event);
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_multilocation = 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_multilocation)
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_multilocation,
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::<moonbase_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 * moonbase_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, 1027, 2048, 2049, 2050, 2051, 2052,
1
			2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066,
1
			2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075,
1
		]
1
		.into_iter()
1
		.map(H160::from_low_u64_be)
1
		.collect();
3001
		for i in 0..3000 {
3000
			let address = H160::from_low_u64_be(i);
3000

            
3000
			if precompile_addresses.contains(&address) {
42
				assert!(
42
					is_precompile_or_fail::<Runtime>(address, 100_000u64).expect("to be ok"),
					"is_precompile({}) should return true",
					i
				);
42
				assert!(
42
					precompiles
42
						.execute(&mut MockHandle::new(
42
							address,
42
							Context {
42
								address,
42
								caller: H160::zero(),
42
								apparent_value: U256::zero()
42
							}
42
						),)
42
						.is_some(),
					"execute({},..) should return Some(_)",
					i
				);
			} else {
2958
				assert!(
2958
					!is_precompile_or_fail::<Runtime>(address, 100_000u64).expect("to be ok"),
					"is_precompile({}) should return false",
					i
				);
2958
				assert!(
2958
					precompiles
2958
						.execute(&mut MockHandle::new(
2958
							address,
2958
							Context {
2958
								address,
2958
								caller: H160::zero(),
2958
								apparent_value: U256::zero()
2958
							}
2958
						),)
2958
						.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") {
2957
				continue;
42
			}
42

            
42
			if !removed_precompiles.contains(&i) {
38
				assert!(
38
					match precompiles.is_active_precompile(address, 100_000u64) {
38
						IsPrecompileResult::Answer { is_precompile, .. } => is_precompile,
						_ => false,
					},
					"{i} should be an active precompile"
				);
38
				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 substrate_based_fees_zero_txn_costs_only_base_extrinsic() {
1
	use frame_support::dispatch::{DispatchInfo, Pays};
1
	use moonbase_runtime::{currency, EXTRINSIC_BASE_WEIGHT};
1

            
1
	ExtBuilder::default().build().execute_with(|| {
1
		let size_bytes = 0;
1
		let tip = 0;
1
		let dispatch_info = DispatchInfo {
1
			weight: Weight::zero(),
1
			class: DispatchClass::Normal,
1
			pays_fee: Pays::Yes,
1
		};
1

            
1
		assert_eq!(
1
			TransactionPayment::compute_fee(size_bytes, &dispatch_info, tip),
1
			EXTRINSIC_BASE_WEIGHT.ref_time() as u128 * currency::WEIGHT_FEE,
1
		);
1
	});
1
}
#[test]
1
fn deal_with_fees_handles_tip() {
1
	use frame_support::traits::OnUnbalanced;
1
	use moonbase_runtime::Treasury;
1
	use moonbeam_runtime_common::deal_with_fees::DealWithSubstrateFeesAndTip;
1

            
1
	ExtBuilder::default().build().execute_with(|| {
1
		set_parachain_inherent_data();
1
		// This test validates the functionality of the `DealWithSubstrateFeesAndTip` trait implementation
1
		// in the Moonbeam runtime. It verifies that:
1
		// - The correct proportion of the fee is sent to the treasury.
1
		// - The remaining fee is burned (removed from the total supply).
1
		// - The entire tip is sent to the block author.
1

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

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

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

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

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

            
1
		// Step 5: Validate the treasury received 20% of the fee.
1
		assert_eq!(
1
			Balances::free_balance(&Treasury::account_id()),
1
			treasury_fee_part,
1
		);
		// Step 6: Verify that 80% of the fee was burned (removed from the total supply).
1
		let total_supply_after = Balances::total_issuance();
1
		assert_eq!(total_supply_before - total_supply_after, burnt_fee_part,);
		// Step 7: Validate that the block author (collator) received 100% of the tip.
1
		let block_author_balance_after = Balances::free_balance(&block_author);
1
		assert_eq!(
1
			block_author_balance_after - block_author_balance_before,
1
			1000,
1
		);
1
	});
1
}
#[test]
1
fn evm_revert_substrate_events() {
1
	ExtBuilder::default()
1
		.with_balances(vec![(AccountId::from(ALICE), 1_000 * UNIT)])
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 * UNIT), 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_GENISIS),
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 * UNIT)])
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 * UNIT)].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_GENISIS),
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
}
#[test]
1
fn validate_transaction_fails_on_filtered_call() {
1
	use sp_runtime::transaction_validity::{
1
		InvalidTransaction, TransactionSource, TransactionValidityError,
1
	};
1
	use sp_transaction_pool::runtime_api::runtime_decl_for_tagged_transaction_queue::TaggedTransactionQueueV3; // editorconfig-checker-disable-line
1

            
1
	ExtBuilder::default().build().execute_with(|| {
1
		let xt = UncheckedExtrinsic::new_unsigned(
1
			pallet_evm::Call::<Runtime>::call {
1
				source: Default::default(),
1
				target: H160::default(),
1
				input: Vec::new(),
1
				value: Default::default(),
1
				gas_limit: Default::default(),
1
				max_fee_per_gas: Default::default(),
1
				max_priority_fee_per_gas: Default::default(),
1
				nonce: Default::default(),
1
				access_list: Default::default(),
1
			}
1
			.into(),
1
		);
1

            
1
		assert_eq!(
1
			Runtime::validate_transaction(TransactionSource::External, xt, Default::default(),),
1
			Err(TransactionValidityError::Invalid(InvalidTransaction::Call)),
1
		);
1
	});
1
}
#[cfg(test)]
mod treasury_tests {
	use super::*;
	use sp_runtime::traits::Hash;
4
	fn expect_events(events: Vec<RuntimeEvent>) {
4
		let block_events: Vec<RuntimeEvent> =
13
			System::events().into_iter().map(|r| r.event).collect();
4

            
4
		dbg!(events.clone());
4
		dbg!(block_events.clone());
4

            
7
		assert!(events.iter().all(|evt| block_events.contains(evt)))
4
	}
8
	fn next_block() {
8
		System::reset_events();
8
		System::set_block_number(System::block_number() + 1u32);
8
		System::on_initialize(System::block_number());
8
		Treasury::on_initialize(System::block_number());
8
	}
	#[test]
1
	fn test_treasury_spend_local_with_root_origin() {
1
		let initial_treasury_balance = 1_000 * UNIT;
1
		ExtBuilder::default()
1
			.with_balances(vec![
1
				(AccountId::from(ALICE), 2_000 * UNIT),
1
				(Treasury::account_id(), initial_treasury_balance),
1
			])
1
			.build()
1
			.execute_with(|| {
1
				let spend_amount = 100u128 * UNIT;
1
				let spend_beneficiary = AccountId::from(BOB);
1

            
1
				next_block();
1

            
1
				// Perform treasury spending
1

            
1
				assert_ok!(moonbase_runtime::Sudo::sudo(
1
					root_origin(),
1
					Box::new(RuntimeCall::Treasury(pallet_treasury::Call::spend {
1
						amount: spend_amount,
1
						asset_kind: Box::new(()),
1
						beneficiary: Box::new(AccountId::from(BOB)),
1
						valid_from: Some(5u32),
1
					}))
1
				));
1
				let payout_period =
1
					<<Runtime as pallet_treasury::Config>::PayoutPeriod as Get<u32>>::get();
1
				let expected_events = [RuntimeEvent::Treasury(
1
					pallet_treasury::Event::AssetSpendApproved {
1
						index: 0,
1
						asset_kind: (),
1
						amount: spend_amount,
1
						beneficiary: spend_beneficiary,
1
						valid_from: 5u32,
1
						expire_at: payout_period + 5u32,
1
					},
1
				)]
1
				.to_vec();
1
				expect_events(expected_events);
4
				while System::block_number() < 5u32 {
3
					next_block();
3
				}
1
				assert_ok!(Treasury::payout(origin_of(spend_beneficiary), 0));
1
				let expected_events = [
1
					RuntimeEvent::Treasury(pallet_treasury::Event::Paid {
1
						index: 0,
1
						payment_id: (),
1
					}),
1
					RuntimeEvent::Balances(pallet_balances::Event::Transfer {
1
						from: Treasury::account_id(),
1
						to: spend_beneficiary,
1
						amount: spend_amount,
1
					}),
1
				]
1
				.to_vec();
1
				expect_events(expected_events);
1
			});
1
	}
	#[test]
1
	fn test_treasury_spend_local_with_council_origin() {
1
		let initial_treasury_balance = 1_000 * UNIT;
1
		ExtBuilder::default()
1
			.with_balances(vec![
1
				(AccountId::from(ALICE), 2_000 * UNIT),
1
				(Treasury::account_id(), initial_treasury_balance),
1
			])
1
			.build()
1
			.execute_with(|| {
1
				let spend_amount = 100u128 * UNIT;
1
				let spend_beneficiary = AccountId::from(BOB);
1

            
1
				next_block();
1

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

            
1
				// Perform treasury spending
1
				let proposal = RuntimeCall::Treasury(pallet_treasury::Call::spend {
1
					amount: spend_amount,
1
					asset_kind: Box::new(()),
1
					beneficiary: Box::new(AccountId::from(BOB)),
1
					valid_from: Some(5u32),
1
				});
1
				assert_ok!(TreasuryCouncilCollective::propose(
1
					origin_of(AccountId::from(ALICE)),
1
					1,
1
					Box::new(proposal.clone()),
1
					1_000
1
				));
1
				let payout_period =
1
					<<Runtime as pallet_treasury::Config>::PayoutPeriod as Get<u32>>::get();
1
				let expected_events = [
1
					RuntimeEvent::Treasury(pallet_treasury::Event::AssetSpendApproved {
1
						index: 0,
1
						asset_kind: (),
1
						amount: spend_amount,
1
						beneficiary: spend_beneficiary,
1
						valid_from: 5u32,
1
						expire_at: payout_period + 5u32,
1
					}),
1
					RuntimeEvent::TreasuryCouncilCollective(pallet_collective::Event::Executed {
1
						proposal_hash: sp_runtime::traits::BlakeTwo256::hash_of(&proposal),
1
						result: Ok(()),
1
					}),
1
				]
1
				.to_vec();
1
				expect_events(expected_events);
3
				while System::block_number() < 5u32 {
2
					next_block();
2
				}
1
				assert_ok!(Treasury::payout(origin_of(spend_beneficiary), 0));
1
				let expected_events = [
1
					RuntimeEvent::Treasury(pallet_treasury::Event::Paid {
1
						index: 0,
1
						payment_id: (),
1
					}),
1
					RuntimeEvent::Balances(pallet_balances::Event::Transfer {
1
						from: Treasury::account_id(),
1
						to: spend_beneficiary,
1
						amount: spend_amount,
1
					}),
1
				]
1
				.to_vec();
1
				expect_events(expected_events);
1
			});
1
	}
}
#[cfg(test)]
mod fee_tests {
	use super::*;
	use fp_evm::FeeCalculator;
	use frame_support::{
		traits::{ConstU128, OnFinalize},
		weights::{ConstantMultiplier, WeightToFee},
	};
	use moonbase_runtime::{
		currency, BlockWeights, FastAdjustingFeeUpdate, LengthToFee, MinimumMultiplier,
		TargetBlockFullness, TransactionPaymentAsGasPrice, NORMAL_WEIGHT, WEIGHT_PER_GAS,
	};
	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
			* BlockWeights::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 = FastAdjustingFeeUpdate::<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 = BlockWeights::get()
1
			.get(DispatchClass::Normal)
1
			.base_extrinsic;
1
		let multiplier = sp_runtime::FixedU128::from_float(0.999000000000000000);
1
		let extrinsic_len = 100u32;
1
		let extrinsic_weight = 5_000u64;
1
		let tip = 42u128;
1
		type WeightToFeeImpl =
1
			ConstantMultiplier<u128, ConstU128<{ moonbase_runtime::currency::WEIGHT_FEE }>>;
1
		type LengthToFeeImpl = LengthToFee;
1

            
1
		// base_fee + (multiplier * extrinsic_weight_fee) + extrinsic_length_fee + tip
1
		let expected_fee =
1
			WeightToFeeImpl::weight_to_fee(&base_extrinsic)
1
				+ multiplier.saturating_mul_int(WeightToFeeImpl::weight_to_fee(
1
					&Weight::from_parts(extrinsic_weight, 1),
1
				)) + LengthToFeeImpl::weight_to_fee(&Weight::from_parts(extrinsic_len as u64, 1))
1
				+ tip;
1

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

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

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

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

            
1
			assert_ne!(
				a, b,
				"both gas prices were equal, unexpected precision loss incurred"
			);
1
		});
1
	}
	#[test]
1
	fn test_fee_scenarios() {
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 = (currency::WEIGHT_FEE).saturating_mul(WEIGHT_PER_GAS as u128);
12
			let sim = |start_gas_price: u128, fullness: Perbill, num_blocks: u64| -> U256 {
12
				let start_multiplier =
12
					FixedU128::from_rational(start_gas_price, weight_fee_per_gas);
12
				pallet_transaction_payment::NextFeeMultiplier::<Runtime>::set(start_multiplier);
12

            
12
				let block_weight = NORMAL_WEIGHT * fullness;
60004
				for i in 0..num_blocks {
60004
					System::set_block_number(i as u32);
60004
					System::set_block_consumed_resources(block_weight, 0);
60004
					TransactionPayment::on_finalize(i as u32);
60004
				}
12
				TransactionPaymentAsGasPrice::min_gas_price().0
12
			};
			// The expected values are the ones observed during test execution,
			// they are expected to change when parameters that influence
			// the fee calculation are changed, and should be updated accordingly.
			// If a test fails when nothing specific to fees has changed,
			// it may indicate an unexpected collateral effect and should be investigated
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(0), 1),
1
				U256::from(998_600_980),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(25), 1),
1
				U256::from(999_600_080),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(50), 1),
1
				U256::from(1_000_600_180),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(100), 1),
1
				U256::from(1_002_603_380),
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(431_710_642),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(25), 600),
1
				U256::from(786_627_866),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(50), 600),
1
				U256::from(1_433_329_383u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(100), 600),
1
				U256::from(4_758_812_897u128),
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(31_250_000), // lower bound enforced
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(25), 14400),
1
				U256::from(31_250_000), // lower bound enforced if threshold not reached
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(50), 14400),
1
				U256::from(5_653_326_895_069u128),
1
			);
1
			assert_eq!(
1
				sim(1_000_000_000, Perbill::from_percent(100), 14400),
1
				U256::from(31_250_000_000_000u128),
1
				// upper bound enforced (min_gas_price * MaximumMultiplier)
1
			);
1
		});
1
	}
}