Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

templates: add genesis config presets for minimal/solochain #5868

Merged
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 2 additions & 18 deletions templates/minimal/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use minimal_template_runtime::{BalancesConfig, SudoConfig, WASM_BINARY};
use minimal_template_runtime::WASM_BINARY;
use polkadot_sdk::{
sc_service::{ChainType, Properties},
sp_keyring::AccountKeyring,
*,
};
use serde_json::{json, Value};

/// This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec = sc_service::GenericChainSpec;
Expand All @@ -38,21 +36,7 @@ pub fn development_config() -> Result<ChainSpec, String> {
.with_name("Development")
.with_id("dev")
.with_chain_type(ChainType::Development)
.with_genesis_config_patch(testnet_genesis())
.with_genesis_config_preset_name(sp_genesis_builder::DEV_RUNTIME_PRESET)
.with_properties(props())
.build())
}

/// Configure initial storage state for FRAME pallets.
fn testnet_genesis() -> Value {
use minimal_template_runtime::interface::{Balance, MinimumBalance};
use polkadot_sdk::polkadot_sdk_frame::traits::Get;
let endowment = <MinimumBalance as Get<Balance>>::get().max(1) * 1000;
let balances = AccountKeyring::iter()
.map(|a| (a.to_account_id(), endowment))
.collect::<Vec<_>>();
json!({
"balances": BalancesConfig { balances },
"sudo": SudoConfig { key: Some(AccountKeyring::Alice.to_account_id()) },
})
}
2 changes: 2 additions & 0 deletions templates/minimal/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ polkadot-sdk = { workspace = true, features = [
"pallet-transaction-payment-rpc-runtime-api",
"runtime",
] }
serde_json = { workspace = true, default-features = false }
michalkucharczyk marked this conversation as resolved.
Show resolved Hide resolved

# local pallet templates
pallet-minimal-template = { workspace = true }
Expand All @@ -37,4 +38,5 @@ std = [
"pallet-minimal-template/std",
"polkadot-sdk/std",
"scale-info/std",
"serde_json/std",
]
60 changes: 57 additions & 3 deletions templates/minimal/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

extern crate alloc;

use alloc::{vec, vec::Vec};
use alloc::vec::Vec;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use polkadot_sdk::{
polkadot_sdk_frame::{
Expand All @@ -36,6 +36,60 @@ use polkadot_sdk::{
*,
};

/// Provides getters for genesis configuration presets.
pub mod genesis_config_presets {
use crate::{
interface::{AccountId, Balance, MinimumBalance},
sp_genesis_builder::PresetId,
sp_keyring::AccountKeyring,
BalancesConfig, RuntimeGenesisConfig, SudoConfig,
};

use alloc::{vec, vec::Vec};
use polkadot_sdk::{sp_core::Get, sp_genesis_builder};
use serde_json::Value;

// Returns a genesis config preset populated with given parameters.
fn testnet_genesis(endowed_accounts: Vec<(AccountId, u64)>, root: AccountId) -> Value {
michalkucharczyk marked this conversation as resolved.
Show resolved Hide resolved
let config = RuntimeGenesisConfig {
balances: BalancesConfig { balances: endowed_accounts },
sudo: SudoConfig { key: Some(root) },
..Default::default()
};

serde_json::to_value(config).expect("Could not build genesis config.")
}

/// Returns a development genesis config preset.
pub fn development_config_genesis() -> Value {
let endowment = <MinimumBalance as Get<Balance>>::get().max(1) * 1000;
testnet_genesis(
AccountKeyring::iter()
.map(|a| (a.to_account_id(), endowment))
.collect::<Vec<_>>(),
AccountKeyring::Alice.to_account_id(),
)
}

/// Get the set of the available genesis config presets.
pub fn get_preset(id: &PresetId) -> Option<Vec<u8>> {
let patch = match id.try_into() {
Ok(sp_genesis_builder::DEV_RUNTIME_PRESET) => development_config_genesis(),
_ => return None,
};
Some(
serde_json::to_string(&patch)
.expect("serialization to json is expected to work. qed.")
.into_bytes(),
)
}

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

/// The runtime version.
#[runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
Expand Down Expand Up @@ -272,11 +326,11 @@ impl_runtime_apis! {
}

fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
get_preset::<RuntimeGenesisConfig>(id, |_| None)
get_preset::<RuntimeGenesisConfig>(id, self::genesis_config_presets::get_preset)
}

fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
vec![]
self::genesis_config_presets::preset_names()
}
}
}
Expand Down
5 changes: 2 additions & 3 deletions templates/solochain/node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ sp-consensus-aura = { workspace = true, default-features = true }
sc-consensus = { workspace = true, default-features = true }
sc-consensus-grandpa = { workspace = true, default-features = true }
sp-consensus-grandpa = { workspace = true, default-features = true }
sp-genesis-builder = { workspace = true, default-features = true }
sc-client-api = { workspace = true, default-features = true }
sc-basic-authorship = { workspace = true, default-features = true }

Expand Down Expand Up @@ -66,9 +67,7 @@ substrate-build-script-utils = { workspace = true, default-features = true }

