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
//! Test utilities
18
use super::*;
19
use frame_support::traits::tokens::{PayFromAccount, UnityAssetBalanceConversion};
20
use frame_support::{
21
	construct_runtime, parameter_types,
22
	traits::{ConstU128, Everything, MapSuccess, OnFinalize, OnInitialize},
23
	PalletId,
24
};
25
use frame_system::{pallet_prelude::BlockNumberFor, EnsureRoot};
26
use pallet_evm::{
27
	EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider, SubstrateBlockHashMapping,
28
};
29
use precompile_utils::{
30
	precompile_set::*,
31
	testing::{Bob, Charlie, MockAccount},
32
};
33
use sp_core::{H256, U256};
34
use sp_io;
35
use sp_runtime::{
36
	traits::{BlakeTwo256, IdentityLookup, Replace},
37
	BuildStorage, Permill,
38
};
39

            
40
#[cfg(feature = "runtime-benchmarks")]
41
use pallet_treasury::ArgumentsFactory;
42

            
43
pub type AccountId = MockAccount;
44
pub type Balance = u128;
45
pub type BlockNumber = BlockNumberFor<Runtime>;
46

            
47
type Block = frame_system::mocking::MockBlockU32<Runtime>;
48

            
49
// Configure a mock runtime to test the pallet.
50
755
construct_runtime!(
51
205
	pub enum Runtime	{
52
205
		System: frame_system,
53
205
		Balances: pallet_balances,
54
205
		Evm: pallet_evm,
55
205
		Timestamp: pallet_timestamp,
56
205
		Treasury: pallet_treasury,
57
205
		CouncilCollective:
58
205
			pallet_collective::<Instance1>,
59
205
	}
60
783
);
61

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

            
99
parameter_types! {
100
	pub const ExistentialDeposit: u128 = 0;
101
}
102

            
103
impl pallet_balances::Config for Runtime {
104
	type MaxReserves = ();
105
	type ReserveIdentifier = ();
106
	type MaxLocks = ();
107
	type Balance = Balance;
108
	type RuntimeEvent = RuntimeEvent;
109
	type DustRemoval = ();
110
	type ExistentialDeposit = ExistentialDeposit;
111
	type AccountStore = System;
112
	type WeightInfo = ();
113
	type RuntimeHoldReason = ();
114
	type FreezeIdentifier = ();
115
	type MaxFreezes = ();
116
	type RuntimeFreezeReason = ();
117
	type DoneSlashHandler = ();
118
}
119

            
120
pub type Precompiles<R> = PrecompileSetBuilder<
121
	R,
122
	(PrecompileAt<AddressU64<1>, CollectivePrecompile<R, pallet_collective::Instance1>>,),
123
>;
124

            
125
pub type PCall = CollectivePrecompileCall<Runtime, pallet_collective::Instance1>;
126

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

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

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

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

            
180
parameter_types! {
181
	pub const LaunchPeriod: BlockNumber = 10;
182
	pub const VotingPeriod: BlockNumber = 10;
183
	pub const VoteLockingPeriod: BlockNumber = 10;
184
	pub const FastTrackVotingPeriod: BlockNumber = 5;
185
	pub const EnactmentPeriod: BlockNumber = 10;
186
	pub const CooloffPeriod: BlockNumber = 10;
187
	pub const MinimumDeposit: Balance = 10;
188
	pub const MaxVotes: u32 = 10;
189
	pub const MaxProposals: u32 = 10;
190
	pub const PreimageByteDeposit: Balance = 10;
191
	pub const InstantAllowed: bool = false;
192
}
193

            
194
parameter_types! {
195
	pub const ProposalBond: Permill = Permill::from_percent(5);
196
	pub const TreasuryId: PalletId = PalletId(*b"pc/trsry");
197
	pub TreasuryAccount: AccountId = Treasury::account_id();
198
}
199

            
200
#[cfg(feature = "runtime-benchmarks")]
201
pub struct BenchmarkHelper;
202
#[cfg(feature = "runtime-benchmarks")]
203
impl ArgumentsFactory<(), AccountId> for BenchmarkHelper {
204
	fn create_asset_kind(_seed: u32) -> () {
205
		()
206
	}
207

            
208
	fn create_beneficiary(seed: [u8; 32]) -> AccountId {
209
		AccountId::from(H160::from(H256::from(seed)))
210
	}
211
}
212

            
213
impl pallet_treasury::Config for Runtime {
214
	type PalletId = TreasuryId;
215
	type Currency = Balances;
216
	type RejectOrigin = frame_support::traits::NeverEnsureOrigin<Balance>;
217
	type RuntimeEvent = RuntimeEvent;
218
	// If spending proposal rejected, transfer proposer bond to treasury
219
	type SpendPeriod = ConstU32<1>;
220
	type Burn = ();
221
	type BurnDestination = ();
222
	type MaxApprovals = ConstU32<100>;
223
	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;
224
	type SpendFunds = ();
225
	type SpendOrigin = MapSuccess<
226
		pallet_collective::EnsureProportionMoreThan<AccountId, pallet_collective::Instance1, 1, 2>,
227
		Replace<ConstU128<1000>>,
228
	>;
229
	type AssetKind = ();
230
	type Beneficiary = AccountId;
231
	type BeneficiaryLookup = IdentityLookup<AccountId>;
232
	type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
233
	type BalanceConverter = UnityAssetBalanceConversion;
234
	type PayoutPeriod = ConstU32<0>;
235
	#[cfg(feature = "runtime-benchmarks")]
236
	type BenchmarkHelper = BenchmarkHelper;
237
	type BlockNumberProvider = System;
238
}
239

            
240
parameter_types! {
241
	pub MaxProposalWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000_000);
