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
//! A minimal precompile runtime including the pallet-randomness pallet
18
use super::*;
19
use frame_support::{
20
	construct_runtime, parameter_types,
21
	traits::{ConstU32, EqualPrivilegeOnly, Everything, SortedMembers, VoteTally},
22
	weights::Weight,
23
};
24
use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy, RawOrigin};
25
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
26
use pallet_referenda::{impl_tracksinfo_get, Curve, TrackInfo};
27
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
28
use precompile_utils::{precompile_set::*, testing::*};
29
use scale_info::TypeInfo;
30
use sp_core::H256;
31
use sp_runtime::{
32
	traits::{BlakeTwo256, IdentityLookup},
33
	BuildStorage, Perbill,
34
};
35
use sp_std::convert::{TryFrom, TryInto};
36

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

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

            
42
// Configure a mock runtime to test the pallet.
43
557
construct_runtime!(
44
	pub enum Runtime
45
	{
46
		System: frame_system,
47
		Balances: pallet_balances,
48
		Evm: pallet_evm,
49
		Timestamp: pallet_timestamp,
50
		Preimage: pallet_preimage,
51
		Scheduler: pallet_scheduler,
52
		Referenda: pallet_referenda,
53
	}
54
1010
);
55

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

            
95
parameter_types! {
96
	pub const ExistentialDeposit: u128 = 0;
97
}
98
impl pallet_balances::Config for Runtime {
99
	type MaxReserves = ();
100
	type ReserveIdentifier = [u8; 4];
101
	type MaxLocks = ();
102
	type Balance = Balance;
103
	type RuntimeEvent = RuntimeEvent;
104
	type DustRemoval = ();
105
	type ExistentialDeposit = ExistentialDeposit;
106
	type AccountStore = System;
107
	type WeightInfo = ();
108
	type RuntimeHoldReason = ();
109
	type FreezeIdentifier = ();
110
	type MaxFreezes = ();
111
	type RuntimeFreezeReason = ();
112
}
113

            
114
pub type TestPrecompiles<R> = PrecompileSetBuilder<
115
	R,
116
	(
117
		PrecompileAt<AddressU64<1>, ReferendaPrecompile<R, GovOrigin>>,
118
		RevertPrecompile<AddressU64<2>>,
119
	),
120
>;
121

            
122
pub type PCall = ReferendaPrecompileCall<Runtime, GovOrigin>;
123

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

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

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

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

            
178
impl pallet_preimage::Config for Runtime {
179
	type RuntimeEvent = RuntimeEvent;
180
	type WeightInfo = ();
181
	type Currency = Balances;
182
	type ManagerOrigin = EnsureRoot<AccountId>;
183
	type Consideration = ();
184
}
185
impl pallet_scheduler::Config for Runtime {
186
	type RuntimeEvent = RuntimeEvent;
187
	type RuntimeOrigin = RuntimeOrigin;
188
	type PalletsOrigin = OriginCaller;
189
	type RuntimeCall = RuntimeCall;
190
	type MaximumWeight = MaximumBlockWeight;
191
	type ScheduleOrigin = EnsureRoot<AccountId>;
192
	type MaxScheduledPerBlock = ConstU32<100>;
193
	type WeightInfo = ();
194
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
195
	type Preimages = Preimage;
196
}
197

            
198
10
parameter_types! {
199
10
	pub static AlarmInterval: u32 = 1;
200
10
}
201
pub struct OneToFive;
202
impl SortedMembers<AccountId> for OneToFive {
203
1
	fn sorted_members() -> Vec<AccountId> {
204
1
		vec![
205
1
			Alice.into(),
206
1
			Bob.into(),
207
1
			Charlie.into(),
208
1
			David.into(),
209
1
			Zero.into(),
210
1
		]
211
1
	}
212
	#[cfg(feature = "runtime-benchmarks")]
213
	fn add(_m: &AccountId) {}
214
}
215

            
216
pub struct TestTracksInfo;
217
impl TracksInfo<u128, u32> for TestTracksInfo {
218
	type Id = u8;
219
	type RuntimeOrigin = <RuntimeOrigin as OriginTrait>::PalletsOrigin;
220
10
	fn tracks() -> &'static [(Self::Id, TrackInfo<u128, u32>)] {
221
10
		static DATA: [(u8, TrackInfo<u128, u32>); 2] = [
222
10
			(
223
10
				0u8,
224
10
				TrackInfo {
225
10
					name: "root",
226
10
					max_deciding: 1,
227
10
					decision_deposit: 10,
228
10
					prepare_period: 4,
229
10
					decision_period: 4,
230
10
					confirm_period: 2,
231
10
					min_enactment_period: 4,
232
10
					min_approval: Curve::LinearDecreasing {
233
10
						length: Perbill::from_percent(100),
234
10
						floor: Perbill::from_percent(50),
235
10
						ceil: Perbill::from_percent(100),
236
10
					},
237
10
					min_support: Curve::LinearDecreasing {
238
10
						length: Perbill::from_percent(100),
239
10
						floor: Perbill::from_percent(0),
240
10
						ceil: Perbill::from_percent(100),
241
10
					},
242
10
				},
243
10
			),
244
10
			(
245
10
				1u8,
246
10
				TrackInfo {
247
10
					name: "none",
248
10
					max_deciding: 3,
249
10
					decision_deposit: 1,
250
10
					prepare_period: 2,
251
10
					decision_period: 2,
252
10
					confirm_period: 1,
253
10
					min_enactment_period: 2,
254
10
					min_approval: Curve::LinearDecreasing {
255
10
						length: Perbill::from_percent(100),
256
10
						floor: Perbill::from_percent(95),
257
10
						ceil: Perbill::from_percent(100),
258
10
					},
259
10
					min_support: Curve::LinearDecreasing {
260
10
						length: Perbill::from_percent(100),
261
10
						floor: Perbill::from_percent(90),
262
10
						ceil: Perbill::from_percent(100),
263
10
					},
264
10
				},
265
10
			),
266
10
		];
267
10
		&DATA[..]
268
10
	}
