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
205
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
205
);
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
	type CreateOriginFilter = ();
169
	type CreateInnerOriginFilter = ();
170
}
171

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
339
		System::set_block_number(System::block_number() + 1);
340

            
341
		System::on_initialize(System::block_number());
342
		Balances::on_initialize(System::block_number());
343
		Evm::on_initialize(System::block_number());
344
		Timestamp::on_initialize(System::block_number());
345
		Treasury::on_initialize(System::block_number());
346
	}
347
}
348

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

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

            
362
			if $tail.len() > $arr.len() {
363
				similar_asserts::assert_eq!($tail, $arr); // will fail
364
			}
365

            
366
			let len_diff = $arr.len() - $tail.len();
367
			similar_asserts::assert_eq!($tail, $arr[len_diff..]);
368
		}
369
	};
370
}
371

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