Skip to content

Commit

Permalink
Update pallets, runtime and node code to v1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
F3Joule committed Nov 15, 2024
1 parent 055ae8b commit 4bf7141
Show file tree
Hide file tree
Showing 43 changed files with 522 additions and 508 deletions.
15 changes: 10 additions & 5 deletions node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const TESTNET_DEFAULT_ENDOWMENT: Balance = 1_000_000;

/// Specialized `ChainSpec` for the normal parachain runtime.
pub type ChainSpec =
sc_service::GenericChainSpec<subsocial_parachain_runtime::GenesisConfig, Extensions>;
sc_service::GenericChainSpec<subsocial_parachain_runtime::RuntimeGenesisConfig, Extensions>;

/// The default XCM version to set in genesis config.
const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION;
Expand All @@ -44,7 +44,7 @@ pub struct Extensions {
/// The id of the Parachain.
pub para_id: u32,
/// Known bad block hashes.
pub bad_blocks: sc_client_api::BadBlocks<polkadot_primitives::v2::Block>,
pub bad_blocks: sc_client_api::BadBlocks<polkadot_primitives::Block>,
}

impl Extensions {
Expand Down Expand Up @@ -263,19 +263,23 @@ fn parachain_genesis(
endowed_accounts: Vec<(AccountId, Balance)>,
id: ParaId,
root_key: AccountId,
) -> subsocial_parachain_runtime::GenesisConfig {
subsocial_parachain_runtime::GenesisConfig {
) -> subsocial_parachain_runtime::RuntimeGenesisConfig {
subsocial_parachain_runtime::RuntimeGenesisConfig {
system: subsocial_parachain_runtime::SystemConfig {
code: subsocial_parachain_runtime::WASM_BINARY
.expect("WASM binary was not build, please build it!")
.to_vec(),
..Default::default()
},
balances: subsocial_parachain_runtime::BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|(account, balance)| {
(account, balance.saturating_mul(UNIT))
}).collect(),
},
parachain_info: subsocial_parachain_runtime::ParachainInfoConfig { parachain_id: id },
parachain_info: subsocial_parachain_runtime::ParachainInfoConfig {
parachain_id: id,
..Default::default()
},
collator_selection: subsocial_parachain_runtime::CollatorSelectionConfig {
invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(),
candidacy_bond: EXISTENTIAL_DEPOSIT * 16,
Expand All @@ -302,6 +306,7 @@ fn parachain_genesis(
vesting: subsocial_parachain_runtime::VestingConfig { vesting: vec![] },
polkadot_xcm: subsocial_parachain_runtime::PolkadotXcmConfig {
safe_xcm_version: Some(SAFE_XCM_VERSION),
..Default::default()
},
sudo: subsocial_parachain_runtime::SudoConfig {
key: Some(root_key.clone()),
Expand Down
21 changes: 19 additions & 2 deletions node/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,25 @@ pub enum Subcommand {
TryRuntime,
}

const AFTER_HELP_EXAMPLE: &str = color_print::cstr!(
r#"<bold><underline>Examples:</></>
<bold>subsocial-node build-spec --disable-default-bootnode > plain-subsocial-chainspec.json</>
Export a chainspec for a local testnet in json format.
<bold>subsocial-node --chain plain-subsocial-chainspec.json --tmp -- --chain rococo-local</>
Launch a full node with chain specification loaded from plain-subsocial-chainspec.json.
<bold>subsocial-node</>
Launch a full node with default parachain <italic>local-testnet</> and relay chain <italic>rococo-local</>.
<bold>subsocial-node --collator</>
Launch a collator with default parachain <italic>local-testnet</> and relay chain <italic>rococo-local</>.
"#
);
#[derive(Debug, clap::Parser)]
#[command(
propagate_version = true,
args_conflicts_with_subcommands = true,
subcommand_negates_reqs = true
)]
#[clap(after_help = AFTER_HELP_EXAMPLE)]
pub struct Cli {
#[command(subcommand)]
pub subcommand: Option<Subcommand>,
Expand Down Expand Up @@ -98,7 +111,11 @@ impl RelayChainCli {
) -> Self {
let extension = crate::chain_spec::Extensions::try_get(&*para_config.chain_spec);
let chain_id = extension.map(|e| e.relay_chain.clone());
let base_path = para_config.base_path.as_ref().map(|x| x.path().join("polkadot"));
Self { base_path, chain_id, base: clap::Parser::parse_from(relay_chain_args) }
let base_path = para_config.base_path.path().join("polkadot");
Self {
base_path: Some(base_path),
chain_id,
base: clap::Parser::parse_from(relay_chain_args),
}
}
}
97 changes: 34 additions & 63 deletions node/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,21 @@

use std::net::SocketAddr;

use codec::Encode;
use cumulus_client_cli::generate_genesis_block;
use cumulus_primitives_core::ParaId;
use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};
use log::{info, warn};
use subsocial_parachain_runtime::Block;
use sc_cli::{
ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,
NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,
NetworkParams, Result, SharedParams, SubstrateCli,
};
use sc_service::config::{BasePath, PrometheusConfig};
use sp_core::hexdisplay::HexDisplay;
use sp_runtime::traits::{AccountIdConversion, Block as BlockT};
use sp_runtime::traits::AccountIdConversion;

use crate::{
chain_spec,
cli::{Cli, RelayChainCli, Subcommand},
service::{new_partial, ParachainNativeExecutor},
service::new_partial,
};

fn load_spec(id: &str) -> std::result::Result<Box<dyn ChainSpec>, String> {
Expand Down Expand Up @@ -66,10 +63,6 @@ impl SubstrateCli for Cli {
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
load_spec(id)
}

fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
&subsocial_parachain_runtime::VERSION
}
}

impl SubstrateCli for RelayChainCli {
Expand Down Expand Up @@ -100,10 +93,6 @@ impl SubstrateCli for RelayChainCli {
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)
}

fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
polkadot_cli::Cli::native_runtime_version(chain_spec)
}
}

