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
714
construct_runtime!(
44
163
	pub enum Runtime
45
163
	{
46
163
		System: frame_system,
47
163
		Balances: pallet_balances,
48
163
		Evm: pallet_evm,
49
163
		Timestamp: pallet_timestamp,
50
163
		Preimage: pallet_preimage,
51
163
		Scheduler: pallet_scheduler,
52
163
		Referenda: pallet_referenda,
53
163
	}
54
732
);
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
	type ExtensionsWeightInfo = ();
94
}
95

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

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

            
124
pub type PCall = ReferendaPrecompileCall<Runtime, GovOrigin>;
125

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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