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
//! Test utilities
18
use super::*;
19
use frame_support::traits::tokens::{PayFromAccount, UnityAssetBalanceConversion};
20
use frame_support::{
21
	construct_runtime, parameter_types,
22
	traits::{ConstU128, Everything, MapSuccess, OnFinalize, OnInitialize},
23
	PalletId,
24
};
25
use frame_system::pallet_prelude::BlockNumberFor;
26
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, SubstrateBlockHashMapping};
27
use precompile_utils::{
28
	precompile_set::*,
29
	testing::{Bob, Charlie, MockAccount},
30
};
31
use sp_core::{H256, U256};
32
use sp_io;
33
use sp_runtime::{
34
	traits::{BlakeTwo256, IdentityLookup, Replace},
35
	BuildStorage, Permill,
36
};
37

            
38
#[cfg(feature = "runtime-benchmarks")]
39
use pallet_treasury::ArgumentsFactory;
40

            
41
pub type AccountId = MockAccount;
42
pub type Balance = u128;
43
pub type BlockNumber = BlockNumberFor<Runtime>;
44

            
45
type Block = frame_system::mocking::MockBlockU32<Runtime>;
46

            
47
// Configure a mock runtime to test the pallet.
48
668
construct_runtime!(
49
	pub enum Runtime	{
50
		System: frame_system,
51
		Balances: pallet_balances,
52
		Evm: pallet_evm,
53
		Timestamp: pallet_timestamp,
54
		Treasury: pallet_treasury,
55
		CouncilCollective:
56
			pallet_collective::<Instance1>,
57
	}
58
1795
);
59

            
60
parameter_types! {
61
	pub const BlockHashCount: u32 = 250;
62
	pub const SS58Prefix: u8 = 42;
63
}
64
impl frame_system::Config for Runtime {
65
	type BaseCallFilter = Everything;
66
	type DbWeight = ();
67
	type RuntimeOrigin = RuntimeOrigin;
68
	type RuntimeTask = RuntimeTask;
69
	type Nonce = u64;
70
	type Block = Block;
71
	type RuntimeCall = RuntimeCall;
72
	type Hash = H256;
73
	type Hashing = BlakeTwo256;
74
	type AccountId = AccountId;
75
	type Lookup = IdentityLookup<Self::AccountId>;
76
	type RuntimeEvent = RuntimeEvent;
77
	type BlockHashCount = BlockHashCount;
78
	type Version = ();
79
	type PalletInfo = PalletInfo;
80
	type AccountData = pallet_balances::AccountData<Balance>;
81
	type OnNewAccount = ();
82
	type OnKilledAccount = ();
83
	type SystemWeightInfo = ();
84
	type BlockWeights = ();
85
	type BlockLength = ();
86
	type SS58Prefix = SS58Prefix;
87
	type OnSetCode = ();
88
	type MaxConsumers = frame_support::traits::ConstU32<16>;
89
	type SingleBlockMigrations = ();
90
	type MultiBlockMigrator = ();
91
	type PreInherents = ();
92
	type PostInherents = ();
93
	type PostTransactions = ();
94
}
95

            
96
parameter_types! {
97
	pub const ExistentialDeposit: u128 = 0;
98
}
99

            
100
impl pallet_balances::Config for Runtime {
101
	type MaxReserves = ();
102
	type ReserveIdentifier = ();
103
	type MaxLocks = ();
104
	type Balance = Balance;
105
	type RuntimeEvent = RuntimeEvent;
106
	type DustRemoval = ();
107
	type ExistentialDeposit = ExistentialDeposit;
108
	type AccountStore = System;
109
	type WeightInfo = ();
110
	type RuntimeHoldReason = ();
111
	type FreezeIdentifier = ();
112
	type MaxFreezes = ();
113
	type RuntimeFreezeReason = ();
114
}
115

            
116
pub type Precompiles<R> = PrecompileSetBuilder<
117
	R,
118
	(PrecompileAt<AddressU64<1>, CollectivePrecompile<R, pallet_collective::Instance1>>,),
