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::{construct_runtime, parameter_types, traits::Everything, weights::Weight};
20
use nimbus_primitives::NimbusId;
21
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
22
use precompile_utils::{precompile_set::*, testing::MockAccount};
23
use session_keys_primitives::VrfId;
24
use sp_core::H256;
25
use sp_runtime::{
26
	traits::{BlakeTwo256, IdentityLookup},
27
	BuildStorage, Perbill,
28
};
29
use sp_std::convert::{TryFrom, TryInto};
30

            
31
pub type AccountId = MockAccount;
32
pub type Balance = u128;
33

            
34
type Block = frame_system::mocking::MockBlockU32<Runtime>;
35

            
36
// Configure a mock runtime to test the pallet.
37
1110
construct_runtime!(
38
	pub enum Runtime	{
39
		System: frame_system,
40
		Balances: pallet_balances,
41
		AuthorMapping: pallet_author_mapping,
42
		Evm: pallet_evm,
43
		Timestamp: pallet_timestamp,
44
		Randomness: pallet_randomness,
45
	}
46
1846
);
47

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

            
87
parameter_types! {
88
	pub const ExistentialDeposit: u128 = 0;
89
}
90
impl pallet_balances::Config for Runtime {
91
	type MaxReserves = ();
92
	type ReserveIdentifier = [u8; 4];
93
	type MaxLocks = ();
94
	type Balance = Balance;
95
	type RuntimeEvent = RuntimeEvent;
96
	type DustRemoval = ();
97
	type ExistentialDeposit = ExistentialDeposit;
98
	type AccountStore = System;
99
	type WeightInfo = ();
100
	type RuntimeHoldReason = ();
101
	type FreezeIdentifier = ();
102
	type MaxFreezes = ();
103
	type RuntimeFreezeReason = ();
104
}
105

            
106
pub type TestPrecompiles<R> = PrecompileSetBuilder<
107
	R,
108
	(
109
		PrecompileAt<
110
			AddressU64<1>,
111
			RandomnessPrecompile<R>,
112
			(SubcallWithMaxNesting<1>, CallableByContract),
113
		>,
114
		RevertPrecompile<AddressU64<2>>,
115
	),
