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;
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
668
construct_runtime!(
51
	pub enum Runtime	{
52
		System: frame_system,
53
		Balances: pallet_balances,
54
		Evm: pallet_evm,
55
		Timestamp: pallet_timestamp,
56
		Treasury: pallet_treasury,
57
		CouncilCollective:
58
			pallet_collective::<Instance1>,
59
	}
60
1795
);
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
}
97

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

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

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

            
123
pub type PCall = CollectivePrecompileCall<Runtime, pallet_collective::Instance1>;
124

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

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

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

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

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

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

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

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

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

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

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

            
259
/// Build test externalities, prepopulated with data for testing democracy precompiles
260
pub(crate) struct ExtBuilder {
261
	/// Endowed accounts with balances
262
	balances: Vec<(AccountId, Balance)>,
263
	/// Collective members
264
	collective: Vec<AccountId>,
265
}
266

            
267
impl Default for ExtBuilder {
268
23
	fn default() -> ExtBuilder {
269
23
		ExtBuilder {
270
23
			balances: vec![],
271
23
			collective: vec![Bob.into(), Charlie.into()],
272
23
		}
273
23
	}
274
}
275

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

            
284
	/// Set members of the collective
285
	#[allow(unused)]
286
	pub(crate) fn with_collective(mut self, collective: Vec<AccountId>) -> Self {
287
		self.collective = collective;
288
		self
289
	}
290

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

            
298
23
		pallet_balances::GenesisConfig::<Runtime> {
299
23
			balances: self.balances.clone(),
300
23
		}
301
23
		.assimilate_storage(&mut t)
302
23
		.expect("Pallet balances storage can be assimilated");
303
23

            
304
23
		pallet_collective::GenesisConfig::<Runtime, pallet_collective::Instance1> {
305
23
			members: self.collective.clone(),
306
23
			phantom: Default::default(),
307
23
		}
308
23
		.assimilate_storage(&mut t)
309
23
		.expect("Pallet collective storage can be assimilated");
310
23

            
311
23
		let mut ext = sp_io::TestExternalities::new(t);
312
23
		ext.execute_with(|| {
313
23
			System::set_block_number(1);
314
23
		});
315
23
		ext
316
23
	}
317
}
318

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

            
331
		System::set_block_number(System::block_number() + 1);
332

            
333
		System::on_initialize(System::block_number());
334
		Balances::on_initialize(System::block_number());
335
		Evm::on_initialize(System::block_number());
336
		Timestamp::on_initialize(System::block_number());
337
		Treasury::on_initialize(System::block_number());
338
	}
339
}
340

            
341
9
pub(crate) fn events() -> Vec<RuntimeEvent> {
342
9
	System::events()
343
9
		.into_iter()
344
42
		.map(|r| r.event)
345
9
		.collect::<Vec<_>>()
346
9
}
347

            
348
#[macro_export]
349
macro_rules! assert_tail_eq {
350
	($tail:expr, $arr:expr) => {
351
		if $tail.len() != 0 {
352
			// 0-length always passes
353

            
354
			if $tail.len() > $arr.len() {
355
				similar_asserts::assert_eq!($tail, $arr); // will fail
356
			}
357

            
358
			let len_diff = $arr.len() - $tail.len();
359
			similar_asserts::assert_eq!($tail, $arr[len_diff..]);
360
		}
361
	};
362
}
363

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