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

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

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

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

            
17
//! Test utilities
18
use super::*;
19
use frame_support::{
20
	construct_runtime, parameter_types,
21
	traits::{Everything, PollStatus, Polling, TotalIssuanceOf},
22
	weights::Weight,
23
};
24
use pallet_conviction_voting::TallyOf;
25
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
26
use precompile_utils::{precompile_set::*, testing::MockAccount};
27
use sp_core::{H256, U256};
28
use sp_runtime::{
29
	traits::{BlakeTwo256, ConstU32, ConstU64, IdentityLookup},
30
	BuildStorage, DispatchError, Perbill,
31
};
32
use sp_std::collections::btree_map::BTreeMap;
33

            
34
#[cfg(feature = "runtime-benchmarks")]
35
use frame_support::traits::VoteTally;
36

            
37
pub type AccountId = MockAccount;
38
pub type Balance = u128;
39

            
40
type Block = frame_system::mocking::MockBlock<Runtime>;
41

            
42
992
construct_runtime!(
43
	pub enum Runtime	{
44
		System: frame_system,
45
		Balances: pallet_balances,
46
		Evm: pallet_evm,
47
		Timestamp: pallet_timestamp,
48
		ConvictionVoting: pallet_conviction_voting,
49
	}
50
1411
);
51

            
52
parameter_types! {
53
	pub const BlockHashCount: u32 = 250;
54
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
55
	pub const MaximumBlockLength: u32 = 2 * 1024;
56
	pub const AvailableBlockRatio: Perbill = Perbill::one();
57
	pub const SS58Prefix: u8 = 42;
58
}
59

            
60
impl frame_system::Config for Runtime {
61
	type BaseCallFilter = Everything;
62
	type DbWeight = ();
63
	type RuntimeOrigin = RuntimeOrigin;
64
	type RuntimeTask = RuntimeTask;
65
	type Nonce = u64;
66
	type Block = Block;
67
	type RuntimeCall = RuntimeCall;
68
	type Hash = H256;
69
	type Hashing = BlakeTwo256;
70
	type AccountId = AccountId;
71
	type Lookup = IdentityLookup<AccountId>;
72
	type RuntimeEvent = RuntimeEvent;
73
	type BlockHashCount = BlockHashCount;
74
	type Version = ();
75
	type PalletInfo = PalletInfo;
76
	type AccountData = pallet_balances::AccountData<Balance>;
77
	type OnNewAccount = ();
78
	type OnKilledAccount = ();
79
	type SystemWeightInfo = ();
80
	type BlockWeights = ();
81
	type BlockLength = ();
82
	type SS58Prefix = SS58Prefix;
83
	type OnSetCode = ();
84
	type MaxConsumers = frame_support::traits::ConstU32<16>;
85
	type SingleBlockMigrations = ();
86
	type MultiBlockMigrator = ();
87
	type PreInherents = ();
88
	type PostInherents = ();
89
	type PostTransactions = ();
90
}
91
parameter_types! {
92
	pub const ExistentialDeposit: u128 = 0;
93
}
94
impl pallet_balances::Config for Runtime {
95
	type MaxReserves = ();
96
	type ReserveIdentifier = [u8; 4];
97
	type MaxLocks = ();
98
	type Balance = Balance;
99
	type RuntimeEvent = RuntimeEvent;
100
	type DustRemoval = ();
101
	type ExistentialDeposit = ExistentialDeposit;
102
	type AccountStore = System;
103
	type WeightInfo = ();
104
	type RuntimeHoldReason = ();
105
	type FreezeIdentifier = ();
106
	type MaxFreezes = ();
107
	type RuntimeFreezeReason = ();
108
}
109

            
110
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
111
/// Block storage limit in bytes. Set to 40 KB.
112
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
113

            
114
parameter_types! {
115
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
116
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
117
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
118
	pub GasLimitPovSizeRatio: u64 = {
119
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
120
		block_gas_limit.saturating_div(MAX_POV_SIZE)
121
	};
122
	pub GasLimitStorageGrowthRatio : u64 = {
123
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
124
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
125
	};
126
}
127

            
128
pub type Precompiles<R> =
129
	PrecompileSetBuilder<R, (PrecompileAt<AddressU64<1>, ConvictionVotingPrecompile<R>>,)>;