116
>;
117

            
118
pub type PCall = RandomnessPrecompileCall<Runtime>;
119

            
120
parameter_types! {
121
	pub PrecompilesValue: TestPrecompiles<Runtime> = TestPrecompiles::new();
122
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
123
	pub const SuicideQuickClearLimit: u32 = 0;
124
}
125

            
126
impl pallet_evm::Config for Runtime {
127
	type FeeCalculator = ();
128
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
129
	type WeightPerGas = WeightPerGas;
130
	type CallOrigin = EnsureAddressRoot<AccountId>;
131
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
132
	type AddressMapping = AccountId;
133
	type Currency = Balances;
134
	type RuntimeEvent = RuntimeEvent;
135
	type Runner = pallet_evm::runner::stack::Runner<Self>;
136
	type PrecompilesType = TestPrecompiles<Runtime>;
137
	type PrecompilesValue = PrecompilesValue;
138
	type ChainId = ();
139
	type OnChargeTransaction = ();
140
	type BlockGasLimit = ();
141
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
142
	type FindAuthor = ();
143
	type OnCreate = ();
144
	type GasLimitPovSizeRatio = ();
145
	type GasLimitStorageGrowthRatio = ();
146
	type Timestamp = Timestamp;
147
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
148
	type SuicideQuickClearLimit = SuicideQuickClearLimit;
149
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
150
}
151

            
152
parameter_types! {
153
	pub const MinimumPeriod: u64 = 5;
154
}
155
impl pallet_timestamp::Config for Runtime {
156
	type Moment = u64;
157
	type OnTimestampSet = ();
158
	type MinimumPeriod = MinimumPeriod;
159
	type WeightInfo = ();
160
}
161

            
162
parameter_types! {
163
	pub const DepositAmount: Balance = 100;
164
}
165
impl pallet_author_mapping::Config for Runtime {
166
	type RuntimeEvent = RuntimeEvent;
167
	type DepositCurrency = Balances;
168
	type DepositAmount = DepositAmount;
169
	type Keys = VrfId;
170
	type WeightInfo = ();
171
}
172

            
173
pub struct BabeDataGetter;
174
impl pallet_randomness::GetBabeData<u64, Option<H256>> for BabeDataGetter {
175
4
	fn get_epoch_index() -> u64 {
176
4
		1u64
177
4
	}
178
	fn get_epoch_randomness() -> Option<H256> {
179
		None
180
	}
181
}
182

            
183
parameter_types! {
184
	pub const Deposit: u128 = 10;
185
	pub const MaxRandomWords: u8 = 1;
186
	pub const MinBlockDelay: u32 = 2;
187
	pub const MaxBlockDelay: u32 = 20;
188
}
189
impl pallet_randomness::Config for Runtime {
190
	type RuntimeEvent = RuntimeEvent;
191
	type AddressMapping = AccountId;
192
	type Currency = Balances;
193
	type BabeDataGetter = BabeDataGetter;
194
	type VrfKeyLookup = AuthorMapping;
195
	type Deposit = Deposit;
196
	type MaxRandomWords = MaxRandomWords;
197
	type MinBlockDelay = MinBlockDelay;
198
	type MaxBlockDelay = MaxBlockDelay;
199
	type BlockExpirationDelay = MaxBlockDelay;
200
	type EpochExpirationDelay = MaxBlockDelay;
201
	type WeightInfo = pallet_randomness::weights::SubstrateWeight<Runtime>;
202
}
203

            
204
/// Externality builder for pallet randomness mock runtime
205
pub(crate) struct ExtBuilder {
206
	/// Balance amounts per AccountId
207
	balances: Vec<(AccountId, Balance)>,
208
	/// AuthorId -> AccountId mappings
209
	mappings: Vec<(NimbusId, AccountId)>,
210
}
211

            
212
impl Default for ExtBuilder {
213
18
	fn default() -> ExtBuilder {
214
18
		ExtBuilder {
215
18
			balances: Vec::new(),
216
18
			mappings: Vec::new(),
217
18
		}
218
18
	}
219
}
220

            
221
impl ExtBuilder {
222
	#[allow(dead_code)]
223
12
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
224
12
		self.balances = balances;
225
12
		self
226
12
	}
227

            
228
	#[allow(dead_code)]
229
	pub(crate) fn with_mappings(mut self, mappings: Vec<(NimbusId, AccountId)>) -> Self {
230
		self.mappings = mappings;
231
		self
232
	}
233

            
234
	#[allow(dead_code)]
235
18
	pub(crate) fn build(self) -> sp_io::TestExternalities {
236
18
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
237
18
			.build_storage()
238
18
			.expect("Frame system builds valid default genesis config");
239
18

            
240
18
		pallet_balances::GenesisConfig::<Runtime> {
241
18
			balances: self.balances,
242
18
		}
243
18
		.assimilate_storage(&mut t)
244
18
		.expect("Pallet balances storage can be assimilated");
245
18

            
246
18
		pallet_author_mapping::GenesisConfig::<Runtime> {
247
18
			mappings: self.mappings,
248
18
		}
249
18
		.assimilate_storage(&mut t)
250
18
		.expect("Pallet author mapping's storage can be assimilated");
251
18

            
252
18
		let mut ext = sp_io::TestExternalities::new(t);
253
18
		ext.execute_with(|| System::set_block_number(1));
254
18
		ext
255
18
	}
256
}
257

            
258
4
pub(crate) fn events() -> Vec<RuntimeEvent> {
259
4
	System::events()
260
4
		.into_iter()
261
20
		.map(|r| r.event)
262
4
		.collect::<Vec<_>>()
263
4
}
264

            
265
/// Panics if an event is not found in the system log of events
266
#[macro_export]
267
macro_rules! assert_event_emitted {
268
	($event:expr) => {
269
		match &$event {
270
			e => {
271
				assert!(
272
					crate::mock::events().iter().find(|x| *x == e).is_some(),
273
					"Event {:?} was not found in events: \n {:#?}",
274
					e,
275
					crate::mock::events()
276
				);
277
			}
278
		}
279
	};
280
}