242
}
243

            
244
impl pallet_collective::Config<pallet_collective::Instance1> for Runtime {
245
	type RuntimeOrigin = RuntimeOrigin;
246
	type RuntimeEvent = RuntimeEvent;
247
	type Proposal = RuntimeCall;
248
	/// The maximum amount of time (in blocks) for council members to vote on motions.
249
	/// Motions may end in fewer blocks if enough votes are cast to determine the result.
250
	type MotionDuration = ConstU32<2>;
251
	/// The maximum number of Proposlas that can be open in the council at once.
252
	type MaxProposals = ConstU32<100>;
253
	/// The maximum number of council members.
254
	type MaxMembers = ConstU32<100>;
255
	type DefaultVote = pallet_collective::MoreThanMajorityThenPrimeDefaultVote;
256
	type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
257
	type SetMembersOrigin = frame_system::EnsureRoot<AccountId>;
258
	type MaxProposalWeight = MaxProposalWeight;
259
	type KillOrigin = EnsureRoot<AccountId>;
260
	type DisapproveOrigin = EnsureRoot<AccountId>;
261
	type Consideration = ();
262
}
263

            
264
/// Build test externalities, prepopulated with data for testing democracy precompiles
265
pub(crate) struct ExtBuilder {
266
	/// Endowed accounts with balances
267
	balances: Vec<(AccountId, Balance)>,
268
	/// Collective members
269
	collective: Vec<AccountId>,
270
}
271

            
272
impl Default for ExtBuilder {
273
23
	fn default() -> ExtBuilder {
274
23
		ExtBuilder {
275
23
			balances: vec![],
276
23
			collective: vec![Bob.into(), Charlie.into()],
277
23
		}
278
23
	}
279
}
280

            
281
impl ExtBuilder {
282
	/// Fund some accounts before starting the test
283
	#[allow(unused)]
284
1
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
285
1
		self.balances = balances;
286
1
		self
287
1
	}
288

            
289
	/// Set members of the collective
290
	#[allow(unused)]
291
	pub(crate) fn with_collective(mut self, collective: Vec<AccountId>) -> Self {
292
		self.collective = collective;
293
		self
294
	}
295

            
296
	/// Build the test externalities for use in tests
297
	#[allow(unused)]
298
23
	pub(crate) fn build(self) -> sp_io::TestExternalities {
299
23
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
300
23
			.build_storage()
301
23
			.expect("Frame system builds valid default genesis config");
302
23

            
303
23
		pallet_balances::GenesisConfig::<Runtime> {
304
23
			balances: self.balances.clone(),
305
23
		}
306
23
		.assimilate_storage(&mut t)
307
23
		.expect("Pallet balances storage can be assimilated");
308
23

            
309
23
		pallet_collective::GenesisConfig::<Runtime, pallet_collective::Instance1> {
310
23
			members: self.collective.clone(),
311
23
			phantom: Default::default(),
312
23
		}
313
23
		.assimilate_storage(&mut t)
314
23
		.expect("Pallet collective storage can be assimilated");
315
23

            
316
23
		let mut ext = sp_io::TestExternalities::new(t);
317
23
		ext.execute_with(|| {
318
23
			System::set_block_number(1);
319
23
		});
320
23
		ext
321
23
	}
322
}
323

            
324
#[allow(unused)]
325
pub(crate) fn roll_to(n: BlockNumber) {
326
	// We skip timestamp's on_finalize because it requires that the timestamp inherent be set
327
	// We may be able to simulate this by poking its storage directly, but I don't see any value
328
	// added from doing that.
329
	while System::block_number() < n {
330
		Treasury::on_finalize(System::block_number());
331
		// Times tamp::on_finalize(System::block_number());
332
		Evm::on_finalize(System::block_number());
333
		Balances::on_finalize(System::block_number());
334
		System::on_finalize(System::block_number());
335

            
336
		System::set_block_number(System::block_number() + 1);
337

            
338
		System::on_initialize(System::block_number());
339
		Balances::on_initialize(System::block_number());
340
		Evm::on_initialize(System::block_number());
341
		Timestamp::on_initialize(System::block_number());
342
		Treasury::on_initialize(System::block_number());
343
	}
344
}
345

            
346
9
pub(crate) fn events() -> Vec<RuntimeEvent> {
347
9
	System::events()
348
9
		.into_iter()
349
42
		.map(|r| r.event)
350
9
		.collect::<Vec<_>>()
351
9
}
352

            
353
#[macro_export]
354
macro_rules! assert_tail_eq {
355
	($tail:expr, $arr:expr) => {
356
		if $tail.len() != 0 {
357
			// 0-length always passes
358

            
359
			if $tail.len() > $arr.len() {
360
				similar_asserts::assert_eq!($tail, $arr); // will fail
361
			}
362

            
363
			let len_diff = $arr.len() - $tail.len();
364
			similar_asserts::assert_eq!($tail, $arr[len_diff..]);
365
		}
366
	};
367
}
368

            
369
/// Panics if an event is not found in the system log of events
370
#[macro_export]
371
macro_rules! assert_event_emitted {
372
	($event:expr) => {
373
		match &$event {
374
			e => {
375
				assert!(
376
35
					crate::mock::events().iter().find(|x| *x == e).is_some(),
377
					"Event {:?} was not found in events: \n {:#?}",
378
					e,
379
					crate::mock::events()
380
				);
381
			}
382
		}
383
	};
384
}