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
79
construct_runtime!(
38
79
	pub enum Runtime	{
39
79
		System: frame_system,
40
79
		Balances: pallet_balances,
41
79
		AuthorMapping: pallet_author_mapping,
42
79
		Evm: pallet_evm,
43
79
		Timestamp: pallet_timestamp,
44
79
		Randomness: pallet_randomness,
45
79
	}
46
79
);
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
	type ExtensionsWeightInfo = ();
86
}
87

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

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

            
120
pub type PCall = RandomnessPrecompileCall<Runtime>;
121

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

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

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

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

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

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

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

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

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

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

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

            
243
18
		pallet_balances::GenesisConfig::<Runtime> {
244
18
			balances: self.balances,
245
18
			dev_accounts: Default::default(),
246
18
		}
247
18
		.assimilate_storage(&mut t)
248
18
		.expect("Pallet balances storage can be assimilated");
249
18

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

            
256
18
		let mut ext = sp_io::TestExternalities::new(t);
257
18
		ext.execute_with(|| System::set_block_number(1));
258
18
		ext
259
18
	}
260
}
261

            
262
4
pub(crate) fn events() -> Vec<RuntimeEvent> {
263
4
	System::events()
264
4
		.into_iter()
265
20
		.map(|r| r.event)
266
4
		.collect::<Vec<_>>()
267
4
}
268

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