119
>;
120

            
121
pub type PCall = CollectivePrecompileCall<Runtime, pallet_collective::Instance1>;
122

            
123
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
124
/// Block storage limit in bytes. Set to 40 KB.
125
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
126

            
127
parameter_types! {
128
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
129
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
130
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
131
	pub GasLimitPovSizeRatio: u64 = {
132
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
133
		block_gas_limit.saturating_div(MAX_POV_SIZE)
134
	};
135
	pub GasLimitStorageGrowthRatio : u64 = {
136
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
137
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
138
	};
139
}
140

            
141
impl pallet_evm::Config for Runtime {
142
	type FeeCalculator = ();
143
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
144
	type WeightPerGas = WeightPerGas;
145
	type CallOrigin = EnsureAddressRoot<AccountId>;
146
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
147
	type AddressMapping = AccountId;
148
	type Currency = Balances;
149
	type RuntimeEvent = RuntimeEvent;
150
	type Runner = pallet_evm::runner::stack::Runner<Self>;
151
	type PrecompilesType = Precompiles<Self>;
152
	type PrecompilesValue = PrecompilesValue;
153
	type ChainId = ();
154
	type OnChargeTransaction = ();
155
	type BlockGasLimit = BlockGasLimit;
156
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
157
	type FindAuthor = ();
158
	type OnCreate = ();
159
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
160
	type SuicideQuickClearLimit = ConstU32<0>;
161
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
162
	type Timestamp = Timestamp;
163
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
164
}
165

            
166
parameter_types! {
167
	pub const MinimumPeriod: u64 = 5;
168
}
169
impl pallet_timestamp::Config for Runtime {
170
	type Moment = u64;
171
	type OnTimestampSet = ();
172
	type MinimumPeriod = MinimumPeriod;
173
	type WeightInfo = ();
174
}
175

            
176
parameter_types! {
177
	pub const LaunchPeriod: BlockNumber = 10;
178
	pub const VotingPeriod: BlockNumber = 10;
179
	pub const VoteLockingPeriod: BlockNumber = 10;
180
	pub const FastTrackVotingPeriod: BlockNumber = 5;
181
	pub const EnactmentPeriod: BlockNumber = 10;
182
	pub const CooloffPeriod: BlockNumber = 10;
183
	pub const MinimumDeposit: Balance = 10;
184
	pub const MaxVotes: u32 = 10;
185
	pub const MaxProposals: u32 = 10;
186
	pub const PreimageByteDeposit: Balance = 10;
187
	pub const InstantAllowed: bool = false;
188
}
189

            
190
parameter_types! {
191
	pub const ProposalBond: Permill = Permill::from_percent(5);
192
	pub const TreasuryId: PalletId = PalletId(*b"pc/trsry");
193
	pub TreasuryAccount: AccountId = Treasury::account_id();
194
}
195

            
196
#[cfg(feature = "runtime-benchmarks")]
197
pub struct BenchmarkHelper;
198
#[cfg(feature = "runtime-benchmarks")]
199
impl ArgumentsFactory<(), AccountId> for BenchmarkHelper {
200
	fn create_asset_kind(_seed: u32) -> () {
201
		()
202
	}
203

            
204
	fn create_beneficiary(seed: [u8; 32]) -> AccountId {
205
		AccountId::from(H160::from(H256::from(seed)))
206
	}
207
}
208

            
209
impl pallet_treasury::Config for Runtime {
210
	type PalletId = TreasuryId;
211
	type Currency = Balances;
212
	type RejectOrigin = frame_support::traits::NeverEnsureOrigin<Balance>;
213
	type RuntimeEvent = RuntimeEvent;
214
	// If spending proposal rejected, transfer proposer bond to treasury
215
	type SpendPeriod = ConstU32<1>;
216
	type Burn = ();
217
	type BurnDestination = ();
218
	type MaxApprovals = ConstU32<100>;
219
	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;
220
	type SpendFunds = ();
221
	type SpendOrigin = MapSuccess<
222
		pallet_collective::EnsureProportionMoreThan<AccountId, pallet_collective::Instance1, 1, 2>,
223
		Replace<ConstU128<1000>>,
224
	>;
225
	type AssetKind = ();
226
	type Beneficiary = AccountId;
227
	type BeneficiaryLookup = IdentityLookup<AccountId>;
228
	type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
229
	type BalanceConverter = UnityAssetBalanceConversion;
230
	type PayoutPeriod = ConstU32<0>;
231
	#[cfg(feature = "runtime-benchmarks")]
232
	type BenchmarkHelper = BenchmarkHelper;
233
}
234

            
235
parameter_types! {
236
	pub MaxProposalWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000_000);
