frame_support/
genesis_builder_helper.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Helper functions for implementing [`sp_genesis_builder::GenesisBuilder`] for runtimes.
19//!
20//! Provides common logic. For more info refer to [`sp_genesis_builder::GenesisBuilder`].
21
22extern crate alloc;
23
24use alloc::vec::Vec;
25use frame_support::traits::BuildGenesisConfig;
26use sp_genesis_builder::{PresetId, Result as BuildResult};
27use sp_runtime::format_runtime_string;
28
29/// Build `GenesisConfig` from a JSON blob not using any defaults and store it in the storage. For
30/// more info refer to [`sp_genesis_builder::GenesisBuilder::build_state`].
31pub fn build_state<GC: BuildGenesisConfig>(json: Vec<u8>) -> BuildResult {
32	let gc = serde_json::from_slice::<GC>(&json)
33		.map_err(|e| format_runtime_string!("Invalid JSON blob: {}", e))?;
34	<GC as BuildGenesisConfig>::build(&gc);
35	Ok(())
36}
37
38/// Get the default `GenesisConfig` as a JSON blob if `name` is None.
39///
40/// Query of named presets is delegetaed to provided `preset_for_name` closure. For more info refer
41/// to [`sp_genesis_builder::GenesisBuilder::get_preset`].
42pub fn get_preset<GC>(
43	name: &Option<PresetId>,
44	preset_for_name: impl FnOnce(&sp_genesis_builder::PresetId) -> Option<alloc::vec::Vec<u8>>,
45) -> Option<Vec<u8>>
46where
47	GC: BuildGenesisConfig + Default,
48{
49	name.as_ref().map_or(
50		Some(
51			serde_json::to_string(&GC::default())
52				.expect("serialization to json is expected to work. qed.")
53				.into_bytes(),
54		),
55		preset_for_name,
56	)
57}