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

            
19
use super::*;
20
use frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND;
21
use frame_support::{
22
	construct_runtime, parameter_types,
23
	traits::{ConstU32, EqualPrivilegeOnly, Everything, SortedMembers, VoteTally},
24
	weights::Weight,
25
};
26
use frame_system::{EnsureRoot, EnsureSigned, EnsureSignedBy, RawOrigin};
27
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
28
use pallet_referenda::{Curve, Track, TrackInfo};
29
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
30
use precompile_utils::{precompile_set::*, testing::*};
31
use scale_info::TypeInfo;
32
use sp_core::H256;
33
use sp_runtime::str_array as s;
34
use sp_runtime::{
35
	traits::{BlakeTwo256, IdentityLookup},
36
	BuildStorage, Perbill,
37
};
38
use sp_std::convert::{TryFrom, TryInto};
39
use std::borrow::Cow;
40

            
41
pub type AccountId = MockAccount;
42
pub type Balance = u128;
43

            
44
type Block = frame_system::mocking::MockBlockU32<Runtime>;
45

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

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

            
103
parameter_types! {
104
	pub const ExistentialDeposit: u128 = 0;
105
}
106
impl pallet_balances::Config for Runtime {
107
	type MaxReserves = ();
108
	type ReserveIdentifier = [u8; 4];
109
	type MaxLocks = ();
110
	type Balance = Balance;
111
	type RuntimeEvent = RuntimeEvent;
112
	type DustRemoval = ();
113
	type ExistentialDeposit = ExistentialDeposit;
114
	type AccountStore = System;
115
	type WeightInfo = ();
116
	type RuntimeHoldReason = ();
117
	type FreezeIdentifier = ();
118
	type MaxFreezes = ();
119
	type RuntimeFreezeReason = ();
120
	type DoneSlashHandler = ();
121
}
122

            
123
pub type TestPrecompiles<R> = PrecompileSetBuilder<
124
	R,
125
	(
126
		PrecompileAt<AddressU64<1>, ReferendaPrecompile<R, GovOrigin>>,
127
		RevertPrecompile<AddressU64<2>>,
128
	),
129
>;
130

            
131
pub type PCall = ReferendaPrecompileCall<Runtime, GovOrigin>;
132

            
133
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
134
/// Block storage limit in bytes. Set to 40 KB.
135
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
136

            
137
parameter_types! {
138
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
139
	pub PrecompilesValue: TestPrecompiles<Runtime> = TestPrecompiles::new();
140
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
141
	pub GasLimitPovSizeRatio: u64 = {
142
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
143
		block_gas_limit.saturating_div(MAX_POV_SIZE)
144
	};
145
	pub GasLimitStorageGrowthRatio: u64 = {
146
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
147
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
148
	};
149
}
150

            
151
impl pallet_evm::Config for Runtime {
152
	type FeeCalculator = ();
153
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
154
	type WeightPerGas = WeightPerGas;
155
	type CallOrigin = EnsureAddressRoot<AccountId>;
156
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
157
	type AddressMapping = AccountId;
158
	type Currency = Balances;
159
	type RuntimeEvent = RuntimeEvent;
160
	type Runner = pallet_evm::runner::stack::Runner<Self>;
161
	type PrecompilesType = TestPrecompiles<Runtime>;
162
	type PrecompilesValue = PrecompilesValue;
163
	type ChainId = ();
164
	type OnChargeTransaction = ();
165
	type BlockGasLimit = BlockGasLimit;
166
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
167
	type FindAuthor = ();
168
	type OnCreate = ();
169
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
170
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
171
	type Timestamp = Timestamp;
172
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
173
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
174
	type CreateOriginFilter = ();
175
	type CreateInnerOriginFilter = ();
176
}
177

            
178
parameter_types! {
179
	pub const MinimumPeriod: u64 = 5;
180
}
181
impl pallet_timestamp::Config for Runtime {
182
	type Moment = u64;
183
	type OnTimestampSet = ();
184
	type MinimumPeriod = MinimumPeriod;
185
	type WeightInfo = ();
186
}
187

            
188
impl pallet_preimage::Config for Runtime {
189
	type RuntimeEvent = RuntimeEvent;
190
	type WeightInfo = ();
191
	type Currency = Balances;
192
	type ManagerOrigin = EnsureRoot<AccountId>;
193
	type Consideration = ();
194
}
195
impl pallet_scheduler::Config for Runtime {
196
	type RuntimeEvent = RuntimeEvent;
197
	type RuntimeOrigin = RuntimeOrigin;
198
	type PalletsOrigin = OriginCaller;
199
	type RuntimeCall = RuntimeCall;
200
	type MaximumWeight = MaximumBlockWeight;
201
	type ScheduleOrigin = EnsureRoot<AccountId>;
202
	type MaxScheduledPerBlock = ConstU32<100>;
203
	type WeightInfo = ();
204
	type OriginPrivilegeCmp = EqualPrivilegeOnly;
205
	type Preimages = Preimage;
206
	type BlockNumberProvider = System;
207
}
208

            
209
parameter_types! {
210
	pub static AlarmInterval: u32 = 1;
211
}
212
pub struct OneToFive;
213
impl SortedMembers<AccountId> for OneToFive {
214
1
	fn sorted_members() -> Vec<AccountId> {
215
1
		vec![
216
1
			Alice.into(),
217
1
			Bob.into(),
218
1
			Charlie.into(),
219
1
			David.into(),
220
1
			Zero.into(),
221
1
		]
222
1
	}
223
	#[cfg(feature = "runtime-benchmarks")]
224
	fn add(_m: &AccountId) {}
225
}
226

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

            
293
#[derive(
294
	Encode, Debug, Decode, TypeInfo, Eq, PartialEq, Clone, MaxEncodedLen, DecodeWithMemTracking,