237
}
238

            
239
impl pallet_collective::Config<pallet_collective::Instance1> for Runtime {
240
	type RuntimeOrigin = RuntimeOrigin;
241
	type RuntimeEvent = RuntimeEvent;
242
	type Proposal = RuntimeCall;
243
	/// The maximum amount of time (in blocks) for council members to vote on motions.
244
	/// Motions may end in fewer blocks if enough votes are cast to determine the result.
245
	type MotionDuration = ConstU32<2>;
246
	/// The maximum number of Proposlas that can be open in the council at once.
247
	type MaxProposals = ConstU32<100>;
248
	/// The maximum number of council members.
249
	type MaxMembers = ConstU32<100>;
250
	type DefaultVote = pallet_collective::MoreThanMajorityThenPrimeDefaultVote;
251
	type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
252
	type SetMembersOrigin = frame_system::EnsureRoot<AccountId>;
253
	type MaxProposalWeight = MaxProposalWeight;
254
}
255

            
256
/// Build test externalities, prepopulated with data for testing democracy precompiles
257
pub(crate) struct ExtBuilder {
258
	/// Endowed accounts with balances
259
	balances: Vec<(AccountId, Balance)>,
260
	/// Collective members
261
	collective: Vec<AccountId>,
262
}
263

            
264
impl Default for ExtBuilder {
265
23
	fn default() -> ExtBuilder {
266
23
		ExtBuilder {
267
23
			balances: vec![],
268
23
			collective: vec![Bob.into(), Charlie.into()],
269
23
		}
270
23
	}
271
}
272

            
273
impl ExtBuilder {
274
	/// Fund some accounts before starting the test
275
	#[allow(unused)]
276
1
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
277
1
		self.balances = balances;
278
1
		self
279
1
	}
280

            
281
	/// Set members of the collective
282
	#[allow(unused)]
283
	pub(crate) fn with_collective(mut self, collective: Vec<AccountId>) -> Self {
284
		self.collective = collective;
285
		self
286
	}
287

            
288
	/// Build the test externalities for use in tests
289
	#[allow(unused)]
290
23
	pub(crate) fn build(self) -> sp_io::TestExternalities {
291
23
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
292
23
			.build_storage()
293
23
			.expect("Frame system builds valid default genesis config");
294
23

            
295
23
		pallet_balances::GenesisConfig::<Runtime> {
296
23
			balances: self.balances.clone(),
297
23
		}
298
23
		.assimilate_storage(&mut t)
299
23
		.expect("Pallet balances storage can be assimilated");
300
23

            
301
23
		pallet_collective::GenesisConfig::<Runtime, pallet_collective::Instance1> {
302
23
			members: self.collective.clone(),
303
23
			phantom: Default::default(),
304
23
		}
305
23
		.assimilate_storage(&mut t)
306
23
		.expect("Pallet collective storage can be assimilated");
307
23

            
308
23
		let mut ext = sp_io::TestExternalities::new(t);
309
23
		ext.execute_with(|| {
310
23
			System::set_block_number(1);
311
23
		});
312
23
		ext
313
23
	}
314
}
315

            
316
#[allow(unused)]
317
pub(crate) fn roll_to(n: BlockNumber) {
318
	// We skip timestamp's on_finalize because it requires that the timestamp inherent be set
319
	// We may be able to simulate this by poking its storage directly, but I don't see any value
320
	// added from doing that.
321
	while System::block_number() < n {
322
		Treasury::on_finalize(System::block_number());
323
		// Times tamp::on_finalize(System::block_number());
324
		Evm::on_finalize(System::block_number());
325
		Balances::on_finalize(System::block_number());
326
		System::on_finalize(System::block_number());
327

            
328
		System::set_block_number(System::block_number() + 1);
329

            
330
		System::on_initialize(System::block_number());
331
		Balances::on_initialize(System::block_number());
332
		Evm::on_initialize(System::block_number());
333
		Timestamp::on_initialize(System::block_number());
334
		Treasury::on_initialize(System::block_number());
335
	}
336
}
337

            
338
9
pub(crate) fn events() -> Vec<RuntimeEvent> {
339
9
	System::events()
340
9
		.into_iter()
341
42
		.map(|r| r.event)
342
9
		.collect::<Vec<_>>()
343
9
}
344

            
345
#[macro_export]
346
macro_rules! assert_tail_eq {
347
	($tail:expr, $arr:expr) => {
348
		if $tail.len() != 0 {
349
			// 0-length always passes
350

            
351
			if $tail.len() > $arr.len() {
352
				similar_asserts::assert_eq!($tail, $arr); // will fail
353
			}
354

            
355
			let len_diff = $arr.len() - $tail.len();
356
			similar_asserts::assert_eq!($tail, $arr[len_diff..]);
357
		}
358
	};
359
}
360

            
361
/// Panics if an event is not found in the system log of events
362
#[macro_export]
363
macro_rules! assert_event_emitted {
364
	($event:expr) => {
365
		match &$event {
366
			e => {
367
				assert!(
368
					crate::mock::events().iter().find(|x| *x == e).is_some(),
369
					"Event {:?} was not found in events: \n {:#?}",
370
					e,
371
					crate::mock::events()
372
				);
373
			}
374
		}
375
	};
376
}