Skip to content
Snippets Groups Projects
Verified Commit 92f2d57f authored by Pascal Engélibert's avatar Pascal Engélibert :bicyclist:
Browse files

fmt

parent 8425343d
No related branches found
No related tags found
No related merge requests found
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
fn main() { fn main() {
generate_cargo_keys(); generate_cargo_keys();
rerun_if_git_head_changed(); rerun_if_git_head_changed();
} }
...@@ -14,15 +14,15 @@ ...@@ -14,15 +14,15 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>.
use sp_core::{Pair, Public, sr25519};
use node_template_runtime::{ use node_template_runtime::{
AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig,
SudoConfig, SystemConfig, WASM_BINARY, Signature SystemConfig, WASM_BINARY,
}; };
use sc_service::ChainType;
use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{sr25519, Pair, Public};
use sp_finality_grandpa::AuthorityId as GrandpaId; use sp_finality_grandpa::AuthorityId as GrandpaId;
use sp_runtime::traits::{Verify, IdentifyAccount}; use sp_runtime::traits::{IdentifyAccount, Verify};
use sc_service::ChainType;
// The URL for the telemetry server. // The URL for the telemetry server.
// const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; // const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
...@@ -32,142 +32,149 @@ pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>; ...@@ -32,142 +32,149 @@ pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;
/// Generate a crypto pair from seed. /// Generate a crypto pair from seed.
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public { pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None) TPublic::Pair::from_string(&format!("//{}", seed), None)
.expect("static values are valid; qed") .expect("static values are valid; qed")
.public() .public()
} }
type AccountPublic = <Signature as Verify>::Signer; type AccountPublic = <Signature as Verify>::Signer;
/// Generate an account ID from seed. /// Generate an account ID from seed.
pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId where pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
AccountPublic: From<<TPublic::Pair as Pair>::Public> where
AccountPublic: From<<TPublic::Pair as Pair>::Public>,
{ {
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account() AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
} }
/// Generate an Aura authority key. /// Generate an Aura authority key.
pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) { pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {
( (get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))
get_from_seed::<AuraId>(s),
get_from_seed::<GrandpaId>(s),
)
} }
pub fn development_config() -> Result<ChainSpec, String> { pub fn development_config() -> Result<ChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?;
Ok(ChainSpec::from_genesis( Ok(ChainSpec::from_genesis(
// Name // Name
"Development", "Development",
// ID // ID
"dev", "dev",
ChainType::Development, ChainType::Development,
move || testnet_genesis( move || {
wasm_binary, testnet_genesis(
// Initial PoA authorities wasm_binary,
vec![ // Initial PoA authorities
authority_keys_from_seed("Alice"), vec![authority_keys_from_seed("Alice")],
], // Sudo account
// Sudo account get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Alice"), // Pre-funded accounts
// Pre-funded accounts vec![
vec![ get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
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>("Bob//stash"), ],
], true,
true, )
), },
// Bootnodes // Bootnodes
vec![], vec![],
// Telemetry // Telemetry
None, None,
// Protocol ID // Protocol ID
None, None,
// Properties // Properties
None, None,
// Extensions // Extensions
None, None,
)) ))
} }
pub fn local_testnet_config() -> Result<ChainSpec, String> { pub fn local_testnet_config() -> Result<ChainSpec, String> {
let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?;
Ok(ChainSpec::from_genesis( Ok(ChainSpec::from_genesis(
// Name // Name
"Local Testnet", "Local Testnet",
// ID // ID
"local_testnet", "local_testnet",
ChainType::Local, ChainType::Local,
move || testnet_genesis( move || {
wasm_binary, testnet_genesis(
// Initial PoA authorities wasm_binary,
vec![ // Initial PoA authorities
authority_keys_from_seed("Alice"), vec![
authority_keys_from_seed("Bob"), authority_keys_from_seed("Alice"),
], authority_keys_from_seed("Bob"),
// Sudo account ],
get_account_id_from_seed::<sr25519::Public>("Alice"), // Sudo account
// Pre-funded accounts get_account_id_from_seed::<sr25519::Public>("Alice"),
vec![ // Pre-funded accounts
get_account_id_from_seed::<sr25519::Public>("Alice"), vec![
get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Charlie"), get_account_id_from_seed::<sr25519::Public>("Bob"),
get_account_id_from_seed::<sr25519::Public>("Dave"), get_account_id_from_seed::<sr25519::Public>("Charlie"),
get_account_id_from_seed::<sr25519::Public>("Eve"), get_account_id_from_seed::<sr25519::Public>("Dave"),
get_account_id_from_seed::<sr25519::Public>("Ferdie"), get_account_id_from_seed::<sr25519::Public>("Eve"),
get_account_id_from_seed::<sr25519::Public>("Alice//stash"), get_account_id_from_seed::<sr25519::Public>("Ferdie"),
get_account_id_from_seed::<sr25519::Public>("Bob//stash"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
get_account_id_from_seed::<sr25519::Public>("Dave//stash"), get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
get_account_id_from_seed::<sr25519::Public>("Eve//stash"), get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
], get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
true, ],
), true,
// Bootnodes )
vec![], },
// Telemetry // Bootnodes
None, vec![],
// Protocol ID // Telemetry
None, None,
// Properties // Protocol ID
None, None,
// Extensions // Properties
None, None,
)) // Extensions
None,
))
} }
/// Configure initial storage state for FRAME modules. /// Configure initial storage state for FRAME modules.
fn testnet_genesis( fn testnet_genesis(
wasm_binary: &[u8], wasm_binary: &[u8],
initial_authorities: Vec<(AuraId, GrandpaId)>, initial_authorities: Vec<(AuraId, GrandpaId)>,
root_key: AccountId, root_key: AccountId,
endowed_accounts: Vec<AccountId>, endowed_accounts: Vec<AccountId>,
_enable_println: bool, _enable_println: bool,
) -> GenesisConfig { ) -> GenesisConfig {
GenesisConfig { GenesisConfig {
frame_system: SystemConfig { frame_system: SystemConfig {
// Add Wasm runtime to storage. // Add Wasm runtime to storage.
code: wasm_binary.to_vec(), code: wasm_binary.to_vec(),
changes_trie_config: Default::default(), changes_trie_config: Default::default(),
}, },
pallet_balances: BalancesConfig { pallet_balances: BalancesConfig {
// Configure endowed accounts with initial balance of 1 << 60. // Configure endowed accounts with initial balance of 1 << 60.
balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(), balances: endowed_accounts
}, .iter()
pallet_aura: AuraConfig { .cloned()
authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), .map(|k| (k, 1 << 60))
}, .collect(),
pallet_grandpa: GrandpaConfig { },
authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), pallet_aura: AuraConfig {
}, authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),
pallet_sudo: SudoConfig { },
// Assign network admin rights. pallet_grandpa: GrandpaConfig {
key: root_key, authorities: initial_authorities
}, .iter()
} .map(|x| (x.1.clone(), 1))
.collect(),
},
pallet_sudo: SudoConfig {
// Assign network admin rights.
key: root_key,
},
}
} }
...@@ -14,44 +14,44 @@ ...@@ -14,44 +14,44 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>.
use structopt::StructOpt;
use sc_cli::RunCmd; use sc_cli::RunCmd;
use structopt::StructOpt;
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
pub struct Cli { pub struct Cli {
#[structopt(subcommand)] #[structopt(subcommand)]
pub subcommand: Option<Subcommand>, pub subcommand: Option<Subcommand>,
#[structopt(flatten)] #[structopt(flatten)]
pub run: RunCmd, pub run: RunCmd,
} }
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
pub enum Subcommand { pub enum Subcommand {
/// Key management cli utilities /// Key management cli utilities
Key(sc_cli::KeySubcommand), Key(sc_cli::KeySubcommand),
/// Build a chain specification. /// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd), BuildSpec(sc_cli::BuildSpecCmd),
/// Validate blocks. /// Validate blocks.
CheckBlock(sc_cli::CheckBlockCmd), CheckBlock(sc_cli::CheckBlockCmd),
/// Export blocks. /// Export blocks.
ExportBlocks(sc_cli::ExportBlocksCmd), ExportBlocks(sc_cli::ExportBlocksCmd),
/// Export the state of a given block into a chain spec. /// Export the state of a given block into a chain spec.
ExportState(sc_cli::ExportStateCmd), ExportState(sc_cli::ExportStateCmd),
/// Import blocks. /// Import blocks.
ImportBlocks(sc_cli::ImportBlocksCmd), ImportBlocks(sc_cli::ImportBlocksCmd),
/// Remove the whole chain. /// Remove the whole chain.
PurgeChain(sc_cli::PurgeChainCmd), PurgeChain(sc_cli::PurgeChainCmd),
/// Revert the chain to a previous state. /// Revert the chain to a previous state.
Revert(sc_cli::RevertCmd), Revert(sc_cli::RevertCmd),
/// The custom benchmark subcommmand benchmarking runtime pallets. /// The custom benchmark subcommmand benchmarking runtime pallets.
#[structopt(name = "benchmark", about = "Benchmark runtime pallets.")] #[structopt(name = "benchmark", about = "Benchmark runtime pallets.")]
Benchmark(frame_benchmarking_cli::BenchmarkCmd), Benchmark(frame_benchmarking_cli::BenchmarkCmd),
} }
...@@ -15,124 +15,144 @@ ...@@ -15,124 +15,144 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>.
use crate::{chain_spec, service};
use crate::cli::{Cli, Subcommand}; use crate::cli::{Cli, Subcommand};
use sc_cli::{SubstrateCli, RuntimeVersion, Role, ChainSpec}; use crate::{chain_spec, service};
use sc_service::PartialComponents;
use node_template_runtime::Block; use node_template_runtime::Block;
use sc_cli::{ChainSpec, Role, RuntimeVersion, SubstrateCli};
use sc_service::PartialComponents;
impl SubstrateCli for Cli { impl SubstrateCli for Cli {
fn impl_name() -> String { fn impl_name() -> String {
"Substrate Node".into() "Substrate Node".into()
} }
fn impl_version() -> String { fn impl_version() -> String {
env!("SUBSTRATE_CLI_IMPL_VERSION").into() env!("SUBSTRATE_CLI_IMPL_VERSION").into()
} }
fn description() -> String { fn description() -> String {
env!("CARGO_PKG_DESCRIPTION").into() env!("CARGO_PKG_DESCRIPTION").into()
} }
fn author() -> String { fn author() -> String {
env!("CARGO_PKG_AUTHORS").into() env!("CARGO_PKG_AUTHORS").into()
} }
fn support_url() -> String { fn support_url() -> String {
"support.anonymous.an".into() "support.anonymous.an".into()
} }
fn copyright_start_year() -> i32 { fn copyright_start_year() -> i32 {
2017 2017
} }
fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> { fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(match id { Ok(match id {
"dev" => Box::new(chain_spec::development_config()?), "dev" => Box::new(chain_spec::development_config()?),
"" | "local" => Box::new(chain_spec::local_testnet_config()?), "" | "local" => Box::new(chain_spec::local_testnet_config()?),
path => Box::new(chain_spec::ChainSpec::from_json_file( path => Box::new(chain_spec::ChainSpec::from_json_file(
std::path::PathBuf::from(path), std::path::PathBuf::from(path),
)?), )?),
}) })
} }
fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion { fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
&node_template_runtime::VERSION &node_template_runtime::VERSION
} }
} }
/// Parse and run command line arguments /// Parse and run command line arguments
pub fn run() -> sc_cli::Result<()> { pub fn run() -> sc_cli::Result<()> {
let cli = Cli::from_args(); let cli = Cli::from_args();
match &cli.subcommand { match &cli.subcommand {
Some(Subcommand::Key(cmd)) => cmd.run(&cli), Some(Subcommand::Key(cmd)) => cmd.run(&cli),
Some(Subcommand::BuildSpec(cmd)) => { Some(Subcommand::BuildSpec(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) runner.sync_run(|config| cmd.run(config.chain_spec, config.network))
}, }
Some(Subcommand::CheckBlock(cmd)) => { Some(Subcommand::CheckBlock(cmd)) => {
let runner = cli.create_runner(cmd)?; let runner = cli.create_runner(cmd)?;
runner.async_run(|config| { runner.async_run(|config| {
let PartialComponents { client, task_manager, import_queue, ..} let PartialComponents {
= service::new_partial(&config)?; client,
Ok((cmd.run(client, import_queue), task_manager)) task_manager,
}) import_queue,
}, ..
Some(Subcommand::ExportBlocks(cmd)) => { } = service::new_partial(&config)?;
let runner = cli.create_runner(cmd)?; Ok((cmd.run(client, import_queue), task_manager))
runner.async_run(|config| { })
let PartialComponents { client, task_manager, ..} }
= service::new_partial(&config)?; Some(Subcommand::ExportBlocks(cmd)) => {
Ok((cmd.run(client, config.database), task_manager)) let runner = cli.create_runner(cmd)?;
}) runner.async_run(|config| {
}, let PartialComponents {
Some(Subcommand::ExportState(cmd)) => { client,
let runner = cli.create_runner(cmd)?; task_manager,
runner.async_run(|config| { ..
let PartialComponents { client, task_manager, ..} } = service::new_partial(&config)?;
= service::new_partial(&config)?; Ok((cmd.run(client, config.database), task_manager))
Ok((cmd.run(client, config.chain_spec), task_manager)) })
}) }
}, Some(Subcommand::ExportState(cmd)) => {
Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?;
let runner = cli.create_runner(cmd)?; runner.async_run(|config| {
runner.async_run(|config| { let PartialComponents {
let PartialComponents { client, task_manager, import_queue, ..} client,
= service::new_partial(&config)?; task_manager,
Ok((cmd.run(client, import_queue), task_manager)) ..
}) } = service::new_partial(&config)?;
}, Ok((cmd.run(client, config.chain_spec), task_manager))
Some(Subcommand::PurgeChain(cmd)) => { })
let runner = cli.create_runner(cmd)?; }
runner.sync_run(|config| cmd.run(config.database)) Some(Subcommand::ImportBlocks(cmd)) => {
}, let runner = cli.create_runner(cmd)?;
Some(Subcommand::Revert(cmd)) => { runner.async_run(|config| {
let runner = cli.create_runner(cmd)?; let PartialComponents {
runner.async_run(|config| { client,
let PartialComponents { client, task_manager, backend, ..} task_manager,
= service::new_partial(&config)?; import_queue,
Ok((cmd.run(client, backend), task_manager)) ..
}) } = service::new_partial(&config)?;
}, Ok((cmd.run(client, import_queue), task_manager))
Some(Subcommand::Benchmark(cmd)) => { })
if cfg!(feature = "runtime-benchmarks") { }
let runner = cli.create_runner(cmd)?; 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), task_manager))
})
}
Some(Subcommand::Benchmark(cmd)) => {
if cfg!(feature = "runtime-benchmarks") {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| cmd.run::<Block, service::Executor>(config)) runner.sync_run(|config| cmd.run::<Block, service::Executor>(config))
} else { } else {
Err("Benchmarking wasn't enabled when building the node. \ Err("Benchmarking wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`.".into()) You can enable it with `--features runtime-benchmarks`."
} .into())
}, }
None => { }
let runner = cli.create_runner(&cli.run)?; None => {
runner.run_node_until_exit(|config| async move { let runner = cli.create_runner(&cli.run)?;
match config.role { runner.run_node_until_exit(|config| async move {
Role::Light => service::new_light(config), match config.role {
_ => service::new_full(config), Role::Light => service::new_light(config),
}.map_err(sc_cli::Error::Service) _ => service::new_full(config),
}) }
} .map_err(sc_cli::Error::Service)
} })
}
}
} }
...@@ -15,5 +15,5 @@ ...@@ -15,5 +15,5 @@
// along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>.
pub mod chain_spec; pub mod chain_spec;
pub mod service;
pub mod rpc; pub mod rpc;
pub mod service;
...@@ -25,5 +25,5 @@ mod command; ...@@ -25,5 +25,5 @@ mod command;
mod rpc; mod rpc;
fn main() -> sc_cli::Result<()> { fn main() -> sc_cli::Result<()> {
command::run() command::run()
} }
...@@ -24,57 +24,57 @@ ...@@ -24,57 +24,57 @@
use std::sync::Arc; use std::sync::Arc;
use node_template_runtime::{opaque::Block, AccountId, Balance, Index}; use node_template_runtime::{opaque::Block, AccountId, Balance, Index};
pub use sc_rpc_api::DenyUnsafe;
use sp_api::ProvideRuntimeApi; use sp_api::ProvideRuntimeApi;
use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend};
use sp_block_builder::BlockBuilder; use sp_block_builder::BlockBuilder;
pub use sc_rpc_api::DenyUnsafe; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
use sp_transaction_pool::TransactionPool; use sp_transaction_pool::TransactionPool;
/// Full client dependencies. /// Full client dependencies.
pub struct FullDeps<C, P> { pub struct FullDeps<C, P> {
/// The client instance to use. /// The client instance to use.
pub client: Arc<C>, pub client: Arc<C>,
/// Transaction pool instance. /// Transaction pool instance.
pub pool: Arc<P>, pub pool: Arc<P>,
/// Whether to deny unsafe calls /// Whether to deny unsafe calls
pub deny_unsafe: DenyUnsafe, pub deny_unsafe: DenyUnsafe,
} }
/// Instantiate all full RPC extensions. /// Instantiate all full RPC extensions.
pub fn create_full<C, P>( pub fn create_full<C, P>(deps: FullDeps<C, P>) -> jsonrpc_core::IoHandler<sc_rpc::Metadata>
deps: FullDeps<C, P>, where
) -> jsonrpc_core::IoHandler<sc_rpc::Metadata> where C: ProvideRuntimeApi<Block>,
C: ProvideRuntimeApi<Block>, C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
C: HeaderBackend<Block> + HeaderMetadata<Block, Error=BlockChainError> + 'static, C: Send + Sync + 'static,
C: Send + Sync + 'static, C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,
C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>, C::Api: BlockBuilder<Block>,
C::Api: BlockBuilder<Block>, P: TransactionPool + 'static,
P: TransactionPool + 'static,
{ {
use substrate_frame_rpc_system::{FullSystem, SystemApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; use substrate_frame_rpc_system::{FullSystem, SystemApi};
let mut io = jsonrpc_core::IoHandler::default(); let mut io = jsonrpc_core::IoHandler::default();
let FullDeps { let FullDeps {
client, client,
pool, pool,
deny_unsafe, deny_unsafe,
} = deps; } = deps;
io.extend_with( io.extend_with(SystemApi::to_delegate(FullSystem::new(
SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe)) client.clone(),
); pool,
deny_unsafe,
)));
io.extend_with( io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(
TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone())) client.clone(),
); )));
// Extend this RPC with a custom API by using the following syntax. // Extend this RPC with a custom API by using the following syntax.
// `YourRpcStruct` should have a reference to a client, which is needed // `YourRpcStruct` should have a reference to a client, which is needed
// to call into the runtime. // to call into the runtime.
// `io.extend_with(YourRpcTrait::to_delegate(YourRpcStruct::new(ReferenceToClient, ...)));` // `io.extend_with(YourRpcTrait::to_delegate(YourRpcStruct::new(ReferenceToClient, ...)));`
io io
} }
This diff is collapsed.
...@@ -18,23 +18,19 @@ ...@@ -18,23 +18,19 @@
use super::*; use super::*;
use frame_system::RawOrigin;
use frame_benchmarking::{benchmarks, whitelisted_caller, impl_benchmark_test_suite};
#[allow(unused)] #[allow(unused)]
use crate::Pallet as Template; use crate::Pallet as Template;
use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller};
use frame_system::RawOrigin;
benchmarks! { benchmarks! {
do_something { do_something {
let s in 0 .. 100; let s in 0 .. 100;
let caller: T::AccountId = whitelisted_caller(); let caller: T::AccountId = whitelisted_caller();
}: _(RawOrigin::Signed(caller), s) }: _(RawOrigin::Signed(caller), s)
verify { verify {
assert_eq!(Something::<T>::get(), Some(s)); assert_eq!(Something::<T>::get(), Some(s));
} }
} }
impl_benchmark_test_suite!( impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test,);
Template,
crate::mock::new_test_ext(),
crate::mock::Test,
);
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
/// Edit this file to define custom logic or remove it if it is not needed. /// Edit this file to define custom logic or remove it if it is not needed.
/// Learn more about FRAME and the core library of Substrate FRAME pallets: /// Learn more about FRAME and the core library of Substrate FRAME pallets:
/// <https://substrate.dev/docs/en/knowledgebase/runtime/frame> /// <https://substrate.dev/docs/en/knowledgebase/runtime/frame>
pub use pallet::*; pub use pallet::*;
#[cfg(test)] #[cfg(test)]
...@@ -33,91 +32,91 @@ mod benchmarking; ...@@ -33,91 +32,91 @@ mod benchmarking;
#[frame_support::pallet] #[frame_support::pallet]
pub mod pallet { pub mod pallet {
use frame_support::{dispatch::DispatchResult, pallet_prelude::*}; use frame_support::{dispatch::DispatchResult, pallet_prelude::*};
use frame_system::pallet_prelude::*; use frame_system::pallet_prelude::*;
/// Configure the pallet by specifying the parameters and types on which it depends. /// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config] #[pallet::config]
pub trait Config: frame_system::Config { pub trait Config: frame_system::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event. /// Because this pallet emits events, it depends on the runtime's definition of an event.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
} }
#[pallet::pallet] #[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)] #[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_); pub struct Pallet<T>(_);
// The pallet's runtime storage items. // The pallet's runtime storage items.
// https://substrate.dev/docs/en/knowledgebase/runtime/storage // https://substrate.dev/docs/en/knowledgebase/runtime/storage
#[pallet::storage] #[pallet::storage]
#[pallet::getter(fn something)] #[pallet::getter(fn something)]
// Learn more about declaring storage items: // Learn more about declaring storage items:
// https://substrate.dev/docs/en/knowledgebase/runtime/storage#declaring-storage-items // https://substrate.dev/docs/en/knowledgebase/runtime/storage#declaring-storage-items
pub type Something<T> = StorageValue<_, u32>; pub type Something<T> = StorageValue<_, u32>;
// Pallets use events to inform users when important changes are made. // Pallets use events to inform users when important changes are made.
// https://substrate.dev/docs/en/knowledgebase/runtime/events // https://substrate.dev/docs/en/knowledgebase/runtime/events
#[pallet::event] #[pallet::event]
#[pallet::metadata(T::AccountId = "AccountId")] #[pallet::metadata(T::AccountId = "AccountId")]
#[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> { pub enum Event<T: Config> {
/// Event documentation should end with an array that provides descriptive names for event /// Event documentation should end with an array that provides descriptive names for event
/// parameters. [something, who] /// parameters. [something, who]
SomethingStored(u32, T::AccountId), SomethingStored(u32, T::AccountId),
} }
// Errors inform users that something went wrong. // Errors inform users that something went wrong.
#[pallet::error] #[pallet::error]
pub enum Error<T> { pub enum Error<T> {
/// Error names should be descriptive. /// Error names should be descriptive.
NoneValue, NoneValue,
/// Errors should have helpful documentation associated with them. /// Errors should have helpful documentation associated with them.
StorageOverflow, StorageOverflow,
} }
#[pallet::hooks] #[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {} impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
// Dispatchable functions allows users to interact with the pallet and invoke state changes. // Dispatchable functions allows users to interact with the pallet and invoke state changes.
// These functions materialize as "extrinsics", which are often compared to transactions. // These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult. // Dispatchable functions must be annotated with a weight and must return a DispatchResult.
#[pallet::call] #[pallet::call]
impl<T:Config> Pallet<T> { impl<T: Config> Pallet<T> {
/// An example dispatchable that takes a singles value as a parameter, writes the value to /// An example dispatchable that takes a singles value as a parameter, writes the value to
/// storage and emits an event. This function must be dispatched by a signed extrinsic. /// storage and emits an event. This function must be dispatched by a signed extrinsic.
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))] #[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResult { pub fn do_something(origin: OriginFor<T>, something: u32) -> DispatchResult {
// Check that the extrinsic was signed and get the signer. // Check that the extrinsic was signed and get the signer.
// This function will return an error if the extrinsic is not signed. // This function will return an error if the extrinsic is not signed.
// https://substrate.dev/docs/en/knowledgebase/runtime/origin // https://substrate.dev/docs/en/knowledgebase/runtime/origin
let who = ensure_signed(origin)?; let who = ensure_signed(origin)?;
// Update storage. // Update storage.
<Something<T>>::put(something); <Something<T>>::put(something);
// Emit an event. // Emit an event.
Self::deposit_event(Event::SomethingStored(something, who)); Self::deposit_event(Event::SomethingStored(something, who));
// Return a successful DispatchResultWithPostInfo // Return a successful DispatchResultWithPostInfo
Ok(()) Ok(())
} }
/// An example dispatchable that may throw a custom error. /// An example dispatchable that may throw a custom error.
#[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))] #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
pub fn cause_error(origin: OriginFor<T>) -> DispatchResult { pub fn cause_error(origin: OriginFor<T>) -> DispatchResult {
let _who = ensure_signed(origin)?; let _who = ensure_signed(origin)?;
// Read a value from storage. // Read a value from storage.
match <Something<T>>::get() { match <Something<T>>::get() {
// Return an error if the value has not been set. // Return an error if the value has not been set.
None => Err(Error::<T>::NoneValue)?, None => Err(Error::<T>::NoneValue)?,
Some(old) => { Some(old) => {
// Increment the value read from storage; will error in the event of overflow. // Increment the value read from storage; will error in the event of overflow.
let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?; let new = old.checked_add(1).ok_or(Error::<T>::StorageOverflow)?;
// Update the value in storage with the incremented result. // Update the value in storage with the incremented result.
<Something<T>>::put(new); <Something<T>>::put(new);
Ok(()) Ok(())
}, }
} }
} }
} }
} }
...@@ -15,64 +15,68 @@ ...@@ -15,64 +15,68 @@
// along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>.
use crate as pallet_template; use crate as pallet_template;
use sp_core::H256;
use frame_support::parameter_types; use frame_support::parameter_types;
use frame_system as system;
use sp_core::H256;
use sp_runtime::{ use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup}, testing::Header, testing::Header,
traits::{BlakeTwo256, IdentityLookup},
}; };
use frame_system as system;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>; type Block = frame_system::mocking::MockBlock<Test>;
// Configure a mock runtime to test the pallet. // Configure a mock runtime to test the pallet.
frame_support::construct_runtime!( frame_support::construct_runtime!(
pub enum Test where pub enum Test where
Block = Block, Block = Block,
NodeBlock = Block, NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic, UncheckedExtrinsic = UncheckedExtrinsic,
{ {
System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
TemplateModule: pallet_template::{Pallet, Call, Storage, Event<T>}, TemplateModule: pallet_template::{Pallet, Call, Storage, Event<T>},
} }
); );
parameter_types! { parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
pub const SS58Prefix: u8 = 42; pub const SS58Prefix: u8 = 42;
} }
impl system::Config for Test { impl system::Config for Test {
type BaseCallFilter = (); type BaseCallFilter = ();
type BlockWeights = (); type BlockWeights = ();
type BlockLength = (); type BlockLength = ();
type DbWeight = (); type DbWeight = ();
type Origin = Origin; type Origin = Origin;
type Call = Call; type Call = Call;
type Index = u64; type Index = u64;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
type Hashing = BlakeTwo256; type Hashing = BlakeTwo256;
type AccountId = u64; type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = Event; type Event = Event;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = PalletInfo; type PalletInfo = PalletInfo;
type AccountData = (); type AccountData = ();
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = (); type OnKilledAccount = ();
type SystemWeightInfo = (); type SystemWeightInfo = ();
type SS58Prefix = SS58Prefix; type SS58Prefix = SS58Prefix;
type OnSetCode = (); type OnSetCode = ();
} }
impl pallet_template::Config for Test { impl pallet_template::Config for Test {
type Event = Event; type Event = Event;
} }
// Build genesis storage according to the mock runtime. // Build genesis storage according to the mock runtime.
pub fn new_test_ext() -> sp_io::TestExternalities { pub fn new_test_ext() -> sp_io::TestExternalities {
system::GenesisConfig::default().build_storage::<Test>().unwrap().into() system::GenesisConfig::default()
.build_storage::<Test>()
.unwrap()
.into()
} }
...@@ -14,26 +14,26 @@ ...@@ -14,26 +14,26 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>. // along with Substrate-Libre-Currency. If not, see <https://www.gnu.org/licenses/>.
use crate::{Error, mock::*}; use crate::{mock::*, Error};
use frame_support::{assert_ok, assert_noop}; use frame_support::{assert_noop, assert_ok};
#[test] #[test]
fn it_works_for_default_value() { fn it_works_for_default_value() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
// Dispatch a signed extrinsic. // Dispatch a signed extrinsic.
assert_ok!(TemplateModule::do_something(Origin::signed(1), 42)); assert_ok!(TemplateModule::do_something(Origin::signed(1), 42));
// Read pallet storage and assert an expected result. // Read pallet storage and assert an expected result.
assert_eq!(TemplateModule::something(), Some(42)); assert_eq!(TemplateModule::something(), Some(42));
}); });
} }
#[test] #[test]
fn correct_error_for_none_value() { fn correct_error_for_none_value() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
// Ensure the expected error is thrown when no value is present. // Ensure the expected error is thrown when no value is present.
assert_noop!( assert_noop!(
TemplateModule::cause_error(Origin::signed(1)), TemplateModule::cause_error(Origin::signed(1)),
Error::<Test>::NoneValue Error::<Test>::NoneValue
); );
}); });
} }
...@@ -17,9 +17,9 @@ ...@@ -17,9 +17,9 @@
use substrate_wasm_builder::WasmBuilder; use substrate_wasm_builder::WasmBuilder;
fn main() { fn main() {
WasmBuilder::new() WasmBuilder::new()
.with_current_project() .with_current_project()
.export_heap_base() .export_heap_base()
.import_memory() .import_memory()
.build() .build()
} }
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment