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
construct_runtime!(
48
	pub enum Runtime
49
	{
50
		System: frame_system,
51
		Balances: pallet_balances,
52
		Evm: pallet_evm,
53
		Timestamp: pallet_timestamp,
54
		Preimage: pallet_preimage,
55
		Scheduler: pallet_scheduler,
56
		Referenda: pallet_referenda,
57
	}
58
);
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 Runner = pallet_evm::runner::stack::Runner<Self>;
160
	type PrecompilesType = TestPrecompiles<Runtime>;
161
	type PrecompilesValue = PrecompilesValue;
162
	type ChainId = ();
163
	type OnChargeTransaction = ();
164
	type BlockGasLimit = BlockGasLimit;
165
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
166
	type FindAuthor = ();
167
	type OnCreate = ();
168
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
169
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
170
	type Timestamp = Timestamp;
171
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
172
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
173
	type CreateOriginFilter = ();
174
	type CreateInnerOriginFilter = ();
175
}
176

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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