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::{format, vec::Vec};
25use frame_support::traits::BuildGenesisConfig;
26use sp_genesis_builder::{PresetId, Result as BuildResult};
27
28/// Build `GenesisConfig` from a JSON blob not using any defaults and store it in the storage. For
29/// more info refer to [`sp_genesis_builder::GenesisBuilder::build_state`].
30pub fn build_state<GC: BuildGenesisConfig>(json: Vec<u8>) -> BuildResult {
31 let gc =
32 serde_json::from_slice::<GC>(&json).map_err(|e| format!("Invalid JSON blob: {}", e))?;
33 <GC as BuildGenesisConfig>::build(&gc);
34 Ok(())
35}
36
37/// Get the default `GenesisConfig` as a JSON blob if `name` is None.
38///
39/// Query of named presets is delegetaed to provided `preset_for_name` closure. For more info refer
40/// to [`sp_genesis_builder::GenesisBuilder::get_preset`].
41pub fn get_preset<GC>(
42 name: &Option<PresetId>,
43 preset_for_name: impl FnOnce(&PresetId) -> Option<Vec<u8>>,
44) -> Option<Vec<u8>>
45where
46 GC: BuildGenesisConfig + Default,
47{
48 name.as_ref().map_or(
49 Some(
50 serde_json::to_string(&GC::default())
51 .expect("serialization to json is expected to work. qed.")
52 .into_bytes(),
53 ),
54 preset_for_name,
55 )
56}