Update template triggered by workflow_dispatch

This commit is contained in:
Template Bot
2024-04-13 11:33:35 +00:00
parent f8eaad8fb2
commit b218abb9bc
17 changed files with 10880 additions and 0 deletions
Generated
+9732
View File
File diff suppressed because it is too large Load Diff
+57
View File
@@ -0,0 +1,57 @@
[workspace.package]
license = "MIT-0"
authors = ["Parity Technologies <admin@parity.io>"]
homepage = "https://substrate.io"
repository = "https://github.com/paritytech/polkadot-sdk-minimal-template.git"
edition = "2021"
[workspace]
members = [
"node",
"pallets/template",
"runtime",
]
resolver = "2"
[workspace.lints.rust]
suspicious_double_ref_op = { level = "allow", priority = 2 }
[workspace.lints.clippy]
all = { level = "allow", priority = 0 }
correctness = { level = "warn", priority = 1 }
complexity = { level = "warn", priority = 1 }
if-same-then-else = { level = "allow", priority = 2 }
zero-prefixed-literal = { level = "allow", priority = 2 } # 00_1000_000
type_complexity = { level = "allow", priority = 2 } # raison d'etre
nonminimal-bool = { level = "allow", priority = 2 } # maybe
borrowed-box = { level = "allow", priority = 2 } # Reasonable to fix this one
too-many-arguments = { level = "allow", priority = 2 } # (Turning this on would lead to)
needless-lifetimes = { level = "allow", priority = 2 } # generated code
unnecessary_cast = { level = "allow", priority = 2 } # Types may change
identity-op = { level = "allow", priority = 2 } # One case where we do 0 +
useless_conversion = { level = "allow", priority = 2 } # Types may change
unit_arg = { level = "allow", priority = 2 } # stylistic
option-map-unit-fn = { level = "allow", priority = 2 } # stylistic
bind_instead_of_map = { level = "allow", priority = 2 } # stylistic
erasing_op = { level = "allow", priority = 2 } # E.g. 0 * DOLLARS
eq_op = { level = "allow", priority = 2 } # In tests we test equality.
while_immutable_condition = { level = "allow", priority = 2 } # false positives
needless_option_as_deref = { level = "allow", priority = 2 } # false positives
derivable_impls = { level = "allow", priority = 2 } # false positives
stable_sort_primitive = { level = "allow", priority = 2 } # prefer stable sort
extra-unused-type-parameters = { level = "allow", priority = 2 } # stylistic
default_constructed_unit_structs = { level = "allow", priority = 2 } # stylistic
[workspace.dependencies]
polkavm = "0.9.3"
polkavm-linker = "0.9.2"
polkavm-derive = "0.9.1"
log = { version = "0.4.20", default-features = false }
quote = { version = "1.0.33" }
serde = { version = "1.0.197", default-features = false }
serde-big-array = { version = "0.3.2" }
serde_derive = { version = "1.0.117" }
serde_json = { version = "1.0.114", default-features = false }
serde_yaml = { version = "0.9" }
syn = { version = "2.0.50" }
thiserror = { version = "1.0.48" }
View File
+56
View File
@@ -0,0 +1,56 @@
[package]
name = "minimal-template-node"
description = "A miniaml Substrate-based Substrate node, ready for hacking. (polkadot v1.9.0)"
version = "0.1.0"
license = "MIT-0"
authors.workspace = true
homepage.workspace = true
repository.workspace = true
edition.workspace = true
publish = false
build = "build.rs"
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
clap = { version = "4.5.1", features = ["derive"] }
futures = { version = "0.3.21", features = ["thread-pool"] }
futures-timer = "3.0.1"
jsonrpsee = { version = "0.22", features = ["server"] }
serde_json = { workspace = true, default-features = true }
sc-cli = { version = "0.39.0" }
sc-executor = { version = "0.35.0" }
sc-network = { version = "0.37.0" }
sc-service = { version = "0.38.0" }
sc-telemetry = { version = "17.0.0" }
sc-transaction-pool = { version = "31.0.0" }
sc-transaction-pool-api = { version = "31.0.0" }
sc-consensus = { version = "0.36.0" }
sc-consensus-manual-seal = { version = "0.38.0" }
sc-rpc-api = { version = "0.36.0" }
sc-basic-authorship = { version = "0.37.0" }
sc-offchain = { version = "32.0.0" }
sc-client-api = { version = "31.0.0" }
sp-timestamp = { version = "29.0.0" }
sp-keyring = { version = "34.0.0" }
sp-api = { version = "29.0.0" }
sp-blockchain = { version = "31.0.0" }
sp-block-builder = { version = "29.0.0" }
sp-io = { version = "33.0.0" }
sp-runtime = { version = "34.0.0" }
substrate-frame-rpc-system = { version = "31.0.0" }
# Once the native runtime is gone, there should be little to no dependency on FRAME here, and
# certainly no dependency on the runtime.
frame = { version = "0.1.1", package = "polkadot-sdk-frame", features = ["experimental", "runtime"] }
runtime = { package = "minimal-template-runtime", path = "../runtime", version = "0.1.0" }
[build-dependencies]
substrate-build-script-utils = { version = "11.0.0" }
[features]
default = []
+23
View File
@@ -0,0 +1,23 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() {
generate_cargo_keys();
rerun_if_git_head_changed();
}
+55
View File
@@ -0,0 +1,55 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use runtime::{BalancesConfig, SudoConfig, WASM_BINARY};
use sc_service::{ChainType, Properties};
use serde_json::{json, Value};
use sp_keyring::AccountKeyring;
/// This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec = sc_service::GenericChainSpec<()>;
fn props() -> Properties {
let mut properties = Properties::new();
properties.insert("tokenDecimals".to_string(), 0.into());
properties.insert("tokenSymbol".to_string(), "MINI".into());
properties
}
pub fn development_config() -> Result<ChainSpec, String> {
Ok(ChainSpec::builder(WASM_BINARY.expect("Development wasm not available"), Default::default())
.with_name("Development")
.with_id("dev")
.with_chain_type(ChainType::Development)
.with_genesis_config_patch(testnet_genesis())
.with_properties(props())
.build())
}
/// Configure initial storage state for FRAME pallets.
fn testnet_genesis() -> Value {
use frame::traits::Get;
use runtime::interface::{Balance, MinimumBalance};
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()) },
})
}
+81
View File
@@ -0,0 +1,81 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use sc_cli::RunCmd;
#[derive(Debug, Clone)]
pub enum Consensus {
ManualSeal(u64),
InstantSeal,
}
impl std::str::FromStr for Consensus {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(if s == "instant-seal" {
Consensus::InstantSeal
} else if let Some(block_time) = s.strip_prefix("manual-seal-") {
Consensus::ManualSeal(block_time.parse().map_err(|_| "invalid block time")?)
} else {
return Err("incorrect consensus identifier".into())
})
}
}
#[derive(Debug, clap::Parser)]
pub struct Cli {
#[command(subcommand)]
pub subcommand: Option<Subcommand>,
#[clap(long, default_value = "manual-seal-3000")]
pub consensus: Consensus,
#[clap(flatten)]
pub run: RunCmd,
}
#[derive(Debug, clap::Subcommand)]
pub enum Subcommand {
/// Key management cli utilities
#[command(subcommand)]
Key(sc_cli::KeySubcommand),
/// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd),
/// Validate blocks.
CheckBlock(sc_cli::CheckBlockCmd),
/// Export blocks.
ExportBlocks(sc_cli::ExportBlocksCmd),
/// Export the state of a given block into a chain spec.
ExportState(sc_cli::ExportStateCmd),
/// Import blocks.
ImportBlocks(sc_cli::ImportBlocksCmd),
/// Remove the whole chain.
PurgeChain(sc_cli::PurgeChainCmd),
/// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd),
/// Db meta columns information.
ChainInfo(sc_cli::ChainInfoCmd),
}
+126
View File
@@ -0,0 +1,126 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{
chain_spec,
cli::{Cli, Subcommand},
service,
};
use sc_cli::SubstrateCli;
use sc_service::PartialComponents;
#[cfg(feature = "try-runtime")]
use try_runtime_cli::block_building_info::timestamp_with_aura_info;
impl SubstrateCli for Cli {
fn impl_name() -> String {
"Substrate Node".into()
}
fn impl_version() -> String {
env!("SUBSTRATE_CLI_IMPL_VERSION").into()
}
fn description() -> String {
env!("CARGO_PKG_DESCRIPTION").into()
}
fn author() -> String {
env!("CARGO_PKG_AUTHORS").into()
}
fn support_url() -> String {
"support.anonymous.an".into()
}
fn copyright_start_year() -> i32 {
2017
}
fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(match id {
"dev" => Box::new(chain_spec::development_config()?),
path =>
Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?),
})
}
}
/// Parse and run command line arguments
pub fn run() -> sc_cli::Result<()> {
let cli = Cli::from_args();
match &cli.subcommand {
Some(Subcommand::Key(cmd)) => cmd.run(&cli),
Some(Subcommand::BuildSpec(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
},
Some(Subcommand::CheckBlock(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, import_queue, .. } =
service::new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
Some(Subcommand::ExportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, .. } = service::new_partial(&config)?;
Ok((cmd.run(client, config.database), task_manager))
})
},
Some(Subcommand::ExportState(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, .. } = service::new_partial(&config)?;
Ok((cmd.run(client, config.chain_spec), task_manager))
})
},
Some(Subcommand::ImportBlocks(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, import_queue, .. } =
service::new_partial(&config)?;
Ok((cmd.run(client, import_queue), task_manager))
})
},
Some(Subcommand::PurgeChain(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.database))
},
Some(Subcommand::Revert(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
let PartialComponents { client, task_manager, backend, .. } =
service::new_partial(&config)?;
Ok((cmd.run(client, backend, None), task_manager))
})
},
Some(Subcommand::ChainInfo(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run::<runtime::interface::OpaqueBlock>(&config))
},
None => {
let runner = cli.create_runner(&cli.run)?;
runner.run_node_until_exit(|config| async move {
service::new_full(config, cli.consensus).map_err(sc_cli::Error::Service)
})
},
}
}
+21
View File
@@ -0,0 +1,21 @@
// This file is part of Polkadot Sdk.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod chain_spec;
pub(crate) mod cli;
pub mod rpc;
pub mod service;
+29
View File
@@ -0,0 +1,29 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Substrate Node Template CLI library.
#![warn(missing_docs)]
mod chain_spec;
mod cli;
mod command;
mod rpc;
mod service;
fn main() -> sc_cli::Result<()> {
command::run()
}
+66
View File
@@ -0,0 +1,66 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A collection of node-specific RPC methods.
//! Substrate provides the `sc-rpc` crate, which defines the core RPC layer
//! used by Substrate nodes. This file extends those RPC definitions with
//! capabilities that are specific to this project's runtime configuration.
#![warn(missing_docs)]
use jsonrpsee::RpcModule;
use runtime::interface::{AccountId, Nonce, OpaqueBlock};
use sc_transaction_pool_api::TransactionPool;
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
use std::sync::Arc;
use substrate_frame_rpc_system::{System, SystemApiServer};
pub use sc_rpc_api::DenyUnsafe;
/// Full client dependencies.
pub struct FullDeps<C, P> {
/// The client instance to use.
pub client: Arc<C>,
/// Transaction pool instance.
pub pool: Arc<P>,
/// Whether to deny unsafe calls
pub deny_unsafe: DenyUnsafe,
}
/// Instantiate all full RPC extensions.
pub fn create_full<C, P>(
deps: FullDeps<C, P>,
) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>
where
C: Send
+ Sync
+ 'static
+ sp_api::ProvideRuntimeApi<OpaqueBlock>
+ HeaderBackend<OpaqueBlock>
+ HeaderMetadata<OpaqueBlock, Error = BlockChainError>
+ 'static,
C::Api: sp_block_builder::BlockBuilder<OpaqueBlock>,
C::Api: substrate_frame_rpc_system::AccountNonceApi<OpaqueBlock, AccountId, Nonce>,
P: TransactionPool + 'static,
{
let mut module = RpcModule::new(());
let FullDeps { client, pool, deny_unsafe } = deps;
module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?;
Ok(module)
}
+252
View File
@@ -0,0 +1,252 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use futures::FutureExt;
use runtime::{self, interface::OpaqueBlock as Block, RuntimeApi};
use sc_client_api::backend::Backend;
use sc_executor::WasmExecutor;
use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
use sc_telemetry::{Telemetry, TelemetryWorker};
use sc_transaction_pool_api::OffchainTransactionPoolFactory;
use std::sync::Arc;
use crate::cli::Consensus;
#[cfg(feature = "runtime-benchmarks")]
type HostFunctions =
(sp_io::SubstrateHostFunctions, frame_benchmarking::benchmarking::HostFunctions);
#[cfg(not(feature = "runtime-benchmarks"))]
type HostFunctions = sp_io::SubstrateHostFunctions;
pub(crate) type FullClient =
sc_service::TFullClient<Block, RuntimeApi, WasmExecutor<HostFunctions>>;
type FullBackend = sc_service::TFullBackend<Block>;
type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;
/// Assembly of PartialComponents (enough to run chain ops subcommands)
pub type Service = sc_service::PartialComponents<
FullClient,
FullBackend,
FullSelectChain,
sc_consensus::DefaultImportQueue<Block>,
sc_transaction_pool::FullPool<Block, FullClient>,
Option<Telemetry>,
>;
pub fn new_partial(config: &Configuration) -> Result<Service, ServiceError> {
let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?;
let telemetry = worker.handle().new_telemetry(endpoints);
Ok((worker, telemetry))
})
.transpose()?;
let executor = sc_service::new_wasm_executor(&config);
let (client, backend, keystore_container, task_manager) =
sc_service::new_full_parts::<Block, RuntimeApi, _>(
config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
executor,
)?;
let client = Arc::new(client);
let telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", None, worker.run());
telemetry
});
let select_chain = sc_consensus::LongestChain::new(backend.clone());
let transaction_pool = sc_transaction_pool::BasicPool::new_full(
config.transaction_pool.clone(),
config.role.is_authority().into(),
config.prometheus_registry(),
task_manager.spawn_essential_handle(),
client.clone(),
);
let import_queue = sc_consensus_manual_seal::import_queue(
Box::new(client.clone()),
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
);
Ok(sc_service::PartialComponents {
client,
backend,
task_manager,
import_queue,
keystore_container,
select_chain,
transaction_pool,
other: (telemetry),
})
}
/// Builds a new service for a full client.
pub fn new_full(config: Configuration, consensus: Consensus) -> Result<TaskManager, ServiceError> {
let sc_service::PartialComponents {
client,
backend,
mut task_manager,
import_queue,
keystore_container,
select_chain,
transaction_pool,
other: mut telemetry,
} = new_partial(&config)?;
let net_config = sc_network::config::FullNetworkConfiguration::new(&config.network);
let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =
sc_service::build_network(sc_service::BuildNetworkParams {
config: &config,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
spawn_handle: task_manager.spawn_handle(),
import_queue,
net_config,
block_announce_validator_builder: None,
warp_sync_params: None,
block_relay: None,
})?;
if config.offchain_worker.enabled {
task_manager.spawn_handle().spawn(
"offchain-workers-runner",
"offchain-worker",
sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
runtime_api_provider: client.clone(),
is_validator: config.role.is_authority(),
keystore: Some(keystore_container.keystore()),
offchain_db: backend.offchain_storage(),
transaction_pool: Some(OffchainTransactionPoolFactory::new(
transaction_pool.clone(),
)),
network_provider: network.clone(),
enable_http_requests: true,
custom_extensions: |_| vec![],
})
.run(client.clone(), task_manager.spawn_handle())
.boxed(),
);
}
let rpc_extensions_builder = {
let client = client.clone();
let pool = transaction_pool.clone();
Box::new(move |deny_unsafe, _| {
let deps =
crate::rpc::FullDeps { client: client.clone(), pool: pool.clone(), deny_unsafe };
crate::rpc::create_full(deps).map_err(Into::into)
})
};
let prometheus_registry = config.prometheus_registry().cloned();
let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
network,
client: client.clone(),
keystore: keystore_container.keystore(),
task_manager: &mut task_manager,
transaction_pool: transaction_pool.clone(),
rpc_builder: rpc_extensions_builder,
backend,
system_rpc_tx,
tx_handler_controller,
sync_service,
config,
telemetry: telemetry.as_mut(),
})?;
let proposer = sc_basic_authorship::ProposerFactory::new(
task_manager.spawn_handle(),
client.clone(),
transaction_pool.clone(),
prometheus_registry.as_ref(),
telemetry.as_ref().map(|x| x.handle()),
);
match consensus {
Consensus::InstantSeal => {
let params = sc_consensus_manual_seal::InstantSealParams {
block_import: client.clone(),
env: proposer,
client,
pool: transaction_pool,
select_chain,
consensus_data_provider: None,
create_inherent_data_providers: move |_, ()| async move {
Ok(sp_timestamp::InherentDataProvider::from_system_time())
},
};
let authorship_future = sc_consensus_manual_seal::run_instant_seal(params);
task_manager.spawn_essential_handle().spawn_blocking(
"instant-seal",
None,
authorship_future,
);
},
Consensus::ManualSeal(block_time) => {
let (mut sink, commands_stream) = futures::channel::mpsc::channel(1024);
task_manager.spawn_handle().spawn("block_authoring", None, async move {
loop {
futures_timer::Delay::new(std::time::Duration::from_millis(block_time)).await;
sink.try_send(sc_consensus_manual_seal::EngineCommand::SealNewBlock {
create_empty: true,
finalize: true,
parent_hash: None,
sender: None,
})
.unwrap();
}
});
let params = sc_consensus_manual_seal::ManualSealParams {
block_import: client.clone(),
env: proposer,
client,
pool: transaction_pool,
select_chain,
commands_stream: Box::pin(commands_stream),
consensus_data_provider: None,
create_inherent_data_providers: move |_, ()| async move {
Ok(sp_timestamp::InherentDataProvider::from_system_time())
},
};
let authorship_future = sc_consensus_manual_seal::run_manual_seal(params);
task_manager.spawn_essential_handle().spawn_blocking(
"manual-seal",
None,
authorship_future,
);
},
}
network_starter.start_network();
Ok(task_manager)
}
+30
View File
@@ -0,0 +1,30 @@
[package]
name = "pallet-minimal-template"
description = "A minimal pallet built with FRAME, part of Polkadot Sdk. (polkadot v1.9.0)"
version = "0.1.0"
license = "MIT-0"
authors.workspace = true
homepage.workspace = true
repository.workspace = true
edition.workspace = true
publish = false
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", features = [
"derive",
], default-features = false }
scale-info = { version = "2.10.0", default-features = false, features = [
"derive",
] }
frame = { version = "0.1.1", package = "polkadot-sdk-frame", default-features = false, features = ["experimental", "runtime"] }
[features]
default = ["std"]
std = ["codec/std", "frame/std", "scale-info/std"]
+19
View File
@@ -0,0 +1,19 @@
//! A shell pallet built with [`frame`].
#![cfg_attr(not(feature = "std"), no_std)]
use frame::prelude::*;
// Re-export all pallet parts, this is needed to properly import the pallet into the runtime.
pub use pallet::*;
#[frame::pallet]
pub mod pallet {
use super::*;
#[pallet::config]
pub trait Config: frame_system::Config {}
#[pallet::pallet]
pub struct Pallet<T>(_);
}
+56
View File
@@ -0,0 +1,56 @@
[package]
name = "minimal-template-runtime"
description = "A solochain runtime template built with Substrate, part of Polkadot Sdk. (polkadot v1.9.0)"
version = "0.1.0"
license = "MIT-0"
authors.workspace = true
homepage.workspace = true
repository.workspace = true
edition.workspace = true
publish = false
[lints]
workspace = true
[dependencies]
parity-scale-codec = { version = "3.0.0", default-features = false }
scale-info = { version = "2.6.0", default-features = false }
# this is a frame-based runtime, thus importing `frame` with runtime feature enabled.
frame = { version = "0.1.1", package = "polkadot-sdk-frame", default-features = false, features = ["experimental", "runtime"] }
# pallets that we want to use
pallet-balances = { version = "31.0.0", default-features = false }
pallet-sudo = { version = "31.0.0", default-features = false }
pallet-timestamp = { version = "30.0.0", default-features = false }
pallet-transaction-payment = { version = "31.0.0", default-features = false }
pallet-transaction-payment-rpc-runtime-api = { version = "31.0.0", default-features = false }
# genesis builder that allows us to interacto with runtime genesis config
sp-genesis-builder = { version = "0.10.0", default-features = false }
# local pallet templates
pallet-minimal-template = { path = "../pallets/template", default-features = false, version = "0.1.0" }
[build-dependencies]
substrate-wasm-builder = { version = "20.0.0", optional = true }
[features]
default = ["std"]
std = [
"parity-scale-codec/std",
"scale-info/std",
"frame/std",
"pallet-balances/std",
"pallet-sudo/std",
"pallet-timestamp/std",
"pallet-transaction-payment-rpc-runtime-api/std",
"pallet-transaction-payment/std",
"pallet-minimal-template/std",
"sp-genesis-builder/std",
"substrate-wasm-builder",
]
+27
View File
@@ -0,0 +1,27 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
fn main() {
#[cfg(feature = "std")]
{
substrate_wasm_builder::WasmBuilder::new()
.with_current_project()
.export_heap_base()
.import_memory()
.build();
}
}
+250
View File
@@ -0,0 +1,250 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![cfg_attr(not(feature = "std"), no_std)]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use frame::{
deps::frame_support::{
genesis_builder_helper::{build_config, create_default_config},
weights::{FixedFee, NoFee},
},
prelude::*,
runtime::{
apis::{
self, impl_runtime_apis, ApplyExtrinsicResult, CheckInherentsResult,
ExtrinsicInclusionMode, OpaqueMetadata,
},
prelude::*,
},
};
#[runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("minimal-template-runtime"),
impl_name: create_runtime_str!("minimal-template-runtime"),
authoring_version: 1,
spec_version: 0,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
state_version: 1,
};
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
}
type SignedExtra = (
frame_system::CheckNonZeroSender<Runtime>,
frame_system::CheckSpecVersion<Runtime>,
frame_system::CheckTxVersion<Runtime>,
frame_system::CheckGenesis<Runtime>,
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
);
construct_runtime!(
pub enum Runtime {
System: frame_system,
Timestamp: pallet_timestamp,
Balances: pallet_balances,
Sudo: pallet_sudo,
TransactionPayment: pallet_transaction_payment,
// our local pallet
Template: pallet_minimal_template,
}
);
parameter_types! {
pub const Version: RuntimeVersion = VERSION;
}
#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for Runtime {
type Block = Block;
type Version = Version;
type BlockHashCount = ConstU32<1024>;
type AccountData = pallet_balances::AccountData<<Runtime as pallet_balances::Config>::Balance>;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)]
impl pallet_balances::Config for Runtime {
type AccountStore = System;
}
#[derive_impl(pallet_sudo::config_preludes::TestDefaultConfig as pallet_sudo::DefaultConfig)]
impl pallet_sudo::Config for Runtime {}
#[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig as pallet_timestamp::DefaultConfig)]
impl pallet_timestamp::Config for Runtime {}
#[derive_impl(pallet_transaction_payment::config_preludes::TestDefaultConfig as pallet_transaction_payment::DefaultConfig)]
impl pallet_transaction_payment::Config for Runtime {
type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;
type WeightToFee = NoFee<<Self as pallet_balances::Config>::Balance>;
type LengthToFee = FixedFee<1, <Self as pallet_balances::Config>::Balance>;
}
impl pallet_minimal_template::Config for Runtime {}
type Block = frame::runtime::types_common::BlockOf<Runtime, SignedExtra>;
type Header = HeaderFor<Runtime>;
type RuntimeExecutive =
Executive<Runtime, Block, frame_system::ChainContext<Runtime>, Runtime, AllPalletsWithSystem>;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
impl_runtime_apis! {
impl apis::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: Block) {
RuntimeExecutive::execute_block(block)
}
fn initialize_block(header: &Header) -> ExtrinsicInclusionMode {
RuntimeExecutive::initialize_block(header)
}
}
impl apis::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> Vec<u32> {
Runtime::metadata_versions()
}
}
impl apis::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: ExtrinsicFor<Runtime>) -> ApplyExtrinsicResult {
RuntimeExecutive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> HeaderFor<Runtime> {
RuntimeExecutive::finalize_block()
}
fn inherent_extrinsics(data: InherentData) -> Vec<ExtrinsicFor<Runtime>> {
data.create_extrinsics()
}
fn check_inherents(
block: Block,
data: InherentData,
) -> CheckInherentsResult {
data.check_extrinsics(&block)
}
}
impl apis::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: ExtrinsicFor<Runtime>,
block_hash: <Runtime as frame_system::Config>::Hash,
) -> TransactionValidity {
RuntimeExecutive::validate_transaction(source, tx, block_hash)
}
}
impl apis::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &HeaderFor<Runtime>) {
RuntimeExecutive::offchain_worker(header)
}
}
impl apis::SessionKeys<Block> for Runtime {
fn generate_session_keys(_seed: Option<Vec<u8>>) -> Vec<u8> {
Default::default()
}
fn decode_session_keys(
_encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, apis::KeyTypeId)>> {
Default::default()
}
}
impl apis::AccountNonceApi<Block, interface::AccountId, interface::Nonce> for Runtime {
fn account_nonce(account: interface::AccountId) -> interface::Nonce {
System::account_nonce(account)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
Block,
interface::Balance,
> for Runtime {
fn query_info(uxt: ExtrinsicFor<Runtime>, len: u32) -> RuntimeDispatchInfo<interface::Balance> {
TransactionPayment::query_info(uxt, len)
}
fn query_fee_details(uxt: ExtrinsicFor<Runtime>, len: u32) -> FeeDetails<interface::Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> interface::Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> interface::Balance {
TransactionPayment::length_to_fee(length)
}
}
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn create_default_config() -> Vec<u8> {
create_default_config::<RuntimeGenesisConfig>()
}
fn build_config(config: Vec<u8>) -> sp_genesis_builder::Result {
build_config::<RuntimeGenesisConfig>(config)
}
}
}
/// Some re-exports that the node side code needs to know. Some are useful in this context as well.
///
/// Other types should preferably be private.
// TODO: this should be standardized in some way, see:
// https://github.com/paritytech/substrate/issues/10579#issuecomment-1600537558
pub mod interface {
use super::Runtime;
use frame::deps::frame_system;
pub type Block = super::Block;
pub use frame::runtime::types_common::OpaqueBlock;
pub type AccountId = <Runtime as frame_system::Config>::AccountId;
pub type Nonce = <Runtime as frame_system::Config>::Nonce;
pub type Hash = <Runtime as frame_system::Config>::Hash;
pub type Balance = <Runtime as pallet_balances::Config>::Balance;
pub type MinimumBalance = <Runtime as pallet_balances::Config>::ExistentialDeposit;
}