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
extern crate alloc;
18

            
19
use crate::{
20
	currency::GLMR, currency::SUPPLY_FACTOR, AccountId, AuthorFilterConfig, AuthorMappingConfig,
21
	Balance, Balances, BalancesConfig, BridgeKusamaGrandpaConfig, BridgeKusamaMessagesConfig,
22
	BridgeKusamaParachainsConfig, BridgeXcmOverMoonriverConfig, CrowdloanRewardsConfig, EVMConfig,
23
	EligibilityValue, EthereumChainIdConfig, EthereumConfig, EvmForeignAssetsConfig, InflationInfo,
24
	MaintenanceModeConfig, OpenTechCommitteeCollectiveConfig, ParachainInfoConfig,
25
	ParachainStakingConfig, PolkadotXcmConfig, Precompiles, Range, RuntimeGenesisConfig,
26
	TransactionPaymentConfig, TreasuryCouncilCollectiveConfig, XcmWeightTraderConfig, HOURS,
27
};
28
use alloc::{vec, vec::Vec};
29
use bp_messages::MessagesOperatingMode;
30
use bp_runtime::BasicOperatingMode;
31
use cumulus_primitives_core::ParaId;
32
use fp_evm::GenesisAccount;
33
use frame_support::pallet_prelude::PalletInfoAccess;
34
use nimbus_primitives::NimbusId;
35
use pallet_moonbeam_foreign_assets::EvmForeignAssetInfo;
36
use pallet_transaction_payment::Multiplier;
37
use pallet_xcm_weight_trader::XcmWeightTraderAssetInfo;
38
use sp_genesis_builder::PresetId;
39
use sp_keyring::Sr25519Keyring;
40
use sp_runtime::{Perbill, Percent};
41
use xcm::prelude::{GlobalConsensus, Junctions, Location, NetworkId, PalletInstance, Parachain};
42

            
43
const COLLATOR_COMMISSION: Perbill = Perbill::from_percent(20);
44
const PARACHAIN_BOND_RESERVE_PERCENT: Percent = Percent::from_percent(30);
45
const BLOCKS_PER_ROUND: u32 = 6 * HOURS;
46
const BLOCKS_PER_YEAR: u32 = 31_557_600 / 12;
47
const NUM_SELECTED_CANDIDATES: u32 = 8;
48

            
49
pub fn moonbeam_inflation_config() -> InflationInfo<Balance> {
50
	fn to_round_inflation(annual: Range<Perbill>) -> Range<Perbill> {
51
		use pallet_parachain_staking::inflation::perbill_annual_to_perbill_round;
52
		perbill_annual_to_perbill_round(
53
			annual,
54
			// rounds per year
55
			BLOCKS_PER_YEAR / BLOCKS_PER_ROUND,
56
		)
57
	}
58
	let annual = Range {
59
		min: Perbill::from_percent(4),
60
		ideal: Perbill::from_percent(5),
61
		max: Perbill::from_percent(5),
62
	};
63
	InflationInfo {
64
		// staking expectations
65
		expect: Range {
66
			min: 100_000 * GLMR * SUPPLY_FACTOR,
67
			ideal: 200_000 * GLMR * SUPPLY_FACTOR,
68
			max: 500_000 * GLMR * SUPPLY_FACTOR,
69
		},
70
		// annual inflation
71
		annual,
72
		round: to_round_inflation(annual),
73
	}
74
}
75

            
76
pub fn testnet_genesis(
77
	treasury_council_members: Vec<AccountId>,
78
	open_tech_committee_members: Vec<AccountId>,
79
	candidates: Vec<(AccountId, NimbusId, Balance)>,
80
	delegations: Vec<(AccountId, AccountId, Balance, Percent)>,
81
	endowed_accounts: Vec<AccountId>,
82
	crowdloan_fund_pot: Balance,
83
	para_id: ParaId,
84
	chain_id: u64,
85
) -> serde_json::Value {
86
	// This is the simplest bytecode to revert without returning any data.
87
	// We will pre-deploy it under all of our precompiles to ensure they can be called from
88
	// within contracts.
89
	// (PUSH1 0x00 PUSH1 0x00 REVERT)
90
	let revert_bytecode = vec![0x60, 0x00, 0x60, 0x00, 0xFD];
91

            
92
	let config = RuntimeGenesisConfig {
93
		system: Default::default(),
94
		balances: BalancesConfig {
95
			balances: endowed_accounts
96
				.iter()
97
				.cloned()
98
				.map(|k| (k, 1 << 110))
99
				.collect(),
100
		},
101
		crowdloan_rewards: CrowdloanRewardsConfig {
102
			funded_amount: crowdloan_fund_pot,
103
		},
104
		parachain_info: ParachainInfoConfig {
105
			parachain_id: para_id,
106
			..Default::default()
107
		},
108
		ethereum_chain_id: EthereumChainIdConfig {
109
			chain_id,
110
			..Default::default()
111
		},
112
		evm: EVMConfig {
113
			// We need _some_ code inserted at the precompile address so that
114
			// the evm will actually call the address.
115
			accounts: Precompiles::used_addresses()
116
				.map(|addr| {
117
					(
118
						addr.into(),
119
						GenesisAccount {
120
							nonce: Default::default(),
121
							balance: Default::default(),
122
							storage: Default::default(),
123
							code: revert_bytecode.clone(),
124
						},
125
					)
126
				})
127
				.collect(),
128
			..Default::default()
129
		},
130
		ethereum: EthereumConfig {
131
			..Default::default()
132
		},
133
		parachain_staking: ParachainStakingConfig {
134
			candidates: candidates
135
				.iter()
136
				.cloned()
137
				.map(|(account, _, bond)| (account, bond))
138
				.collect(),
139
			delegations,
140
			inflation_config: moonbeam_inflation_config(),
141
			collator_commission: COLLATOR_COMMISSION,
142
			parachain_bond_reserve_percent: PARACHAIN_BOND_RESERVE_PERCENT,
143
			blocks_per_round: BLOCKS_PER_ROUND,
144
			num_selected_candidates: NUM_SELECTED_CANDIDATES,
145
		},
146
		treasury_council_collective: TreasuryCouncilCollectiveConfig {
147
			phantom: Default::default(),
148
			members: treasury_council_members,
149
		},
150
		open_tech_committee_collective: OpenTechCommitteeCollectiveConfig {
151
			phantom: Default::default(),
152
			members: open_tech_committee_members,
153
		},
154
		author_filter: AuthorFilterConfig {
155
			eligible_count: EligibilityValue::new_unchecked(50),
156
			..Default::default()
157
		},
158
		author_mapping: AuthorMappingConfig {
159
			mappings: candidates
160
				.iter()
161
				.cloned()
162
				.map(|(account_id, author_id, _)| (author_id, account_id))
163
				.collect(),
164
		},
165
		proxy_genesis_companion: Default::default(),
166
		treasury: Default::default(),
167
		maintenance_mode: MaintenanceModeConfig {
168
			start_in_maintenance_mode: false,
169
			..Default::default()
170
		},
171
		polkadot_xcm: PolkadotXcmConfig {
172
			supported_version: vec![
173
				// Required for bridging Moonbeam with Moonriver
174
				(
175
					bp_moonriver::GlobalConsensusLocation::get(),
176
					xcm::latest::VERSION,
177
				),
178
			],
179
			..Default::default()
180
		},
181
		transaction_payment: TransactionPaymentConfig {
182
			multiplier: Multiplier::from(8u128),
183
			..Default::default()
184
		},
185
		evm_foreign_assets: EvmForeignAssetsConfig {
186
			assets: vec![EvmForeignAssetInfo {
187
				asset_id: 1001,
188
				name: b"xcMOVR".to_vec().try_into().expect("Invalid asset name"),
189
				symbol: b"xcMOVR".to_vec().try_into().expect("Invalid asset symbol"),
190
				decimals: 18,
191
				xcm_location: Location::new(
192
					2,
193
					[
194
						GlobalConsensus(crate::bridge_config::KusamaGlobalConsensusNetwork::get()),
195
						Parachain(<bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID),
196
						PalletInstance(<Balances as PalletInfoAccess>::index() as u8),
197
					],
198
				),
199
			}],
200
			_phantom: Default::default(),
201
		},
202
		xcm_weight_trader: XcmWeightTraderConfig {
203
			assets: vec![XcmWeightTraderAssetInfo {
204
				location: Location::new(
205
					2,
206
					[
207
						GlobalConsensus(crate::bridge_config::KusamaGlobalConsensusNetwork::get()),
208
						Parachain(<bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID),
209
						PalletInstance(<Balances as PalletInfoAccess>::index() as u8),
210
					],
211
				),
212
				relative_price: GLMR,
213
			}],
214
			_phantom: Default::default(),
215
		},
216
		bridge_kusama_grandpa: BridgeKusamaGrandpaConfig {
217
			owner: Some(endowed_accounts[0]),
218
			init_data: None,
219
		},
220
		bridge_kusama_parachains: BridgeKusamaParachainsConfig {
221
			owner: Some(endowed_accounts[0]),
222
			operating_mode: BasicOperatingMode::Normal,
223
			..Default::default()
224
		},
225
		bridge_kusama_messages: BridgeKusamaMessagesConfig {
226
			owner: Some(endowed_accounts[0]),
227
			opened_lanes: vec![],
228
			operating_mode: MessagesOperatingMode::Basic(BasicOperatingMode::Normal),
229
			_phantom: Default::default(),
230
		},
231
		bridge_xcm_over_moonriver: BridgeXcmOverMoonriverConfig {
232
			opened_bridges: vec![(
233
				Location::new(
234
					1,
235
					[Parachain(
236
						<bp_moonbeam::Moonbeam as bp_runtime::Parachain>::PARACHAIN_ID,
237
					)],
238
				),
239
				Junctions::from([
240
					NetworkId::Kusama.into(),
241
					Parachain(<bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID),
242
				]),
243
				Some(Default::default()),
244
			)],
245
			_phantom: Default::default(),
246
		},
247
	};
248

            
249
	serde_json::to_value(&config).expect("Could not build genesis config.")
250
}
251

            
252
/// Generate a chain spec for use with the development service.
253
pub fn development() -> serde_json::Value {
254
	testnet_genesis(
255
		// Treasury Council members: Baltathar, Charleth and Dorothy
256
		vec![
257
			AccountId::from(sp_core::hex2array!(
258
				"3Cd0A705a2DC65e5b1E1205896BaA2be8A07c6e0"
259
			)),
260
			AccountId::from(sp_core::hex2array!(
261
				"798d4Ba9baf0064Ec19eB4F0a1a45785ae9D6DFc"
262
			)),
263
			AccountId::from(sp_core::hex2array!(
264
				"773539d4Ac0e786233D90A233654ccEE26a613D9"
265
			)),
266
		],
267
		// Open Tech committee members: Alith and Baltathar
268
		vec![
269
			AccountId::from(sp_core::hex2array!(
270
				"f24FF3a9CF04c71Dbc94D0b566f7A27B94566cac"
271
			)),
272
			AccountId::from(sp_core::hex2array!(
273
				"3Cd0A705a2DC65e5b1E1205896BaA2be8A07c6e0"
274
			)),
275
		],
276
		// Collator Candidate: Alice -> Alith
277
		vec![(
278
			AccountId::from(sp_core::hex2array!(
279
				"f24FF3a9CF04c71Dbc94D0b566f7A27B94566cac"
280
			)),
281
			NimbusId::from(Sr25519Keyring::Alice.public()),
282
			20_000 * GLMR * SUPPLY_FACTOR,
283
		)],
284
		// Delegations
285
		vec![],
286
		vec![
287
			AccountId::from(sp_core::hex2array!(
288
				"f24FF3a9CF04c71Dbc94D0b566f7A27B94566cac"
289
			)),
290
			AccountId::from(sp_core::hex2array!(
291
				"3Cd0A705a2DC65e5b1E1205896BaA2be8A07c6e0"
292
			)),
293
			AccountId::from(sp_core::hex2array!(
294
				"798d4Ba9baf0064Ec19eB4F0a1a45785ae9D6DFc"
295
			)),
296
			AccountId::from(sp_core::hex2array!(
297
				"773539d4Ac0e786233D90A233654ccEE26a613D9"
298
			)),
299
		],
300
		1_500_000 * GLMR * SUPPLY_FACTOR,
301
		Default::default(), // para_id
302
		1281,               //ChainId
303
	)
304
}
305

            
306
/// Provides the JSON representation of predefined genesis config for given `id`.
307
pub fn get_preset(id: &PresetId) -> Option<Vec<u8>> {
308
	let patch = match id.as_str() {
309
		sp_genesis_builder::DEV_RUNTIME_PRESET => development(),
310
		_ => return None,
311
	};
312
	Some(
313
		serde_json::to_string(&patch)
314
			.expect("serialization to json is expected to work. qed.")
315
			.into_bytes(),
316
	)
317
}
318

            
319
/// List of supported presets.
320
pub fn preset_names() -> Vec<PresetId> {
321
	vec![PresetId::from(sp_genesis_builder::DEV_RUNTIME_PRESET)]
322
}