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
283
construct_runtime!(
43
283
	pub enum Runtime	{
44
283
		System: frame_system,
45
283
		Balances: pallet_balances,
46
283
		Evm: pallet_evm,
47
283
		Timestamp: pallet_timestamp,
48
283
		ConvictionVoting: pallet_conviction_voting,
49
283
	}
50
283
);
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
	type CreateOriginFilter = ();
159
	type CreateInnerOriginFilter = ();
160
}
161

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

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

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

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

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

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

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

            
279
pub(crate) struct ExtBuilder {
280
	/// Endowed accounts with balances
281
	balances: Vec<(AccountId, Balance)>,
282
}
283

            
284
impl Default for ExtBuilder {
285
11
	fn default() -> ExtBuilder {
286
11
		ExtBuilder { balances: vec![] }
287
11
	}
288
}
289

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

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

            
303
11
		pallet_balances::GenesisConfig::<Runtime> {
304
11
			balances: self.balances.clone(),
305
11
			dev_accounts: Default::default(),
306
11
		}
307
11
		.assimilate_storage(&mut t)
308
11
		.expect("Pallet balances storage can be assimilated");
309
11

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

            
318
10
pub(crate) fn events() -> Vec<RuntimeEvent> {
319
10
	System::events()
320
10
		.into_iter()
321
71
		.map(|r| r.event)
322
10
		.collect::<Vec<_>>()
323
10
}