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
1062
construct_runtime!(
43
282
	pub enum Runtime	{
44
282
		System: frame_system,
45
282
		Balances: pallet_balances,
46
282
		Evm: pallet_evm,
47
282
		Timestamp: pallet_timestamp,
48
282
		ConvictionVoting: pallet_conviction_voting,
49
282
	}
50
1101
);
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
	type ExtensionsWeightInfo = ();
91
}
92
parameter_types! {
93
	pub const ExistentialDeposit: u128 = 0;
94
}
95
impl pallet_balances::Config for Runtime {
96
	type MaxReserves = ();
97
	type ReserveIdentifier = [u8; 4];
98
	type MaxLocks = ();
99
	type Balance = Balance;
100
	type RuntimeEvent = RuntimeEvent;
101
	type DustRemoval = ();
102
	type ExistentialDeposit = ExistentialDeposit;
103
	type AccountStore = System;
104
	type WeightInfo = ();
105
	type RuntimeHoldReason = ();
106
	type FreezeIdentifier = ();
107
	type MaxFreezes = ();
108
	type RuntimeFreezeReason = ();
109
	type DoneSlashHandler = ();
110
}
111

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

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

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

            
133
pub type PCall = ConvictionVotingPrecompileCall<Runtime>;
134

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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