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
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
);
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 Runner = pallet_evm::runner::stack::Runner<Self>;
154
	type PrecompilesType = Precompiles<Self>;
155
	type PrecompilesValue = PrecompilesValue;
156
	type ChainId = ();
157
	type OnChargeTransaction = ();
158
	type BlockGasLimit = BlockGasLimit;
159
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
160
	type FindAuthor = ();
161
	type OnCreate = ();
162
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
163
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
164
	type Timestamp = Timestamp;
165
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
166
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
167
	type CreateOriginFilter = ();
168
	type CreateInnerOriginFilter = ();
169
}
170

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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