[features]
default = ["std"]
std = [
"solochain-template-runtime/std",
]
std = ["solochain-template-runtime/std"]
# Dependencies that are only required if runtime benchmarking should be build.
runtime-benchmarks = [
"frame-benchmarking-cli/runtime-benchmarks",
Expand Down
96 changes: 4 additions & 92 deletions templates/solochain/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,9 @@
use sc_service::ChainType;
use solochain_template_runtime::{AccountId, Signature, WASM_BINARY};
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_consensus_grandpa::AuthorityId as GrandpaId;
use sp_core::{sr25519, Pair, Public};
use sp_runtime::traits::{IdentifyAccount, Verify};

// The URL for the telemetry server.
// const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
use solochain_template_runtime::WASM_BINARY;

/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec = sc_service::GenericChainSpec;

/// Generate a crypto pair from seed.
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None)
.expect("static values are valid; qed")
.public()
}

type AccountPublic = <Signature as Verify>::Signer;

/// Generate an account ID from seed.
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}

/// Generate an Aura authority key.
pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {
(get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))
}

pub fn development_config() -> Result<ChainSpec, String> {
michalkucharczyk marked this conversation as resolved.
Show resolved Hide resolved
Ok(ChainSpec::builder(
WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?,
Expand All @@ -41,77 +12,18 @@ pub fn development_config() -> Result<ChainSpec, String> {
.with_name("Development")
.with_id("dev")
.with_chain_type(ChainType::Development)
.with_genesis_config_patch(testnet_genesis(
// Initial PoA authorities
vec![authority_keys_from_seed("Alice")],
// Sudo account
get_account_id_from_seed::<sr25519::Public>("Alice"),
// Pre-funded accounts
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
],
true,
))
.with_genesis_config_preset_name(sp_genesis_builder::DEV_RUNTIME_PRESET)
.build())
}

pub fn local_testnet_config() -> Result<ChainSpec, String> {
pub fn local_config() -> Result<ChainSpec, String> {
Ok(ChainSpec::builder(
WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?,
None,
)
.with_name("Local Testnet")
.with_id("local_testnet")
.with_chain_type(ChainType::Local)
.with_genesis_config_patch(testnet_genesis(
// Initial PoA authorities
vec![authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob")],
// Sudo account
get_account_id_from_seed::<sr25519::Public>("Alice"),
// Pre-funded accounts
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Charlie"),
get_account_id_from_seed::<sr25519::Public>("Dave"),
get_account_id_from_seed::<sr25519::Public>("Eve"),
get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
],
true,
))
.with_genesis_config_preset_name(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET)
.build())
}

/// Configure initial storage state for FRAME modules.
fn testnet_genesis(
initial_authorities: Vec<(AuraId, GrandpaId)>,
root_key: AccountId,
endowed_accounts: Vec<AccountId>,
_enable_println: bool,
) -> serde_json::Value {
serde_json::json!({
"balances": {
// Configure endowed accounts with initial balance of 1 << 60.
"balances": endowed_accounts.iter().cloned().map(|k| (k, 1u64 << 60)).collect::<Vec<_>>(),
},
"aura": {
"authorities": initial_authorities.iter().map(|x| (x.0.clone())).collect::<Vec<_>>(),
},
"grandpa": {
"authorities": initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect::<Vec<_>>(),
},
"sudo": {
// Assign network admin rights.
"key": Some(root_key),
},
})
}
2 changes: 1 addition & 1 deletion templates/solochain/node/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl SubstrateCli for Cli {
fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(match id {
"dev" => Box::new(chain_spec::development_config()?),
"" | "local" => Box::new(chain_spec::local_testnet_config()?),
"" | "local" => Box::new(chain_spec::local_config()?),
path =>
Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?),
})
Expand Down
4 changes: 4 additions & 0 deletions templates/solochain/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ scale-info = { features = [
"derive",
"serde",
], workspace = true }
serde_json = { workspace = true, default-features = false }

# frame
frame-support = { features = ["experimental"], workspace = true }
Expand All @@ -45,6 +46,7 @@ sp-consensus-aura = { features = [
sp-consensus-grandpa = { features = [
"serde",
], workspace = true }
sp-keyring = { workspace = true }
sp-core = { features = [
"serde",
], workspace = true }
Expand Down Expand Up @@ -114,6 +116,8 @@ std = [
"sp-transaction-pool/std",
"sp-version/std",

"serde_json/std",
"sp-keyring/std",
"substrate-wasm-builder",
]

Expand Down
6 changes: 3 additions & 3 deletions templates/solochain/runtime/src/apis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
// For more information, please refer to <http://unlicense.org>

// External crates imports
use alloc::{vec, vec::Vec};
use alloc::vec::Vec;
use frame_support::{
genesis_builder_helper::{build_state, get_preset},
weights::Weight,
Expand Down Expand Up @@ -285,11 +285,11 @@ impl_runtime_apis! {
}

fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
get_preset::<RuntimeGenesisConfig>(id, |_| None)
get_preset::<RuntimeGenesisConfig>(id, crate::genesis_config_presets::get_preset)
}

fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
vec![]
crate::genesis_config_presets::preset_names()
}
}
}
Loading