macro_rules! construct_async_run {
Expand Down Expand Up @@ -172,10 +161,10 @@ pub fn run() -> Result<()> {
},
Some(Subcommand::ExportGenesisState(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|_config| {
let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
let state_version = Cli::native_runtime_version(&spec).state_version();
cmd.run::<Block>(&*spec, state_version)
runner.sync_run(|config| {
let partials = new_partial(&config)?;

cmd.run(&*config.chain_spec, &*partials.client)
})
},
Some(Subcommand::ExportGenesisWasm(cmd)) => {
Expand All @@ -191,7 +180,7 @@ pub fn run() -> Result<()> {
match cmd {
BenchmarkCmd::Pallet(cmd) =>
if cfg!(feature = "runtime-benchmarks") {
runner.sync_run(|config| cmd.run::<Block, ParachainNativeExecutor>(config))
runner.sync_run(|config| cmd.run::<Block, ()>(config))
} else {
Err("Benchmarking wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`."
Expand Down Expand Up @@ -228,14 +217,11 @@ pub fn run() -> Result<()> {
#[cfg(feature = "try-runtime")]
Some(Subcommand::TryRuntime(cmd)) => {
use subsocial_parachain_runtime::MILLISECS_PER_BLOCK;
use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};
use try_runtime_cli::block_building_info::timestamp_with_aura_info;
let runner = cli.create_runner(cmd)?;

type HostFunctionsOf<E> = ExtendedHostFunctions<
sp_io::SubstrateHostFunctions,
<E as NativeExecutionDispatch>::ExtendHostFunctions,
>;
type HostFunctions =
(sp_io::SubstrateHostFunctions, frame_benchmarking::benchmarking::HostFunctions);

// grab the task manager.
let registry = &runner.config().prometheus_config.as_ref().map(|cfg| &cfg.registry);
Expand All @@ -246,12 +232,7 @@ pub fn run() -> Result<()> {
let info_provider = timestamp_with_aura_info(MILLISECS_PER_BLOCK);

runner.async_run(|_| {
Ok((
cmd.run::<Block, HostFunctionsOf<ParachainNativeExecutor>, _>(Some(
info_provider,
)),
task_manager,
))
Ok((cmd.run::<Block, HostFunctions, _>(Some(info_provider)), task_manager))
})
},
#[cfg(not(feature = "try-runtime"))]
Expand All @@ -263,15 +244,16 @@ pub fn run() -> Result<()> {
let collator_options = cli.run.collator_options();

runner.run_node_until_exit(|config| async move {
let hwbench = (!cli.no_hardware_benchmarks).then_some(
config.database.path().map(|database_path| {
let _ = std::fs::create_dir_all(&database_path);
let hwbench = (!cli.no_hardware_benchmarks)
.then_some(config.database.path().map(|database_path| {
let _ = std::fs::create_dir_all(database_path);
sc_sysinfo::gather_hwbench(Some(database_path))
})).flatten();
}))
.flatten();

let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)
.map(|e| e.para_id)
.ok_or_else(|| "Could not find parachain ID in chain-spec.")?;
.ok_or("Could not find parachain ID in chain-spec.")?;

let polkadot_cli = RelayChainCli::new(
&config,
Expand All @@ -281,25 +263,26 @@ pub fn run() -> Result<()> {
let id = ParaId::from(para_id);

let parachain_account =
AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(&id);

let state_version = Cli::native_runtime_version(&config.chain_spec).state_version();
let block: Block = generate_genesis_block(&*config.chain_spec, state_version)
.map_err(|e| format!("{:?}", e))?;
let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));
AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(
&id,
);

let tokio_handle = config.tokio_handle.clone();
let polkadot_config =
SubstrateCli::create_configuration(&polkadot_cli, &polkadot_cli, tokio_handle)
.map_err(|err| format!("Relay chain argument error: {}", err))?;

info!("Parachain id: {:?}", id);
info!("Parachain Account: {}", parachain_account);
info!("Parachain genesis state: {}", genesis_state);
info!("Parachain Account: {parachain_account}");
info!("Is collating: {}", if config.role.is_authority() { "yes" } else { "no" });

if !collator_options.relay_chain_rpc_urls.is_empty() && cli.relay_chain_args.len() > 0 {
warn!("Detected relay chain node arguments together with --relay-chain-rpc-url. This command starts a minimal Polkadot node that only uses a network-related subset of all relay chain CLI options.");
if !collator_options.relay_chain_rpc_urls.is_empty() &&
!cli.relay_chain_args.is_empty()
{
warn!(
"Detected relay chain node arguments together with --relay-chain-rpc-url. \
This command starts a minimal Polkadot node that only uses a \
network-related subset of all relay chain CLI options."
);
}

crate::service::start_parachain_node(
Expand All @@ -322,14 +305,10 @@ impl DefaultConfigurationValues for RelayChainCli {
30334
}

fn rpc_ws_listen_port() -> u16 {
fn rpc_listen_port() -> u16 {
9945
}

fn rpc_http_listen_port() -> u16 {
9934
}

fn prometheus_listen_port() -> u16 {
9616
}
Expand Down Expand Up @@ -359,16 +338,8 @@ impl CliConfiguration<Self> for RelayChainCli {
.or_else(|| self.base_path.clone().map(Into::into)))
}

fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {
self.base.base.rpc_http(default_listen_port)
}

fn rpc_ipc(&self) -> Result<Option<String>> {
self.base.base.rpc_ipc()
}

fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {
self.base.base.rpc_ws(default_listen_port)
fn rpc_addr(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {
self.base.base.rpc_addr(default_listen_port)
}

fn prometheus_config(
Expand Down Expand Up @@ -414,8 +385,8 @@ impl CliConfiguration<Self> for RelayChainCli {
self.base.base.rpc_methods()
}

fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {
self.base.base.rpc_ws_max_connections()
fn rpc_max_connections(&self) -> Result<u32> {
self.base.base.rpc_max_connections()
}

fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {
Expand Down
20 changes: 10 additions & 10 deletions node/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

use std::sync::Arc;

use subsocial_parachain_runtime::{opaque::Block, AccountId, Balance, Index as Nonce};
use subsocial_parachain_runtime::{opaque::Block, AccountId, Balance, Nonce};

use sc_client_api::AuxStore;
pub use sc_rpc::{DenyUnsafe, SubscriptionTaskExecutor};
Expand Down Expand Up @@ -48,27 +48,27 @@ where
+ Sync
+ 'static,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: pallet_creator_staking_rpc::CreatorStakingRuntimeApi<Block, AccountId, Balance>,
C::Api: pallet_domains_rpc::DomainsRuntimeApi<Block, Balance>,
C::Api: pallet_posts_rpc::PostsRuntimeApi<Block, AccountId>,
// C::Api: pallet_creator_staking_rpc::CreatorStakingRuntimeApi<Block, AccountId, Balance>,
// C::Api: pallet_domains_rpc::DomainsRuntimeApi<Block, Balance>,
// C::Api: pallet_posts_rpc::PostsRuntimeApi<Block, AccountId>,
C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>,
C::Api: BlockBuilder<Block>,
P: TransactionPool + Sync + Send + 'static,
{
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
use pallet_creator_staking_rpc::{CreatorStaking, CreatorStakingApiServer};
use pallet_domains_rpc::{Domains, DomainsApiServer};
use pallet_posts_rpc::{Posts, PostsApiServer};
// use pallet_creator_staking_rpc::{CreatorStaking, CreatorStakingApiServer};
// use pallet_domains_rpc::{Domains, DomainsApiServer};
// use pallet_posts_rpc::{Posts, PostsApiServer};
use substrate_frame_rpc_system::{System, SystemApiServer};

let mut module = RpcExtension::new(());
let FullDeps { client, pool, deny_unsafe } = deps;

module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?;
module.merge(TransactionPayment::new(client.clone()).into_rpc())?;
module.merge(CreatorStaking::new(client.clone()).into_rpc())?;
module.merge(Domains::new(client.clone()).into_rpc())?;
module.merge(Posts::new(client).into_rpc())?;
// module.merge(CreatorStaking::new(client.clone()).into_rpc())?;
// module.merge(Domains::new(client.clone()).into_rpc())?;
// module.merge(Posts::new(client).into_rpc())?;

Ok(module)
}
Loading

0 comments on commit 4bf7141

Please sign in to comment.