269
5
	fn track_for(id: &Self::RuntimeOrigin) -> Result<Self::Id, ()> {
270
5
		if let Ok(system_origin) = frame_system::RawOrigin::try_from(id.clone()) {
271
5
			match system_origin {
272
5
				frame_system::RawOrigin::Root => Ok(0),
273
				frame_system::RawOrigin::None => Ok(1),
274
				_ => Err(()),
275
			}
276
		} else {
277
			Err(())
278
		}
279
5
	}
280
}
281
impl_tracksinfo_get!(TestTracksInfo, u128, u32);
282

            
283
3
#[derive(Encode, Debug, Decode, TypeInfo, Eq, PartialEq, Clone, MaxEncodedLen)]
284
pub struct Tally {
285
	pub ayes: u32,
286
	pub nays: u32,
287
}
288

            
289
impl<Class> VoteTally<u32, Class> for Tally {
290
5
	fn new(_: Class) -> Self {
291
5
		Self { ayes: 0, nays: 0 }
292
5
	}
293

            
294
	fn ayes(&self, _: Class) -> u32 {
295
		self.ayes
296
	}
297

            
298
	fn support(&self, _: Class) -> Perbill {
299
		Perbill::from_percent(self.ayes)
300
	}
301

            
302
	fn approval(&self, _: Class) -> Perbill {
303
		if self.ayes + self.nays > 0 {
304
			Perbill::from_rational(self.ayes, self.ayes + self.nays)
305
		} else {
306
			Perbill::zero()
307
		}
308
	}
309

            
310
	#[cfg(feature = "runtime-benchmarks")]
311
	fn unanimity(_: Class) -> Self {
312
		Self { ayes: 100, nays: 0 }
313
	}
314

            
315
	#[cfg(feature = "runtime-benchmarks")]
316
	fn rejection(_: Class) -> Self {
317
		Self { ayes: 0, nays: 100 }
318
	}
319

            
320
	#[cfg(feature = "runtime-benchmarks")]
321
	fn from_requirements(support: Perbill, approval: Perbill, _: Class) -> Self {
322
		let ayes = support.mul_ceil(100u32);
323
		let nays = ((ayes as u64) * 1_000_000_000u64 / approval.deconstruct() as u64) as u32 - ayes;
324
		Self { ayes, nays }
325
	}
326

            
327
	#[cfg(feature = "runtime-benchmarks")]
328
	fn setup(_: Class, _: Perbill) {}
329
}
330
parameter_types! {
331
	pub const SubmissionDeposit: u128 = 15;
332
}
333
impl pallet_referenda::Config for Runtime {
334
	type WeightInfo = ();
335
	type RuntimeCall = RuntimeCall;
336
	type RuntimeEvent = RuntimeEvent;
337
	type Scheduler = Scheduler;
338
	type Currency = pallet_balances::Pallet<Self>;
339
	type SubmitOrigin = EnsureSigned<AccountId>;
340
	type CancelOrigin = EnsureSignedBy<OneToFive, AccountId>;
341
	type KillOrigin = EnsureRoot<AccountId>;
342
	type Slash = ();
343
	type Votes = u32;
344
	type Tally = Tally;
345
	type SubmissionDeposit = SubmissionDeposit;
346
	type MaxQueued = ConstU32<3>;
347
	type UndecidingTimeout = ConstU32<20>;
348
	type AlarmInterval = AlarmInterval;
349
	type Tracks = TestTracksInfo;
350
	type Preimages = Preimage;
351
}
352

            
353
pub struct GovOrigin;
354
impl FromStr for GovOrigin {
355
	type Err = ();
356
	fn from_str(_s: &str) -> Result<Self, Self::Err> {
357
		Err(())
358
	}
359
}
360

            
361
impl From<GovOrigin> for OriginCaller {
362
	fn from(_o: GovOrigin) -> OriginCaller {
363
		OriginCaller::system(RawOrigin::Root)
364
	}
365
}
366

            
367
/// Externality builder for pallet referenda mock runtime
368
pub(crate) struct ExtBuilder {
369
	/// Balance amounts per AccountId
370
	balances: Vec<(AccountId, Balance)>,
371
}
372

            
373
impl Default for ExtBuilder {
374
4
	fn default() -> ExtBuilder {
375
4
		ExtBuilder {
376
4
			balances: Vec::new(),
377
4
		}
378
4
	}
379
}
380

            
381
impl ExtBuilder {
382
	#[allow(dead_code)]
383
4
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
384
4
		self.balances = balances;
385
4
		self
386
4
	}
387

            
388
	#[allow(dead_code)]
389
4
	pub(crate) fn build(self) -> sp_io::TestExternalities {
390
4
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
391
4
			.build_storage()
392
4
			.expect("Frame system builds valid default genesis config");
393
4

            
394
4
		pallet_balances::GenesisConfig::<Runtime> {
395
4
			balances: self.balances,
396
4
		}
397
4
		.assimilate_storage(&mut t)
398
4
		.expect("Pallet balances storage can be assimilated");
399
4

            
400
4
		let mut ext = sp_io::TestExternalities::new(t);
401
4
		ext.execute_with(|| System::set_block_number(1));
402
4
		ext
403
4
	}
404
}
405

            
406
10
pub(crate) fn events() -> Vec<RuntimeEvent> {
407
10
	System::events()
408
10
		.into_iter()
409
150
		.map(|r| r.event)
410
10
		.collect::<Vec<_>>()
411
10
}