295
)]
296
pub struct Tally {
297
	pub ayes: u32,
298
	pub nays: u32,
299
}
300

            
301
impl<Class> VoteTally<u32, Class> for Tally {
302
5
	fn new(_: Class) -> Self {
303
5
		Self { ayes: 0, nays: 0 }
304
5
	}
305

            
306
	fn ayes(&self, _: Class) -> u32 {
307
		self.ayes
308
	}
309

            
310
	fn support(&self, _: Class) -> Perbill {
311
		Perbill::from_percent(self.ayes)
312
	}
313

            
314
	fn approval(&self, _: Class) -> Perbill {
315
		if self.ayes + self.nays > 0 {
316
			Perbill::from_rational(self.ayes, self.ayes + self.nays)
317
		} else {
318
			Perbill::zero()
319
		}
320
	}
321

            
322
	#[cfg(feature = "runtime-benchmarks")]
323
	fn unanimity(_: Class) -> Self {
324
		Self { ayes: 100, nays: 0 }
325
	}
326

            
327
	#[cfg(feature = "runtime-benchmarks")]
328
	fn rejection(_: Class) -> Self {
329
		Self { ayes: 0, nays: 100 }
330
	}
331

            
332
	#[cfg(feature = "runtime-benchmarks")]
333
	fn from_requirements(support: Perbill, approval: Perbill, _: Class) -> Self {
334
		let ayes = support.mul_ceil(100u32);
335
		let nays = ((ayes as u64) * 1_000_000_000u64 / approval.deconstruct() as u64) as u32 - ayes;
336
		Self { ayes, nays }
337
	}
338

            
339
	#[cfg(feature = "runtime-benchmarks")]
340
	fn setup(_: Class, _: Perbill) {}
341
}
342
parameter_types! {
343
	pub const SubmissionDeposit: u128 = 15;
344
}
345
impl pallet_referenda::Config for Runtime {
346
	type WeightInfo = ();
347
	type RuntimeCall = RuntimeCall;
348
	type RuntimeEvent = RuntimeEvent;
349
	type Scheduler = Scheduler;
350
	type Currency = pallet_balances::Pallet<Self>;
351
	type SubmitOrigin = EnsureSigned<AccountId>;
352
	type CancelOrigin = EnsureSignedBy<OneToFive, AccountId>;
353
	type KillOrigin = EnsureRoot<AccountId>;
354
	type Slash = ();
355
	type Votes = u32;
356
	type Tally = Tally;
357
	type SubmissionDeposit = SubmissionDeposit;
358
	type MaxQueued = ConstU32<3>;
359
	type UndecidingTimeout = ConstU32<20>;
360
	type AlarmInterval = AlarmInterval;
361
	type Tracks = TestTracksInfo;
362
	type Preimages = Preimage;
363
	type BlockNumberProvider = System;
364
}
365

            
366
pub struct GovOrigin;
367
impl FromStr for GovOrigin {
368
	type Err = ();
369
	fn from_str(_s: &str) -> Result<Self, Self::Err> {
370
		Err(())
371
	}
372
}
373

            
374
impl From<GovOrigin> for OriginCaller {
375
	fn from(_o: GovOrigin) -> OriginCaller {
376
		OriginCaller::system(RawOrigin::Root)
377
	}
378
}
379

            
380
/// Externality builder for pallet referenda mock runtime
381
pub(crate) struct ExtBuilder {
382
	/// Balance amounts per AccountId
383
	balances: Vec<(AccountId, Balance)>,
384
}
385

            
386
impl Default for ExtBuilder {
387
4
	fn default() -> ExtBuilder {
388
4
		ExtBuilder {
389
4
			balances: Vec::new(),
390
4
		}
391
4
	}
392
}
393

            
394
impl ExtBuilder {
395
	#[allow(dead_code)]
396
4
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
397
4
		self.balances = balances;
398
4
		self
399
4
	}
400

            
401
	#[allow(dead_code)]
402
4
	pub(crate) fn build(self) -> sp_io::TestExternalities {
403
4
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
404
4
			.build_storage()
405
4
			.expect("Frame system builds valid default genesis config");
406
4

            
407
4
		pallet_balances::GenesisConfig::<Runtime> {
408
4
			balances: self.balances,
409
4
			dev_accounts: Default::default(),
410
4
		}
411
4
		.assimilate_storage(&mut t)
412
4
		.expect("Pallet balances storage can be assimilated");
413
4

            
414
4
		let mut ext = sp_io::TestExternalities::new(t);
415
4
		ext.execute_with(|| System::set_block_number(1));
416
4
		ext
417
4
	}
418
}
419

            
420
10
pub(crate) fn events() -> Vec<RuntimeEvent> {
421
10
	System::events()
422
10
		.into_iter()
423
150
		.map(|r| r.event)
424
10
		.collect::<Vec<_>>()
425
10
}