130

            
131
pub type PCall = ConvictionVotingPrecompileCall<Runtime>;
132

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

            
159
parameter_types! {
160
	pub const MinimumPeriod: u64 = 5;
161
}
162
impl pallet_timestamp::Config for Runtime {
163
	type Moment = u64;
164
	type OnTimestampSet = ();
165
	type MinimumPeriod = MinimumPeriod;
166
	type WeightInfo = ();
167
}
168

            
169
#[derive(Clone, PartialEq, Eq, Debug)]
170
pub enum TestPollState {
171
	Ongoing(TallyOf<Runtime>, u8),
172
	Completed(u64, bool),
173
}
174
use TestPollState::*;
175

            
176
44
parameter_types! {
177
44
	pub static Polls: BTreeMap<u8, TestPollState> = vec![
178
44
		(1, Completed(1, true)),
179
44
		(2, Completed(2, false)),
180
44
		(3, Ongoing(Tally::from_parts(0, 0, 0), 0)),
181
44
	].into_iter().collect();
182
44
}
183

            
184
pub struct TestPolls;
185
impl Polling<TallyOf<Runtime>> for TestPolls {
186
	type Index = u8;
187
	type Votes = u128;
188
	type Moment = u64;
189
	type Class = u8;
190
17
	fn classes() -> Vec<u8> {
191
17
		vec![0, 1, 2]
192
17
	}
193
2
	fn as_ongoing(index: u8) -> Option<(TallyOf<Runtime>, Self::Class)> {
194
2
		Polls::get().remove(&index).and_then(|x| {
195
2
			if let TestPollState::Ongoing(t, c) = x {
196
2
				Some((t, c))
197
			} else {
198
				None
199
			}
200
2
		})
201
2
	}
202
	fn access_poll<R>(
203
		index: Self::Index,
204
		f: impl FnOnce(PollStatus<&mut TallyOf<Runtime>, u64, u8>) -> R,
205
	) -> R {
206
		let mut polls = Polls::get();
207
		let entry = polls.get_mut(&index);
208
		let r = match entry {
209
			Some(Ongoing(ref mut tally_mut_ref, class)) => {
210
				f(PollStatus::Ongoing(tally_mut_ref, *class))
211
			}
212
			Some(Completed(when, succeeded)) => f(PollStatus::Completed(
213
				(*when).try_into().unwrap(),
214
				*succeeded,
215
			)),
216
			None => f(PollStatus::None),
217
		};
218
		Polls::set(polls);
219
		r
220
	}
221
16
	fn try_access_poll<R>(
222
16
		index: Self::Index,
223
16
		f: impl FnOnce(PollStatus<&mut TallyOf<Runtime>, u64, u8>) -> Result<R, DispatchError>,
224
16
	) -> Result<R, DispatchError> {
225
16
		let mut polls = Polls::get();
226
16
		let entry = polls.get_mut(&index);
227
16
		let r = match entry {
228
16
			Some(Ongoing(ref mut tally_mut_ref, class)) => {
229
16
				f(PollStatus::Ongoing(tally_mut_ref, *class))
230
			}
231
			Some(Completed(when, succeeded)) => f(PollStatus::Completed(
232
				(*when).try_into().unwrap(),
233
				*succeeded,
234
			)),
235
			None => f(PollStatus::None),
236
		}?;
237
16
		Polls::set(polls);
238
16
		Ok(r)
239
16
	}
240

            
241
	#[cfg(feature = "runtime-benchmarks")]
242
	fn create_ongoing(class: Self::Class) -> Result<Self::Index, ()> {
243
		let mut polls = Polls::get();
244
		let i = polls.keys().rev().next().map_or(0, |x| x + 1);
245
		polls.insert(i, Ongoing(Tally::new(0), class));
246
		Polls::set(polls);
247
		Ok(i)
248
	}
249

            
250
	#[cfg(feature = "runtime-benchmarks")]
251
	fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()> {
252
		let mut polls = Polls::get();
253
		match polls.get(&index) {
254
			Some(Ongoing(..)) => {}
255
			_ => return Err(()),
256
		}
257
		let now = frame_system::Pallet::<Runtime>::block_number();
258
		polls.insert(index, Completed(now, approved));
259
		Polls::set(polls);
260
		Ok(())
261
	}
262
}
263

            
264
impl pallet_conviction_voting::Config for Runtime {
265
	type RuntimeEvent = RuntimeEvent;
266
	type Currency = pallet_balances::Pallet<Self>;
267
	type VoteLockingPeriod = ConstU64<3>;
268
	type MaxVotes = ConstU32<3>;
269
	type WeightInfo = ();
270
	type MaxTurnout = TotalIssuanceOf<Balances, Self::AccountId>;
271
	type Polls = TestPolls;
272
}
273

            
274
pub(crate) struct ExtBuilder {
275
	/// Endowed accounts with balances
276
	balances: Vec<(AccountId, Balance)>,
277
}
278

            
279
impl Default for ExtBuilder {
280
11
	fn default() -> ExtBuilder {
281
11
		ExtBuilder { balances: vec![] }
282
11
	}
283
}
284

            
285
impl ExtBuilder {
286
	/// Fund some accounts before starting the test
287
11
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
288
11
		self.balances = balances;
289
11
		self
290
11
	}
291

            
292
	/// Build the test externalities for use in tests
293
11
	pub(crate) fn build(self) -> sp_io::TestExternalities {
294
11
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
295
11
			.build_storage()
296
11
			.expect("Frame system builds valid default genesis config");
297
11

            
298
11
		pallet_balances::GenesisConfig::<Runtime> {
299
11
			balances: self.balances.clone(),
300
11
		}
301
11
		.assimilate_storage(&mut t)
302
11
		.expect("Pallet balances storage can be assimilated");
303
11

            
304
11
		let mut ext = sp_io::TestExternalities::new(t);
305
11
		ext.execute_with(|| {
306
11
			System::set_block_number(1);
307
11
		});
308
11
		ext
309
11
	}
310
}
311

            
312
10
pub(crate) fn events() -> Vec<RuntimeEvent> {
313
10
	System::events()
314
10
		.into_iter()
315
70
		.map(|r| r.event)
316
10
		.collect::<Vec<_>>()
317
10
}