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
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
);
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 Runner = pallet_evm::runner::stack::Runner<Self>;
144
	type PrecompilesType = Precompiles<Runtime>;
145
	type PrecompilesValue = PrecompilesValue;
146
	type ChainId = ();
147
	type OnChargeTransaction = ();
148
	type BlockGasLimit = BlockGasLimit;
149
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
150
	type FindAuthor = ();
151
	type OnCreate = ();
152
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
153
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
154
	type Timestamp = Timestamp;
155
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
156
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
157
	type CreateOriginFilter = ();
158
	type CreateInnerOriginFilter = ();
159
}
160

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

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

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

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

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

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

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

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

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

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

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

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

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

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