From 4bf71413c8362b96cb07c6c4dccac3c19b424094 Mon Sep 17 00:00:00 2001 From: Vlad Proshchavaiev <32250097+F3Joule@users.noreply.github.com> Date: Fri, 15 Nov 2024 12:06:50 +0200 Subject: [PATCH] Update pallets, runtime and node code to v1.0 --- node/src/chain_spec.rs | 15 +- node/src/cli.rs | 21 +- node/src/command.rs | 97 +++------ node/src/rpc.rs | 20 +- node/src/service.rs | 63 ++++-- pallets/creator-staking/src/lib.rs | 6 +- pallets/creator-staking/src/migration.rs | 5 +- pallets/creator-staking/src/tests/mock.rs | 78 ++++--- .../src/tests/testing_utils.rs | 2 +- pallets/domains/src/lib.rs | 6 +- pallets/domains/src/migration.rs | 9 +- pallets/domains/src/mock.rs | 38 ++-- pallets/domains/src/types.rs | 6 +- pallets/energy/src/mock.rs | 68 +++--- pallets/energy/src/tests.rs | 18 +- pallets/evm-addresses/src/evm.rs | 4 +- pallets/evm-addresses/src/mock.rs | 29 +-- pallets/free-proxy/src/lib.rs | 2 +- pallets/free-proxy/src/mock.rs | 33 ++- pallets/ownership/src/migration.rs | 4 +- pallets/ownership/tests/src/mock.rs | 17 +- pallets/ownership/tests/src/tests_utils.rs | 5 +- pallets/posts/tests/src/mock.rs | 19 +- pallets/posts/tests/src/tests_utils.rs | 10 +- pallets/profiles/src/mock.rs | 22 +- pallets/reactions/tests/src/mock.rs | 18 +- pallets/reactions/tests/src/tests_utils.rs | 6 +- pallets/resource-discussions/src/mock.rs | 27 +-- pallets/roles/src/benchmarking.rs | 3 +- pallets/roles/src/functions.rs | 5 +- pallets/roles/src/lib.rs | 2 +- pallets/roles/src/mock.rs | 49 ++--- pallets/roles/src/types.rs | 3 +- pallets/space-follows/tests/src/mock.rs | 18 +- .../space-follows/tests/src/tests_utils.rs | 16 +- pallets/spaces/src/lib.rs | 5 +- pallets/spaces/tests/src/mock.rs | 21 +- pallets/spaces/tests/src/tests_utils.rs | 6 +- pallets/support/src/lib.rs | 5 +- runtime/build.rs | 10 +- runtime/src/lib.rs | 205 +++++++++--------- runtime/src/weights/mod.rs | 2 +- runtime/src/xcm_config.rs | 32 ++- 43 files changed, 522 insertions(+), 508 deletions(-) diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index 62c0ca6d..75728788 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -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; + sc_service::GenericChainSpec; /// The default XCM version to set in genesis config. const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION; @@ -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, + pub bad_blocks: sc_client_api::BadBlocks, } impl Extensions { @@ -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, @@ -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()), diff --git a/node/src/cli.rs b/node/src/cli.rs index 998bb0c1..952ed8de 100644 --- a/node/src/cli.rs +++ b/node/src/cli.rs @@ -50,12 +50,25 @@ pub enum Subcommand { TryRuntime, } +const AFTER_HELP_EXAMPLE: &str = color_print::cstr!( + r#"Examples: + subsocial-node build-spec --disable-default-bootnode > plain-subsocial-chainspec.json + Export a chainspec for a local testnet in json format. + subsocial-node --chain plain-subsocial-chainspec.json --tmp -- --chain rococo-local + Launch a full node with chain specification loaded from plain-subsocial-chainspec.json. + subsocial-node + Launch a full node with default parachain local-testnet and relay chain rococo-local. + subsocial-node --collator + Launch a collator with default parachain local-testnet and relay chain 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, @@ -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), + } } } diff --git a/node/src/command.rs b/node/src/command.rs index 86e6531d..972ed660 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -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, String> { @@ -66,10 +63,6 @@ impl SubstrateCli for Cli { fn load_spec(&self, id: &str) -> std::result::Result, String> { load_spec(id) } - - fn native_runtime_version(_: &Box) -> &'static RuntimeVersion { - &subsocial_parachain_runtime::VERSION - } } impl SubstrateCli for RelayChainCli { @@ -100,10 +93,6 @@ impl SubstrateCli for RelayChainCli { fn load_spec(&self, id: &str) -> std::result::Result, String> { polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id) } - - fn native_runtime_version(chain_spec: &Box) -> &'static RuntimeVersion { - polkadot_cli::Cli::native_runtime_version(chain_spec) - } } macro_rules! construct_async_run { @@ -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::(&*spec, state_version) + runner.sync_run(|config| { + let partials = new_partial(&config)?; + + cmd.run(&*config.chain_spec, &*partials.client) }) }, Some(Subcommand::ExportGenesisWasm(cmd)) => { @@ -191,7 +180,7 @@ pub fn run() -> Result<()> { match cmd { BenchmarkCmd::Pallet(cmd) => if cfg!(feature = "runtime-benchmarks") { - runner.sync_run(|config| cmd.run::(config)) + runner.sync_run(|config| cmd.run::(config)) } else { Err("Benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." @@ -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 = ExtendedHostFunctions< - sp_io::SubstrateHostFunctions, - ::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); @@ -246,12 +232,7 @@ pub fn run() -> Result<()> { let info_provider = timestamp_with_aura_info(MILLISECS_PER_BLOCK); runner.async_run(|_| { - Ok(( - cmd.run::, _>(Some( - info_provider, - )), - task_manager, - )) + Ok((cmd.run::(Some(info_provider)), task_manager)) }) }, #[cfg(not(feature = "try-runtime"))] @@ -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, @@ -281,25 +263,26 @@ pub fn run() -> Result<()> { let id = ParaId::from(para_id); let parachain_account = - AccountIdConversion::::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::::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( @@ -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 } @@ -359,16 +338,8 @@ impl CliConfiguration for RelayChainCli { .or_else(|| self.base_path.clone().map(Into::into))) } - fn rpc_http(&self, default_listen_port: u16) -> Result> { - self.base.base.rpc_http(default_listen_port) - } - - fn rpc_ipc(&self) -> Result> { - self.base.base.rpc_ipc() - } - - fn rpc_ws(&self, default_listen_port: u16) -> Result> { - self.base.base.rpc_ws(default_listen_port) + fn rpc_addr(&self, default_listen_port: u16) -> Result> { + self.base.base.rpc_addr(default_listen_port) } fn prometheus_config( @@ -414,8 +385,8 @@ impl CliConfiguration for RelayChainCli { self.base.base.rpc_methods() } - fn rpc_ws_max_connections(&self) -> Result> { - self.base.base.rpc_ws_max_connections() + fn rpc_max_connections(&self) -> Result { + self.base.base.rpc_max_connections() } fn rpc_cors(&self, is_dev: bool) -> Result>> { diff --git a/node/src/rpc.rs b/node/src/rpc.rs index 6254bfdb..717ac08d 100644 --- a/node/src/rpc.rs +++ b/node/src/rpc.rs @@ -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}; @@ -48,17 +48,17 @@ where + Sync + 'static, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: pallet_creator_staking_rpc::CreatorStakingRuntimeApi, - C::Api: pallet_domains_rpc::DomainsRuntimeApi, - C::Api: pallet_posts_rpc::PostsRuntimeApi, + // C::Api: pallet_creator_staking_rpc::CreatorStakingRuntimeApi, + // C::Api: pallet_domains_rpc::DomainsRuntimeApi, + // C::Api: pallet_posts_rpc::PostsRuntimeApi, C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: BlockBuilder, 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(()); @@ -66,9 +66,9 @@ where 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) } diff --git a/node/src/service.rs b/node/src/service.rs index 41324562..de94c021 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -27,13 +27,17 @@ use cumulus_relay_chain_interface::RelayChainInterface; // Substrate Imports use frame_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE; +use sc_client_api::Backend; use sc_consensus::ImportQueue; -use sc_executor::NativeElseWasmExecutor; +use sc_executor::{ + HeapAllocStrategy, NativeElseWasmExecutor, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY, +}; use sc_network::NetworkBlock; use sc_network_sync::SyncingService; use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager}; use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle}; -use sp_keystore::SyncCryptoStorePtr; +use sc_transaction_pool_api::OffchainTransactionPoolFactory; +use sp_keystore::KeystorePtr; use substrate_prometheus_endpoint::Registry; /// Native executor type. @@ -87,12 +91,19 @@ pub fn new_partial( }) .transpose()?; - let executor = ParachainExecutor::new( - config.wasm_method, - config.default_heap_pages, - config.max_runtime_instances, - config.runtime_cache_size, - ); + let heap_pages = config + .default_heap_pages + .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ }); + + let wasm = WasmExecutor::builder() + .with_execution_method(config.wasm_method) + .with_onchain_heap_alloc_strategy(heap_pages) + .with_offchain_heap_alloc_strategy(heap_pages) + .with_max_runtime_instances(config.max_runtime_instances) + .with_runtime_cache_size(config.runtime_cache_size) + .build(); + + let executor = ParachainExecutor::new_with_wasm_executor(wasm); let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::( @@ -154,6 +165,7 @@ async fn start_node_impl( let params = new_partial(¶chain_config)?; let (block_import, mut telemetry, telemetry_worker_handle) = params.other; + let net_config = sc_network::config::FullNetworkConfiguration::new(¶chain_config.network); let client = params.client.clone(); let backend = params.backend.clone(); @@ -179,6 +191,7 @@ async fn start_node_impl( let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = build_network(BuildNetworkParams { parachain_config: ¶chain_config, + net_config, client: client.clone(), transaction_pool: transaction_pool.clone(), para_id, @@ -189,11 +202,25 @@ async fn start_node_impl( .await?; if parachain_config.offchain_worker.enabled { - sc_service::build_offchain_workers( - ¶chain_config, - task_manager.spawn_handle(), - client.clone(), - network.clone(), + use futures::FutureExt; + + task_manager.spawn_handle().spawn( + "offchain-workers-runner", + "offchain-work", + sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions { + runtime_api_provider: client.clone(), + keystore: Some(params.keystore_container.keystore()), + offchain_db: backend.offchain_storage(), + transaction_pool: Some(OffchainTransactionPoolFactory::new( + transaction_pool.clone(), + )), + network_provider: network.clone(), + is_validator: parachain_config.role.is_authority(), + enable_http_requests: false, + custom_extensions: move |_| vec![], + }) + .run(client.clone(), task_manager.spawn_handle()) + .boxed(), ); } @@ -218,7 +245,7 @@ async fn start_node_impl( transaction_pool: transaction_pool.clone(), task_manager: &mut task_manager, config: parachain_config, - keystore: params.keystore_container.sync_keystore(), + keystore: params.keystore_container.keystore(), backend, network: network.clone(), sync_service: sync_service.clone(), @@ -268,8 +295,8 @@ async fn start_node_impl( &task_manager, relay_chain_interface.clone(), transaction_pool, - sync_service, - params.keystore_container.sync_keystore(), + sync_service.clone(), + params.keystore_container.keystore(), force_authoring, para_id, )?; @@ -288,6 +315,7 @@ async fn start_node_impl( collator_key: collator_key.expect("Command line arguments do not allow this. qed"), relay_chain_slot_duration, recovery_handle: Box::new(overseer_handle), + sync_service, }; start_collator(params).await?; @@ -301,6 +329,7 @@ async fn start_node_impl( relay_chain_slot_duration, import_queue: import_queue_service, recovery_handle: Box::new(overseer_handle), + sync_service, }; start_full_node(params)?; @@ -358,7 +387,7 @@ fn build_consensus( relay_chain_interface: Arc, transaction_pool: Arc>, sync_oracle: Arc>, - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, force_authoring: bool, para_id: ParaId, ) -> Result>, sc_service::Error> { diff --git a/pallets/creator-staking/src/lib.rs b/pallets/creator-staking/src/lib.rs index 5fd772e2..ee64d6f9 100644 --- a/pallets/creator-staking/src/lib.rs +++ b/pallets/creator-staking/src/lib.rs @@ -51,7 +51,7 @@ pub mod pallet { type BlockPerEra: Get>; /// The currency trait. - type Currency: LockableCurrency + type Currency: LockableCurrency> + ReservableCurrency; type SpacesProvider: SpacesProvider; @@ -116,7 +116,7 @@ pub mod pallet { /// Represents the estimated number of blocks that are generated within the span of one year. #[pallet::constant] - type BlocksPerYear: Get; + type BlocksPerYear: Get>; /// The chain's treasury account, where we deposit leftover tokens after distributing rewards, /// not to make any extra tokens left on a rewards holding account. @@ -164,7 +164,7 @@ pub mod pallet { #[pallet::storage] #[pallet::whitelist_storage] #[pallet::getter(fn next_era_starting_block)] - pub type NextEraStartingBlock = StorageValue<_, T::BlockNumber, ValueQuery>; + pub type NextEraStartingBlock = StorageValue<_, BlockNumberFor, ValueQuery>; #[pallet::storage] #[pallet::getter(fn registered_creator)] diff --git a/pallets/creator-staking/src/migration.rs b/pallets/creator-staking/src/migration.rs index df03be36..18e7587a 100644 --- a/pallets/creator-staking/src/migration.rs +++ b/pallets/creator-staking/src/migration.rs @@ -11,6 +11,7 @@ use frame_support::{ traits::OnRuntimeUpgrade, weights::Weight, }; +use sp_runtime::DispatchError; use sp_runtime::traits::Zero; use sp_std::vec::Vec; @@ -110,7 +111,7 @@ impl OnRuntimeUpgrade for MigrateToV1 { } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, &'static str> { + fn pre_upgrade() -> Result, DispatchError> { let current_version = Pallet::::current_storage_version(); let onchain_version = Pallet::::on_chain_storage_version(); ensure!(onchain_version == 0 && current_version == 1, "migration from version 0 to 1."); @@ -119,7 +120,7 @@ impl OnRuntimeUpgrade for MigrateToV1 { } #[cfg(feature = "try-runtime")] - fn post_upgrade(prev_count: Vec) -> Result<(), &'static str> { + fn post_upgrade(prev_count: Vec) -> Result<(), DispatchError> { let prev_count: u32 = Decode::decode(&mut prev_count.as_slice()) .expect("the state parameter should be something that was generated by pre_upgrade"); let post_count = crate::BackerStakesByCreator::::iter().count() as u32; diff --git a/pallets/creator-staking/src/tests/mock.rs b/pallets/creator-staking/src/tests/mock.rs index 546f28a1..41d07760 100644 --- a/pallets/creator-staking/src/tests/mock.rs +++ b/pallets/creator-staking/src/tests/mock.rs @@ -4,12 +4,13 @@ // Full notice is available at https://github.com/dappforce/subsocial-parachain/blob/main/COPYRIGHT // Full license is available at https://github.com/dappforce/subsocial-parachain/blob/main/LICENSE -use crate::{self as pallet_creator_staking, PalletDisabled}; +use crate::PalletDisabled; use frame_support::{ - construct_runtime, parameter_types, - traits::{Currency, OnFinalize, OnInitialize}, + construct_runtime, dispatch::DispatchResult, + parameter_types, + traits::{Currency, OnFinalize, OnInitialize}, weights::Weight, PalletId, }; @@ -19,7 +20,10 @@ use mockall::mock; use sp_core::H256; use sp_io::TestExternalities; -use sp_runtime::{DispatchError, testing::Header, traits::{BlakeTwo256, ConstU32, IdentityLookup}}; +use sp_runtime::{ + traits::{BlakeTwo256, ConstU32, IdentityLookup}, + BuildStorage, DispatchError, +}; use sp_std::sync::{Mutex, MutexGuard}; pub(super) type AccountId = u64; @@ -27,21 +31,23 @@ pub(super) type BlockNumber = u64; pub(super) type Balance = u128; pub(super) type EraIndex = u32; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; -/// Value shouldn't be less than 2 for testing purposes, otherwise we cannot test certain corner cases. +/// Value shouldn't be less than 2 for testing purposes, otherwise we cannot test certain corner +/// cases. pub(super) const EXISTENTIAL_DEPOSIT: Balance = 2; pub(super) const REGISTER_DEPOSIT: Balance = 10; pub(super) const MAX_NUMBER_OF_BACKERS: u32 = 4; -/// Value shouldn't be less than 2 for testing purposes, otherwise we cannot test certain corner cases. +/// Value shouldn't be less than 2 for testing purposes, otherwise we cannot test certain corner +/// cases. pub(super) const MINIMUM_TOTAL_STAKE: Balance = 10; pub(super) const MINIMUM_REMAINING_AMOUNT: Balance = 1; pub(super) const MAX_UNBONDING_CHUNKS: u32 = 5; pub(super) const UNBONDING_PERIOD_IN_ERAS: EraIndex = 3; pub(super) const MAX_ERA_STAKE_ITEMS: u32 = 8; -// Do note that this needs to at least be 3 for tests to be valid. It can be greater but not smaller. +// Do note that this needs to at least be 3 for tests to be valid. It can be greater but not +// smaller. pub(super) const BLOCKS_PER_ERA: BlockNumber = 3; pub(super) const BLOCKS_PER_YEAR: BlockNumber = 2628000; pub(super) const BLOCK_REWARD: Balance = 100; @@ -49,16 +55,11 @@ pub(super) const BLOCK_REWARD: Balance = 100; pub(super) const TREASURY_ACCOUNT: BlockNumber = 42; construct_runtime!( - pub struct TestRuntime - where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub struct TestRuntime { System: frame_system, Balances: pallet_balances, Timestamp: pallet_timestamp, - CreatorStaking: pallet_creator_staking, + CreatorStaking: crate, } ); @@ -73,14 +74,13 @@ impl frame_system::Config for TestRuntime { type BlockWeights = (); type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; - type Index = u64; + type Nonce = u64; type RuntimeCall = RuntimeCall; - type BlockNumber = BlockNumber; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -110,6 +110,10 @@ impl pallet_balances::Config for TestRuntime { type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); + type MaxHolds = (); + type MaxFreezes = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); } parameter_types! { @@ -123,11 +127,12 @@ impl pallet_timestamp::Config for TestRuntime { type WeightInfo = (); } -use pallet_permissions::default_permissions::DefaultSpacePermissions; -use pallet_permissions::SpacePermissionsInfoOf; -use subsocial_support::{Content, SpaceId}; -use subsocial_support::traits::{SpacePermissionsProvider, SpacesProvider}; use crate::tests::tests::Rewards; +use pallet_permissions::{default_permissions::DefaultSpacePermissions, SpacePermissionsInfoOf}; +use subsocial_support::{ + traits::{SpacePermissionsProvider, SpacesProvider}, + Content, SpaceId, +}; impl pallet_permissions::Config for TestRuntime { type DefaultSpacePermissions = DefaultSpacePermissions; @@ -160,7 +165,7 @@ mock! { impl SpacesProvider for Spaces { fn get_space_owner(_space_id: SpaceId) -> Result; - + fn do_update_space_owner(_space_id: SpaceId, _new_owner: AccountId) -> DispatchResult; fn create_space(_owner: &AccountId, _content: Content) -> Result; @@ -179,7 +184,7 @@ pub(super) fn use_static_mock() -> MutexGuard<'static, ()> { } } -impl pallet_creator_staking::Config for TestRuntime { +impl crate::Config for TestRuntime { type RuntimeEvent = RuntimeEvent; type PalletId = CreatorStakingPalletId; type BlockPerEra = BlockPerEra; @@ -205,9 +210,7 @@ pub struct ExternalityBuilder; impl ExternalityBuilder { pub fn build() -> TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![ @@ -230,7 +233,7 @@ impl ExternalityBuilder { .assimilate_storage(&mut storage) .ok(); - let mut ext = TestExternalities::from(storage); + let mut ext: TestExternalities = storage.into(); ext.execute_with(|| { System::set_block_number(1); // TODO: revert when default PalletDisabled changed back to false @@ -266,7 +269,8 @@ pub fn advance_to_era(n: EraIndex) { } /// Initialize first block. -/// This method should only be called once in a UT otherwise the first block will get initialized multiple times. +/// This method should only be called once in a UT otherwise the first block will get initialized +/// multiple times. pub fn initialize_first_block() { // This assert prevents method misuse assert_eq!(System::block_number(), 1 as BlockNumber); @@ -294,12 +298,14 @@ pub fn creator_staking_events() -> Vec> { System::events() .into_iter() .map(|r| r.event) - .filter_map(|e| { - if let RuntimeEvent::CreatorStaking(inner) = e { - Some(inner) - } else { - None - } - }) + .filter_map( + |e| { + if let RuntimeEvent::CreatorStaking(inner) = e { + Some(inner) + } else { + None + } + }, + ) .collect() } diff --git a/pallets/creator-staking/src/tests/testing_utils.rs b/pallets/creator-staking/src/tests/testing_utils.rs index 55e4a83a..6878825c 100644 --- a/pallets/creator-staking/src/tests/testing_utils.rs +++ b/pallets/creator-staking/src/tests/testing_utils.rs @@ -509,7 +509,7 @@ fn assert_restake_reward( ) { if CreatorStaking::can_restake_reward( restake, - init_state_current_era.clone().creator_info.status, + init_state_current_era.creator_info.status, init_state_current_era.backer_stakes.staked, ) { // staked values should increase diff --git a/pallets/domains/src/lib.rs b/pallets/domains/src/lib.rs index 1ded0e0e..d0605e87 100644 --- a/pallets/domains/src/lib.rs +++ b/pallets/domains/src/lib.rs @@ -72,7 +72,7 @@ pub mod pallet { /// The maximum period of time the domain may be held for. #[pallet::constant] - type RegistrationPeriodLimit: Get; + type RegistrationPeriodLimit: Get>; /// The maximum length of the domain's outer value. #[pallet::constant] @@ -242,7 +242,7 @@ pub mod pallet { alt_recipient: Option<::Source>, full_domain: DomainName, content: Content, - expires_in: T::BlockNumber, + expires_in: BlockNumberFor, ) -> DispatchResult { let caller = ensure_signed(origin)?; let recipient = alt_recipient @@ -435,7 +435,7 @@ pub mod pallet { recipient: T::AccountId, full_domain: DomainName, content: Content, - expires_in: T::BlockNumber, + expires_in: BlockNumberFor, ) -> DispatchResult { ensure!(!expires_in.is_zero(), Error::::ZeroReservationPeriod); ensure!( diff --git a/pallets/domains/src/migration.rs b/pallets/domains/src/migration.rs index fcd6934f..6301cd56 100644 --- a/pallets/domains/src/migration.rs +++ b/pallets/domains/src/migration.rs @@ -13,9 +13,8 @@ use super::*; pub mod v1 { use frame_support::{pallet_prelude::*, weights::Weight}; - + use frame_system::pallet_prelude::BlockNumberFor; use subsocial_support::WhoAndWhenOf; - use crate::types::*; use super::*; @@ -25,7 +24,7 @@ pub mod v1 { pub struct OldDomainMeta { pub(super) created: WhoAndWhenOf, pub(super) updated: Option>, - pub(super) expires_at: T::BlockNumber, + pub(super) expires_at: BlockNumberFor, pub(super) owner: T::AccountId, pub(super) content: Content, pub(super) inner_value: Option>, @@ -95,7 +94,7 @@ pub mod v1 { } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, &'static str> { + fn pre_upgrade() -> Result, DispatchError> { #[frame_support::storage_alias] type RegisteredDomains = StorageMap, Blake2_128Concat, DomainName, OldDomainMeta>; @@ -108,7 +107,7 @@ pub mod v1 { } #[cfg(feature = "try-runtime")] - fn post_upgrade(prev_count: Vec) -> Result<(), &'static str> { + fn post_upgrade(prev_count: Vec) -> Result<(), DispatchError> { let prev_count: u32 = Decode::decode(&mut prev_count.as_slice()).expect( "the state parameter should be something that was generated by pre_upgrade", ); diff --git a/pallets/domains/src/mock.rs b/pallets/domains/src/mock.rs index 80bb9489..071fa3f7 100644 --- a/pallets/domains/src/mock.rs +++ b/pallets/domains/src/mock.rs @@ -8,11 +8,10 @@ use frame_support::{ assert_ok, dispatch::DispatchResult, parameter_types, traits::{Currency, Everything}, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_core::H256; use sp_io::TestExternalities; -use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, -}; +use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, BuildStorage}; use sp_std::convert::{TryInto, TryFrom}; use subsocial_support::Content; @@ -21,15 +20,10 @@ use subsocial_support::mock_functions::{another_valid_content_ipfs, valid_conten pub(crate) use crate as pallet_domains; use crate::types::*; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Timestamp: pallet_timestamp, Balances: pallet_balances, @@ -39,7 +33,6 @@ frame_support::construct_runtime!( pub(super) type AccountId = u64; pub(super) type Balance = u64; -type BlockNumber = u64; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -52,13 +45,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -98,6 +90,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxFreezes = (); + type MaxHolds = (); } pub(super) const DEFAULT_DOMAIN_DEPOSIT: Balance = 10; @@ -109,7 +105,7 @@ parameter_types! { pub static MaxDomainsPerAccount: u32 = 0; pub const DomainsInsertLimit: u32 = 2860; - pub static ReservationPeriodLimit: BlockNumber = 0; + pub static ReservationPeriodLimit: BlockNumberFor = 0; pub const MaxOuterValueLength: u16 = 256; pub static BaseDomainDeposit: Balance = DEFAULT_DOMAIN_DEPOSIT; @@ -217,7 +213,7 @@ pub(crate) fn _force_register_domain_with_origin(origin: RuntimeOrigin) -> Dispa _register_domain(Some(origin), None, None, None, None) } -pub(crate) fn _force_register_domain_with_expires_in(expires_in: BlockNumber) -> DispatchResult { +pub(crate) fn _force_register_domain_with_expires_in(expires_in: BlockNumberFor) -> DispatchResult { _register_domain(domain_registrar_origin(), None, None, None, Some(expires_in)) } @@ -234,7 +230,7 @@ pub(crate) fn _register_domain( recipient: Option>, domain: Option>, content: Option, - expires_in: Option, + expires_in: Option>, ) -> DispatchResult { Domains::register_domain( origin.unwrap_or_else(|| RuntimeOrigin::signed(DOMAIN_OWNER)), @@ -334,7 +330,7 @@ pub(crate) fn get_reserved_balance(who: &AccountId) -> BalanceOf { pub struct ExtBuilder { pub(crate) min_domain_length: u32, pub(crate) max_domains_per_account: u32, - pub(crate) reservation_period_limit: BlockNumber, + pub(crate) reservation_period_limit: BlockNumberFor, pub(crate) base_domain_deposit: Balance, pub(crate) outer_value_byte_deposit: Balance, pub(crate) initial_prices_config: PricesConfigVec, @@ -368,7 +364,7 @@ impl ExtBuilder { self } - pub(crate) fn reservation_period_limit(mut self, reservation_period_limit: BlockNumber) -> Self { + pub(crate) fn reservation_period_limit(mut self, reservation_period_limit: BlockNumberFor) -> Self { self.reservation_period_limit = reservation_period_limit; self } @@ -400,11 +396,7 @@ impl ExtBuilder { pub(crate) fn build(self) -> TestExternalities { self.set_configs(); - let storage = &mut frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - - let mut ext = TestExternalities::from(storage.clone()); + let mut ext: TestExternalities = frame_system::GenesisConfig::::default().build_storage().unwrap().into(); ext.execute_with(|| { System::set_block_number(1); assert_ok!( diff --git a/pallets/domains/src/types.rs b/pallets/domains/src/types.rs index 1d778cae..0ade7be3 100644 --- a/pallets/domains/src/types.rs +++ b/pallets/domains/src/types.rs @@ -6,11 +6,11 @@ use frame_support::pallet_prelude::*; use frame_support::traits::Currency; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::traits::Zero; use sp_std::vec::Vec; use subsocial_support::{WhoAndWhenOf, new_who_and_when}; - use super::*; pub(crate) type DomainName = BoundedVec::MaxDomainLength>; @@ -63,7 +63,7 @@ pub struct DomainMeta { pub(super) updated: Option>, /// Specific block, when the domain will become unavailable. - pub(super) expires_at: T::BlockNumber, + pub(super) expires_at: BlockNumberFor, /// The domain owner. pub(super) owner: T::AccountId, @@ -87,7 +87,7 @@ impl DomainMeta { pub fn new( caller: T::AccountId, owner: T::AccountId, - expires_at: T::BlockNumber, + expires_at: BlockNumberFor, content: Content, domain_deposit: DomainDepositOf, ) -> Self { diff --git a/pallets/energy/src/mock.rs b/pallets/energy/src/mock.rs index 11fddb01..999ed266 100644 --- a/pallets/energy/src/mock.rs +++ b/pallets/energy/src/mock.rs @@ -4,52 +4,48 @@ // Full notice is available at https://github.com/dappforce/subsocial-parachain/blob/main/COPYRIGHT // Full license is available at https://github.com/dappforce/subsocial-parachain/blob/main/LICENSE -use scale_info::TypeInfo; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ - dispatch::{RawOrigin, DispatchInfo}, + dispatch::{DispatchInfo, RawOrigin}, pallet_prelude::{DispatchClass, Pays, Weight}, parameter_types, - traits::{ConstU8, Currency, EnsureOrigin, Everything, Get, Imbalance, IsType}, + traits::{ConstU8, Currency, EnsureOrigin, Everything, Get, Imbalance, InstanceFilter, IsType}, weights::{ - WeightToFee, WeightToFeeCoefficient, WeightToFeeCoefficients, - WeightToFeePolynomial, + WeightToFee, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }, }; -use frame_support::traits::InstanceFilter; use pallet_balances::NegativeImbalance; use pallet_transaction_payment::{CurrencyAdapter, OnChargeTransaction}; +use scale_info::TypeInfo; use smallvec::smallvec; use sp_core::H256; use sp_io::TestExternalities; -use sp_runtime::{testing::Header, traits::{BlakeTwo256, DispatchInfoOf, IdentityLookup, One, PostDispatchInfoOf}, transaction_validity::TransactionValidityError, FixedI64, Perbill, RuntimeDebug}; -use sp_runtime::traits::{ConstU32, ConstU64}; +use sp_runtime::{ + traits::{ + BlakeTwo256, ConstU32, ConstU64, DispatchInfoOf, IdentityLookup, One, PostDispatchInfoOf, + }, + transaction_validity::TransactionValidityError, + BuildStorage, FixedI64, Perbill, RuntimeDebug, +}; use sp_std::{ cell::RefCell, convert::{TryFrom, TryInto}, marker::PhantomData, }; -pub(crate) use crate as pallet_energy; use crate::{EnergyBalance, TotalEnergy}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; pub(super) type AccountId = u64; pub(super) type Balance = u64; -type BlockNumber = u64; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Balances: pallet_balances, TransactionPayment: pallet_transaction_payment, - Energy: pallet_energy, + Energy: crate, Proxy: pallet_proxy, } ); @@ -58,10 +54,10 @@ parameter_types! { pub const BlockHashCount: u64 = 250; pub const SS58Prefix: u8 = 42; pub MockBlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max( - frame_support::weights::Weight::from_parts(1_000_000, 0) + frame_system::limits::BlockWeights::simple_max( + frame_support::weights::Weight::from_parts(1_000_000, 0) .set_proof_size(u64::MAX) - ); + ); } impl frame_system::Config for Test { @@ -70,13 +66,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -105,9 +100,25 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); -} - -#[derive(Encode, Decode, Clone, Eq, PartialEq, Ord, PartialOrd, TypeInfo, MaxEncodedLen, RuntimeDebug, Default)] + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxHolds = (); + type MaxFreezes = (); +} + +#[derive( + Encode, + Decode, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + TypeInfo, + MaxEncodedLen, + RuntimeDebug, + Default, +)] pub enum MockProxyType { #[default] Any, @@ -243,7 +254,7 @@ where } } -impl pallet_energy::Config for Test { +impl crate::Config for Test { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type Currency = Balances; @@ -427,9 +438,8 @@ impl ExtBuilder { clear_withdraw_fee_args(); clear_corrected_and_deposit_fee_args(); - let storage = &mut frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut ext: TestExternalities = frame_system::GenesisConfig::::default().build_storage().unwrap().into(); - let mut ext = TestExternalities::from(storage.clone()); ext.execute_with(|| { System::set_block_number(1); }); diff --git a/pallets/energy/src/tests.rs b/pallets/energy/src/tests.rs index 0c7770f9..c73dcdfe 100644 --- a/pallets/energy/src/tests.rs +++ b/pallets/energy/src/tests.rs @@ -16,7 +16,7 @@ use sp_runtime::{ DispatchError, FixedI64, FixedPointNumber, }; -use pallet_energy::{Call as EnergyCall, EnergyBalance, Event as EnergyEvent}; +use crate::{Call as EnergyCall, EnergyBalance, Event as EnergyEvent}; use crate::{mock::*, Error, WeightInfo}; @@ -111,7 +111,7 @@ fn update_value_coefficient_should_have_correct_weight() { assert_eq!( extract_actual_weight(&result, &info), - ::WeightInfo::update_value_coefficient(), + ::WeightInfo::update_value_coefficient(), ); }); } @@ -238,7 +238,7 @@ fn generate_energy_should_have_correct_weight() { assert_eq!( extract_actual_weight(&result, &info), - ::WeightInfo::generate_energy(), + ::WeightInfo::generate_energy(), ); }); } @@ -564,7 +564,7 @@ fn update_value_coefficient_should_reflect_on_future_charge_transactions() { }; assert_eq!( - ::DefaultValueCoefficient::get().to_float(), + ::DefaultValueCoefficient::get().to_float(), 1.25, "Default value coefficient should be 1.25", ); @@ -718,22 +718,22 @@ fn existential_deposit_and_providers() { #[test] fn native_token_to_energy() { ExtBuilder::default().value_coefficient(1.25).build().execute_with(|| { - assert_eq!(pallet_energy::Pallet::::native_token_to_energy(100), 80); + assert_eq!(crate::Pallet::::native_token_to_energy(100), 80); }); ExtBuilder::default().value_coefficient(1.5).build().execute_with(|| { - assert_eq!(pallet_energy::Pallet::::native_token_to_energy(200), 133); + assert_eq!(crate::Pallet::::native_token_to_energy(200), 133); }); ExtBuilder::default().value_coefficient(10.0).build().execute_with(|| { - assert_eq!(pallet_energy::Pallet::::native_token_to_energy(500), 50); + assert_eq!(crate::Pallet::::native_token_to_energy(500), 50); }); ExtBuilder::default().value_coefficient(0.5).build().execute_with(|| { - assert_eq!(pallet_energy::Pallet::::native_token_to_energy(33), 66); + assert_eq!(crate::Pallet::::native_token_to_energy(33), 66); }); ExtBuilder::default().value_coefficient(0.1).build().execute_with(|| { - assert_eq!(pallet_energy::Pallet::::native_token_to_energy(33), 330); + assert_eq!(crate::Pallet::::native_token_to_energy(33), 330); }); } diff --git a/pallets/evm-addresses/src/evm.rs b/pallets/evm-addresses/src/evm.rs index 9bcdcc33..aca298a2 100644 --- a/pallets/evm-addresses/src/evm.rs +++ b/pallets/evm-addresses/src/evm.rs @@ -25,7 +25,7 @@ impl Pallet { pub(crate) fn verify_evm_signature( sig: &EcdsaSignature, sub_address: &T::AccountId, - sub_nonce: T::Index, + sub_nonce: T::Nonce, ) -> Option { let msg = keccak_256(&Self::eth_signable_message(sub_address, sub_nonce)); @@ -37,7 +37,7 @@ impl Pallet { /// Constructs the message that Ethereum RPC's `personal_sign` and `eth_sign` would sign. /// In accordance with https://eips.ethereum.org/EIPS/eip-191 - pub(super) fn eth_signable_message(sub_address: &T::AccountId, sub_nonce: T::Index) -> Vec { + pub(super) fn eth_signable_message(sub_address: &T::AccountId, sub_nonce: T::Nonce) -> Vec { let addr = hex::encode(sub_address.encode()); let nonce = format!("{:?}", sub_nonce); diff --git a/pallets/evm-addresses/src/mock.rs b/pallets/evm-addresses/src/mock.rs index 3e24a195..7a0f7c5e 100644 --- a/pallets/evm-addresses/src/mock.rs +++ b/pallets/evm-addresses/src/mock.rs @@ -15,12 +15,7 @@ use frame_support::{ use smallvec::smallvec; use sp_core::H256; use sp_io::TestExternalities; -use sp_runtime::{ - generic, - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, - Perbill, -}; +use sp_runtime::{generic, traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill}; use sp_std::convert::{TryFrom, TryInto}; pub(crate) use crate as pallet_evm_accounts; @@ -32,18 +27,13 @@ type SignedExtra = ( type Signature = (); type UncheckedExtrinsic = generic::UncheckedExtrinsic; -type Block = generic::Block, UncheckedExtrinsic>; +type Block = generic::Block, UncheckedExtrinsic>; pub(super) type AccountId = u64; pub(super) type Balance = u64; -type BlockNumber = u64; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Balances: pallet_balances, TransactionPayment: pallet_transaction_payment, @@ -62,13 +52,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -112,6 +101,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxFreezes = (); + type MaxHolds = (); } parameter_types! { @@ -146,9 +139,7 @@ pub struct ExtBuilder; impl ExtBuilder { pub(crate) fn build(self) -> TestExternalities { - let storage = &mut frame_system::GenesisConfig::default().build_storage::().unwrap(); - - let mut ext = TestExternalities::from(storage.clone()); + let mut ext: TestExternalities = frame_system::GenesisConfig::::default().build_storage().unwrap().into(); ext.execute_with(|| { System::set_block_number(1); }); diff --git a/pallets/free-proxy/src/lib.rs b/pallets/free-proxy/src/lib.rs index 728d9a02..c65ee5af 100644 --- a/pallets/free-proxy/src/lib.rs +++ b/pallets/free-proxy/src/lib.rs @@ -66,7 +66,7 @@ pub mod pallet { origin: OriginFor, delegate: AccountIdLookupOf, proxy_type: T::ProxyType, - delay: T::BlockNumber, + delay: BlockNumberFor, ) -> DispatchResult { let who = ensure_signed(origin)?; diff --git a/pallets/free-proxy/src/mock.rs b/pallets/free-proxy/src/mock.rs index 314a86c1..45aa1ae5 100644 --- a/pallets/free-proxy/src/mock.rs +++ b/pallets/free-proxy/src/mock.rs @@ -8,30 +8,22 @@ use frame_support::{parameter_types, traits::Everything}; use sp_core::H256; use sp_io::TestExternalities; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use sp_std::convert::{TryFrom, TryInto}; -pub(crate) use crate as pallet_free_proxy; - -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; pub(super) type AccountId = u64; pub(super) type Balance = u64; -type BlockNumber = u64; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Balances: pallet_balances, Proxy: pallet_proxy, - FreeProxy: pallet_free_proxy, + FreeProxy: crate, } ); @@ -46,13 +38,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -81,6 +72,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type FreezeIdentifier = (); + type MaxFreezes = (); + type MaxHolds = (); + type RuntimeHoldReason = (); } parameter_types! { @@ -92,7 +87,7 @@ parameter_types! { pub const MaxPending: u16 = 32; } -impl pallet_free_proxy::Config for Test { +impl crate::Config for Test { type ProxyDepositBase = ProxyDepositBase; type ProxyDepositFactor = ProxyDepositFactor; type WeightInfo = (); @@ -103,8 +98,8 @@ impl pallet_proxy::Config for Test { type RuntimeCall = RuntimeCall; type Currency = Balances; type ProxyType = (); - type ProxyDepositBase = pallet_free_proxy::AdjustedProxyDepositBase; - type ProxyDepositFactor = pallet_free_proxy::AdjustedProxyDepositFactor; + type ProxyDepositBase = crate::AdjustedProxyDepositBase; + type ProxyDepositFactor = crate::AdjustedProxyDepositFactor; type MaxProxies = MaxProxies; type WeightInfo = (); type MaxPending = MaxPending; @@ -143,9 +138,9 @@ impl ExtBuilder { pub(crate) fn build(self) -> TestExternalities { self.set_configs(); - let storage = &mut frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut ext: TestExternalities = + frame_system::GenesisConfig::::default().build_storage().unwrap().into(); - let mut ext = TestExternalities::from(storage.clone()); ext.execute_with(|| { System::set_block_number(1); }); diff --git a/pallets/ownership/src/migration.rs b/pallets/ownership/src/migration.rs index a96551c3..a3d49619 100644 --- a/pallets/ownership/src/migration.rs +++ b/pallets/ownership/src/migration.rs @@ -84,7 +84,7 @@ pub mod v1 { } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, &'static str> { + fn pre_upgrade() -> Result, DispatchError> { let old_pallet_name = N::get().as_bytes(); let old_pallet_prefix = twox_128(old_pallet_name); @@ -97,7 +97,7 @@ pub mod v1 { } #[cfg(feature = "try-runtime")] - fn post_upgrade(_: Vec) -> Result<(), &'static str> { + fn post_upgrade(_: Vec) -> Result<(), DispatchError> { let old_pallet_name = N::get(); let new_pallet_name =

::name(); diff --git a/pallets/ownership/tests/src/mock.rs b/pallets/ownership/tests/src/mock.rs index 8d051380..f98ac19e 100644 --- a/pallets/ownership/tests/src/mock.rs +++ b/pallets/ownership/tests/src/mock.rs @@ -9,7 +9,6 @@ use lazy_static::lazy_static; use mockall::mock; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; use sp_std::{ @@ -19,15 +18,10 @@ use sp_std::{ use subsocial_support::{traits::CreatorStakingProvider, SpaceId}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Timestamp: pallet_timestamp, Balances: pallet_balances, @@ -82,13 +76,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -128,6 +121,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type MaxHolds = (); + type MaxFreezes = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); } impl pallet_permissions::Config for Test { diff --git a/pallets/ownership/tests/src/tests_utils.rs b/pallets/ownership/tests/src/tests_utils.rs index 0092fd8a..0cc1e292 100644 --- a/pallets/ownership/tests/src/tests_utils.rs +++ b/pallets/ownership/tests/src/tests_utils.rs @@ -7,6 +7,7 @@ use frame_support::{assert_ok, pallet_prelude::*}; use sp_core::storage::Storage; use sp_io::TestExternalities; +use sp_runtime::BuildStorage; use pallet_ownership::{OwnableEntity, Event as OwnershipEvent}; use pallet_posts::PostExtension; @@ -35,11 +36,11 @@ impl ExtBuilder { /// Default ext configuration with BlockNumber 1 pub fn build() -> TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); Self::configure_storages(&mut storage); - let mut ext = TestExternalities::from(storage); + let mut ext: TestExternalities = storage.into(); ext.execute_with(|| { let _m = use_static_mock(); System::set_block_number(1); diff --git a/pallets/posts/tests/src/mock.rs b/pallets/posts/tests/src/mock.rs index dfb715c3..747d1900 100644 --- a/pallets/posts/tests/src/mock.rs +++ b/pallets/posts/tests/src/mock.rs @@ -7,21 +7,16 @@ use frame_support::{pallet_prelude::ConstU32, parameter_types, traits::Everything}; use frame_support::dispatch::DispatchResult; use sp_core::H256; -use sp_runtime::{DispatchError, testing::Header, traits::{BlakeTwo256, IdentityLookup}}; +use sp_runtime::{DispatchError, traits::{BlakeTwo256, IdentityLookup}}; use sp_std::convert::{TryFrom, TryInto}; use subsocial_support::traits::DomainsProvider; use crate::tests_utils::*; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Timestamp: pallet_timestamp, Balances: pallet_balances, @@ -37,7 +32,6 @@ frame_support::construct_runtime!( pub(super) type AccountId = u64; pub(super) type Balance = u64; -pub(super) type BlockNumber = u64; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -50,13 +44,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -96,6 +89,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type MaxHolds = (); + type MaxFreezes = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); } parameter_types! { diff --git a/pallets/posts/tests/src/tests_utils.rs b/pallets/posts/tests/src/tests_utils.rs index 326ddc45..04a7193f 100644 --- a/pallets/posts/tests/src/tests_utils.rs +++ b/pallets/posts/tests/src/tests_utils.rs @@ -11,9 +11,11 @@ use std::{ }; use frame_support::{assert_ok, pallet_prelude::*}; +use frame_system::pallet_prelude::BlockNumberFor; +use pallet_ownership::OwnableEntity; use sp_core::storage::Storage; use sp_io::TestExternalities; -use pallet_ownership::OwnableEntity; +use sp_runtime::BuildStorage; use pallet_permissions::{SpacePermission as SP, SpacePermission, SpacePermissions}; use pallet_posts::{Comment, PostExtension, PostUpdate}; @@ -45,11 +47,11 @@ impl ExtBuilder { /// Default ext configuration with BlockNumber 1 pub fn build() -> TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); Self::configure_storages(&mut storage); - let mut ext = TestExternalities::from(storage); + let mut ext: TestExternalities = storage.into(); ext.execute_with(|| System::set_block_number(1)); ext @@ -432,7 +434,7 @@ pub fn _create_default_role() -> DispatchResult { pub fn _create_role( origin: Option, space_id: Option, - time_to_live: Option>, + time_to_live: Option>>, content: Option, permissions: Option>, ) -> DispatchResult { diff --git a/pallets/profiles/src/mock.rs b/pallets/profiles/src/mock.rs index 9ff9b664..a8d28bf9 100644 --- a/pallets/profiles/src/mock.rs +++ b/pallets/profiles/src/mock.rs @@ -13,9 +13,8 @@ use pallet_permissions::{default_permissions::DefaultSpacePermissions, SpacePerm use sp_core::H256; use sp_io::TestExternalities; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, - DispatchError, + BuildStorage, DispatchError, }; use sp_std::sync::{Mutex, MutexGuard}; use subsocial_support::{ @@ -23,16 +22,11 @@ use subsocial_support::{ Content, SpaceId, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Permissions: pallet_permissions, Profiles: pallet_profiles, @@ -53,13 +47,12 @@ impl system::Config for Test { type DbWeight = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type Version = (); @@ -88,7 +81,7 @@ mock! { impl SpacesProvider for Spaces { fn get_space_owner(_space_id: SpaceId) -> Result; - + fn do_update_space_owner(_space_id: SpaceId, _new_owner: AccountId) -> DispatchResult; fn create_space(_owner: &AccountId, _content: Content) -> Result; @@ -118,9 +111,8 @@ pub(super) struct ExtBuilder; impl ExtBuilder { /// Default ext configuration with BlockNumber 1 pub fn build() -> TestExternalities { - let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); - - let mut ext = TestExternalities::from(storage); + let mut ext: TestExternalities = + frame_system::GenesisConfig::::default().build_storage().unwrap().into(); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/pallets/reactions/tests/src/mock.rs b/pallets/reactions/tests/src/mock.rs index e5e5a976..b0e8a3f6 100644 --- a/pallets/reactions/tests/src/mock.rs +++ b/pallets/reactions/tests/src/mock.rs @@ -7,20 +7,14 @@ use frame_support::{pallet_prelude::ConstU32, parameter_types, traits::Everything}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; use sp_std::convert::{TryFrom, TryInto}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Timestamp: pallet_timestamp, Balances: pallet_balances, @@ -35,7 +29,6 @@ frame_support::construct_runtime!( pub(super) type AccountId = u64; pub(super) type Balance = u64; -pub(super) type BlockNumber = u64; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -48,13 +41,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -94,6 +86,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxFreezes = (); + type MaxHolds = (); } parameter_types! { diff --git a/pallets/reactions/tests/src/tests_utils.rs b/pallets/reactions/tests/src/tests_utils.rs index b4976beb..d143d3dd 100644 --- a/pallets/reactions/tests/src/tests_utils.rs +++ b/pallets/reactions/tests/src/tests_utils.rs @@ -7,7 +7,7 @@ use frame_support::{assert_ok, pallet_prelude::*}; use sp_core::storage::Storage; use sp_io::TestExternalities; - +use sp_runtime::BuildStorage; use pallet_permissions::SpacePermissions; use pallet_posts::{PostExtension, PostUpdate}; use pallet_reactions::{ReactionId, ReactionKind}; @@ -35,11 +35,11 @@ impl ExtBuilder { /// Default ext configuration with BlockNumber 1 pub fn build() -> TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); Self::configure_storages(&mut storage); - let mut ext = TestExternalities::from(storage); + let mut ext: TestExternalities = storage.into(); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/pallets/resource-discussions/src/mock.rs b/pallets/resource-discussions/src/mock.rs index 8bea5d88..0815abed 100644 --- a/pallets/resource-discussions/src/mock.rs +++ b/pallets/resource-discussions/src/mock.rs @@ -7,11 +7,7 @@ use frame_support::{dispatch::DispatchResult, parameter_types, traits::Everything}; use sp_core::H256; use sp_io::TestExternalities; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, - DispatchError, -}; +use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, BuildStorage, DispatchError}; use sp_std::convert::{TryFrom, TryInto}; use pallet_permissions::{ @@ -22,19 +18,13 @@ use subsocial_support::{traits::SpaceFollowsProvider, SpaceId, User}; pub(crate) use crate as pallet_resource_discussions; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; pub(super) type AccountId = u64; pub(super) type Balance = u64; -type BlockNumber = u64; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Balances: pallet_balances, Timestamp: pallet_timestamp, @@ -57,13 +47,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -103,6 +92,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type MaxHolds = (); + type MaxFreezes = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); } impl pallet_permissions::Config for Test { @@ -198,9 +191,7 @@ impl ExtBuilder { pub(crate) fn build(self) -> TestExternalities { self.set_configs(); - let storage = &mut frame_system::GenesisConfig::default().build_storage::().unwrap(); - - let mut ext = TestExternalities::from(storage.clone()); + let mut ext: TestExternalities = frame_system::GenesisConfig::::default().build_storage().unwrap().into(); ext.execute_with(|| { System::set_block_number(1); }); diff --git a/pallets/roles/src/benchmarking.rs b/pallets/roles/src/benchmarking.rs index 739da384..3546ddd6 100644 --- a/pallets/roles/src/benchmarking.rs +++ b/pallets/roles/src/benchmarking.rs @@ -13,6 +13,7 @@ use super::*; use frame_benchmarking::{account, benchmarks}; use frame_support::dispatch::DispatchError; +use frame_system::pallet_prelude::BlockNumberFor; use frame_system::RawOrigin; use pallet_permissions::SpacePermission as SP; use pallet_spaces::types::Space; @@ -76,7 +77,7 @@ benchmarks! { create_role { let caller_origin = RawOrigin::Signed(account::("Acc1", 1, 0)); let space = create_dummy_space::(caller_origin.clone())?; - let time_to_live: Option = Some(100u32.into()); + let time_to_live: Option> = Some(100u32.into()); let content = valid_content_ipfs(); let perms = vec![SP::ManageRoles]; let role_id = NextRoleId::::get(); diff --git a/pallets/roles/src/functions.rs b/pallets/roles/src/functions.rs index d6485793..654c9b1f 100644 --- a/pallets/roles/src/functions.rs +++ b/pallets/roles/src/functions.rs @@ -7,6 +7,7 @@ use super::*; use frame_support::dispatch::DispatchError; +use frame_system::pallet_prelude::BlockNumberFor; use pallet_permissions::SpacePermissionsContext; impl Pallet { @@ -121,13 +122,13 @@ impl Role { pub fn new( created_by: T::AccountId, space_id: SpaceId, - time_to_live: Option, + time_to_live: Option>, content: Content, permissions: BTreeSet, ) -> Result { let role_id = Pallet::::next_role_id(); - let mut expires_at: Option = None; + let mut expires_at: Option> = None; if let Some(ttl) = time_to_live { expires_at = Some(ttl + >::block_number()); } diff --git a/pallets/roles/src/lib.rs b/pallets/roles/src/lib.rs index ee6f39a2..5f67a015 100644 --- a/pallets/roles/src/lib.rs +++ b/pallets/roles/src/lib.rs @@ -190,7 +190,7 @@ pub mod pallet { pub fn create_role( origin: OriginFor, space_id: SpaceId, - time_to_live: Option, + time_to_live: Option>, content: Content, permissions: Vec, ) -> DispatchResult { diff --git a/pallets/roles/src/mock.rs b/pallets/roles/src/mock.rs index bf362ba7..72ea80fb 100644 --- a/pallets/roles/src/mock.rs +++ b/pallets/roles/src/mock.rs @@ -16,9 +16,10 @@ use frame_support::{ parameter_types, traits::{ConstU32, Everything}, }; +use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; use pallet_permissions::{SpacePermission, SpacePermission as SP, SpacePermissions}; @@ -27,28 +28,20 @@ use subsocial_support::{ Content, SpaceId, SpacePermissionsInfo, User, }; -use crate as roles; - -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: system::{Pallet, Call, Config, Storage, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, - Roles: roles::{Pallet, Call, Storage, Event}, - Spaces: pallet_spaces::{Pallet, Call, Storage, Event}, + pub enum Test { + System: frame_system, + Balances: pallet_balances, + Timestamp: pallet_timestamp, + Roles: crate, + Spaces: pallet_spaces, } ); pub(super) type AccountId = u64; pub(super) type Balance = u64; -type BlockNumber = u64; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -61,13 +54,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -107,6 +99,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxFreezes = (); + type MaxHolds = (); } use pallet_permissions::default_permissions::DefaultSpacePermissions; @@ -180,18 +176,16 @@ pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> TestExternalities { - let storage = system::GenesisConfig::default().build_storage::().unwrap(); - - let mut ext = TestExternalities::from(storage); + let mut ext: TestExternalities = + system::GenesisConfig::::default().build_storage().unwrap().into(); ext.execute_with(|| System::set_block_number(1)); ext } pub fn build_with_a_few_roles_granted_to_account2() -> TestExternalities { - let storage = system::GenesisConfig::default().build_storage::().unwrap(); - - let mut ext = TestExternalities::from(storage); + let mut ext: TestExternalities = + system::GenesisConfig::::default().build_storage().unwrap().into(); ext.execute_with(|| { System::set_block_number(1); let user = User::Account(ACCOUNT2); @@ -270,7 +264,7 @@ pub(crate) fn _create_default_role() -> DispatchResult { pub(crate) fn _create_role( origin: Option, space_id: Option, - time_to_live: Option>, + time_to_live: Option>>, content: Option, permissions: Option>, ) -> DispatchResult { @@ -341,7 +335,10 @@ pub(crate) fn _delete_default_role() -> DispatchResult { _delete_role(None, None) } -pub(crate) fn _delete_role(origin: Option, role_id: Option) -> DispatchResult { +pub(crate) fn _delete_role( + origin: Option, + role_id: Option, +) -> DispatchResult { let role_id = role_id.unwrap_or(ROLE1); Roles::delete_role( origin.unwrap_or_else(|| RuntimeOrigin::signed(ACCOUNT1)), diff --git a/pallets/roles/src/types.rs b/pallets/roles/src/types.rs index 581b2359..b483308d 100644 --- a/pallets/roles/src/types.rs +++ b/pallets/roles/src/types.rs @@ -4,6 +4,7 @@ // Full notice is available at https://github.com/dappforce/subsocial-parachain/blob/main/COPYRIGHT // Full license is available at https://github.com/dappforce/subsocial-parachain/blob/main/LICENSE +use frame_system::pallet_prelude::BlockNumberFor; use super::*; pub type RoleId = u64; @@ -30,7 +31,7 @@ pub struct Role { /// An optional block number at which this role will expire. If `expires_at` is `Some` /// and the current block is greater or equal to its value, the permissions associated /// with a given role will have no affect. - pub expires_at: Option, + pub expires_at: Option>, /// Content can optionally contain additional information associated with a role, /// such as a name, description, and image for a role. This may be useful for end users. diff --git a/pallets/space-follows/tests/src/mock.rs b/pallets/space-follows/tests/src/mock.rs index 9b569088..6827ca77 100644 --- a/pallets/space-follows/tests/src/mock.rs +++ b/pallets/space-follows/tests/src/mock.rs @@ -7,20 +7,14 @@ use frame_support::{pallet_prelude::ConstU32, parameter_types, traits::Everything}; use sp_core::H256; use sp_runtime::{ - testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; use sp_std::convert::{TryFrom, TryInto}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Timestamp: pallet_timestamp, Balances: pallet_balances, @@ -33,7 +27,6 @@ frame_support::construct_runtime!( pub(super) type AccountId = u64; pub(super) type Balance = u64; -pub(super) type BlockNumber = u64; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -46,13 +39,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -92,6 +84,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type MaxHolds = (); + type MaxFreezes = (); + type FreezeIdentifier = (); + type RuntimeHoldReason = (); } impl pallet_permissions::Config for Test { diff --git a/pallets/space-follows/tests/src/tests_utils.rs b/pallets/space-follows/tests/src/tests_utils.rs index f17909e6..40b802fa 100644 --- a/pallets/space-follows/tests/src/tests_utils.rs +++ b/pallets/space-follows/tests/src/tests_utils.rs @@ -9,6 +9,7 @@ use pallet_permissions::SpacePermissions; use pallet_spaces::{types::SpaceUpdate, SpaceById}; use sp_core::storage::Storage; use sp_io::TestExternalities; +use sp_runtime::BuildStorage; use subsocial_support::{Content, SpaceId}; use crate::mock::*; @@ -32,11 +33,11 @@ impl ExtBuilder { /// Default ext configuration with BlockNumber 1 pub fn build() -> TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); Self::configure_storages(&mut storage); - let mut ext = TestExternalities::from(storage); + let mut ext: TestExternalities = storage.into(); ext.execute_with(|| System::set_block_number(1)); ext @@ -102,7 +103,6 @@ pub(crate) fn _create_space( ) } - pub(crate) fn _update_space( origin: Option, space_id: Option, @@ -121,7 +121,10 @@ pub(crate) fn _default_follow_space() -> DispatchResult { _follow_space(None, None) } -pub(crate) fn _follow_space(origin: Option, space_id: Option) -> DispatchResult { +pub(crate) fn _follow_space( + origin: Option, + space_id: Option, +) -> DispatchResult { SpaceFollows::follow_space( origin.unwrap_or_else(|| RuntimeOrigin::signed(ACCOUNT2)), space_id.unwrap_or(SPACE1), @@ -132,7 +135,10 @@ pub(crate) fn _default_unfollow_space() -> DispatchResult { _unfollow_space(None, None) } -pub(crate) fn _unfollow_space(origin: Option, space_id: Option) -> DispatchResult { +pub(crate) fn _unfollow_space( + origin: Option, + space_id: Option, +) -> DispatchResult { SpaceFollows::unfollow_space( origin.unwrap_or_else(|| RuntimeOrigin::signed(ACCOUNT2)), space_id.unwrap_or(SPACE1), diff --git a/pallets/spaces/src/lib.rs b/pallets/spaces/src/lib.rs index 793f5e2d..a7ba1b96 100644 --- a/pallets/spaces/src/lib.rs +++ b/pallets/spaces/src/lib.rs @@ -132,20 +132,21 @@ pub mod pallet { pub type SpaceIdsByOwner = StorageMap<_, Twox64Concat, T::AccountId, SpacesByAccount, ValueQuery>; + #[derive(scale_info::TypeInfo, Debug)] #[pallet::genesis_config] pub struct GenesisConfig { pub endowed_account: Option, } - #[cfg(feature = "std")] impl Default for GenesisConfig { + #[inline] fn default() -> Self { Self { endowed_account: None } } } #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { + impl BuildGenesisConfig for GenesisConfig { fn build(&self) { Pallet::::init_pallet(self.endowed_account.as_ref()); } diff --git a/pallets/spaces/tests/src/mock.rs b/pallets/spaces/tests/src/mock.rs index b441b844..51272961 100644 --- a/pallets/spaces/tests/src/mock.rs +++ b/pallets/spaces/tests/src/mock.rs @@ -6,23 +6,15 @@ use frame_support::{pallet_prelude::ConstU32, parameter_types, traits::Everything}; use sp_core::H256; -use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, -}; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; use sp_std::convert::{TryFrom, TryInto}; use crate::tests_utils::*; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Test { System: frame_system, Timestamp: pallet_timestamp, Balances: pallet_balances, @@ -50,13 +42,12 @@ impl frame_system::Config for Test { type BlockLength = (); type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = BlockNumber; + type Nonce = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup; - type Header = Header; + type Block = Block; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = (); @@ -96,6 +87,10 @@ impl pallet_balances::Config for Test { type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxFreezes = (); + type MaxHolds = (); } parameter_types! { diff --git a/pallets/spaces/tests/src/tests_utils.rs b/pallets/spaces/tests/src/tests_utils.rs index 5d2af08f..03531831 100644 --- a/pallets/spaces/tests/src/tests_utils.rs +++ b/pallets/spaces/tests/src/tests_utils.rs @@ -13,7 +13,7 @@ use std::{ use frame_support::{assert_ok, pallet_prelude::*}; use sp_core::storage::Storage; use sp_io::TestExternalities; - +use sp_runtime::BuildStorage; use pallet_permissions::{ default_permissions::DefaultSpacePermissions, SpacePermission as SP, SpacePermission, SpacePermissions, @@ -47,11 +47,11 @@ impl ExtBuilder { /// Default ext configuration with BlockNumber 1 pub fn build() -> TestExternalities { - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); Self::configure_storages(&mut storage); - let mut ext = TestExternalities::from(storage); + let mut ext: TestExternalities = storage.into(); ext.execute_with(|| System::set_block_number(1)); ext diff --git a/pallets/support/src/lib.rs b/pallets/support/src/lib.rs index 7a491c89..2e8c7818 100644 --- a/pallets/support/src/lib.rs +++ b/pallets/support/src/lib.rs @@ -14,6 +14,7 @@ use scale_info::TypeInfo; use serde::{Serialize, Deserialize}; use frame_support::pallet_prelude::*; +use frame_system::pallet_prelude::BlockNumberFor; use sp_std::{collections::btree_set::BTreeSet, vec, vec::Vec}; pub mod traits; @@ -30,13 +31,13 @@ pub struct WhoAndWhen { pub type WhoAndWhenOf = WhoAndWhen< ::AccountId, - ::BlockNumber, + BlockNumberFor, ::Moment, >; pub fn new_who_and_when( account: T::AccountId, -) -> WhoAndWhen +) -> WhoAndWhen, T::Moment> where T: frame_system::Config + pallet_timestamp::Config, { diff --git a/runtime/build.rs b/runtime/build.rs index 60302754..d5f5f014 100644 --- a/runtime/build.rs +++ b/runtime/build.rs @@ -4,12 +4,16 @@ // Full notice is available at https://github.com/dappforce/subsocial-parachain/blob/main/COPYRIGHT // Full license is available at https://github.com/dappforce/subsocial-parachain/blob/main/LICENSE -use substrate_wasm_builder::WasmBuilder; - +#[cfg(feature = "std")] fn main() { - WasmBuilder::new() + substrate_wasm_builder::WasmBuilder::new() .with_current_project() .export_heap_base() .import_memory() .build() } + +/// The wasm builder is deactivated when compiling +/// this crate for wasm to speed up the compilation. +#[cfg(not(feature = "std"))] +fn main() {} diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 2ab91fc2..d6aaa5e6 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -29,7 +29,7 @@ use sp_version::RuntimeVersion; use frame_support::{ construct_runtime, parameter_types, dispatch::DispatchClass, - traits::{ConstU32, ConstU64, ConstU8, Contains, Currency, OnUnbalanced, WithdrawReasons}, + traits::{ConstBool, ConstU32, ConstU64, ConstU8, Contains, Currency, OnUnbalanced, WithdrawReasons}, weights::{ constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, @@ -73,7 +73,7 @@ pub type AccountId = <::Signer as IdentifyAccount>::Account pub type Balance = u128; /// Index of a transaction in the chain. -pub type Index = u32; +pub type Nonce = u32; /// A hash of some data used by the chain. pub type Hash = sp_core::H256; @@ -121,6 +121,7 @@ pub type Executive = frame_executive::Executive< frame_system::ChainContext, Runtime, AllPalletsWithSystem, + // FIXME: remove if unnecessary pallet_ownership::migration::v1::MigrateToV1< Runtime, Ownership, @@ -242,7 +243,7 @@ const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); /// We allow for 0.5 of a second of compute with a 12 second average block time. const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts( WEIGHT_REF_TIME_PER_SECOND.saturating_div(2), - polkadot_primitives::v2::MAX_POV_SIZE as u64, + polkadot_primitives::MAX_POV_SIZE as u64, ); /// The version information used to identify this runtime when compiled natively. @@ -286,8 +287,11 @@ parameter_types! { pub struct BaseFilter; impl Contains for BaseFilter { fn contains(c: &RuntimeCall) -> bool { - let is_set_balance = - matches!(c, RuntimeCall::Balances(pallet_balances::Call::set_balance { .. })); + let is_set_balance = matches!( + c, + RuntimeCall::Balances(pallet_balances::Call::set_balance_deprecated { .. }) + | RuntimeCall::Balances(pallet_balances::Call::force_set_balance { .. }) + ); let is_force_transfer = matches!(c, RuntimeCall::Balances(pallet_balances::Call::force_transfer { .. })); @@ -312,15 +316,13 @@ impl frame_system::Config for Runtime { /// The lookup mechanism to get account ID from whatever is passed in dispatchers. type Lookup = AccountIdLookup; /// The index type for storing how many extrinsics an account has signed. - type Index = Index; - /// The index type for blocks. - type BlockNumber = BlockNumber; + type Nonce = Nonce; /// The type for hashing blocks and tries. type Hash = Hash; /// The hashing algorithm used. type Hashing = BlakeTwo256; - /// The header type. - type Header = generic::Header; + /// The block type. + type Block = Block; /// The ubiquitous event type. type RuntimeEvent = RuntimeEvent; /// The ubiquitous origin type. @@ -383,6 +385,10 @@ impl pallet_balances::Config for Runtime { type WeightInfo = pallet_balances::weights::SubstrateWeight; type MaxReserves = ConstU32<50>; type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = RuntimeHoldReason; + type FreezeIdentifier = (); + type MaxHolds = ConstU32<0>; + type MaxFreezes = ConstU32<0>; } parameter_types! { @@ -492,14 +498,15 @@ impl pallet_aura::Config for Runtime { type AuthorityId = AuraId; type DisabledValidators = (); type MaxAuthorities = ConstU32<100_000>; + type AllowMultipleBlocksPerSlot = ConstBool; } parameter_types! { pub const PotId: PalletId = PalletId(*b"PotStake"); pub const MaxCandidates: u32 = 1000; - pub const MinCandidates: u32 = 5; + pub const MinEligibleCollators: u32 = 3; pub const SessionLength: BlockNumber = 6 * HOURS; - pub const MaxInvulnerables: u32 = 100; + pub const MaxInvulnerables: u32 = 20; pub const ExecutiveBody: BodyId = BodyId::Executive; } @@ -512,7 +519,7 @@ impl pallet_collator_selection::Config for Runtime { type UpdateOrigin = CollatorSelectionUpdateOrigin; type PotId = PotId; type MaxCandidates = MaxCandidates; - type MinCandidates = MinCandidates; + type MinEligibleCollators = MinEligibleCollators; type MaxInvulnerables = MaxInvulnerables; // should be a multiple of session or things will get inconsistent type KickThreshold = Period; @@ -525,6 +532,7 @@ impl pallet_collator_selection::Config for Runtime { impl pallet_sudo::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; + type WeightInfo = (); } parameter_types! { @@ -651,7 +659,7 @@ impl pallet_utility::Config for Runtime { } parameter_types! { -// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. + // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. pub const DepositBase: Balance = deposit(1, 88); // Additional storage item size of 32 bytes. pub const DepositFactor: Balance = deposit(0, 32); @@ -870,11 +878,7 @@ impl pallet_resource_discussions::Config for Runtime { // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { + pub enum Runtime { // System support stuff. System: frame_system = 0, ParachainSystem: cumulus_pallet_parachain_system = 1, @@ -940,12 +944,12 @@ mod benches { [pallet_proxy, Proxy] [pallet_utility, Utility] [pallet_collator_selection, CollatorSelection] + [cumulus_pallet_xcmp_queue, XcmpQueue] + [pallet_xcm, PolkadotXcm] [pallet_domains, Domains] [pallet_energy, Energy] [pallet_evm_addresses, EvmAddresses] [pallet_profiles, Profiles] - [cumulus_pallet_xcmp_queue, XcmpQueue] - [pallet_xcm, PolkadotXcm] [pallet_reactions, Reactions] [pallet_roles, Roles] [pallet_space_follows, SpaceFollows] @@ -987,6 +991,14 @@ impl_runtime_apis! { fn metadata() -> OpaqueMetadata { OpaqueMetadata::new(Runtime::metadata().into()) } + + fn metadata_at_version(version: u32) -> Option { + Runtime::metadata_at_version(version) + } + + fn metadata_versions() -> sp_std::vec::Vec { + Runtime::metadata_versions() + } } impl sp_block_builder::BlockBuilder for Runtime { @@ -1038,8 +1050,8 @@ impl_runtime_apis! { } } - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { System::account_nonce(account) } } @@ -1094,65 +1106,65 @@ impl_runtime_apis! { } } - impl pallet_creator_staking_rpc_runtime_api::CreatorStakingApi - for Runtime - { - fn estimated_backer_rewards_by_creators( - backer: AccountId, - creators: Vec, - ) -> Vec<(CreatorId, Balance)> { - CreatorStaking::estimated_backer_rewards_by_creators(backer, creators) - } - - fn withdrawable_amounts_from_inactive_creators( - backer: AccountId, - ) -> Vec<(CreatorId, Balance)> { - CreatorStaking::withdrawable_amounts_from_inactive_creators(backer) - } - - fn available_claims_by_backer( - backer: AccountId, - ) -> Vec<(CreatorId, u32)> { - CreatorStaking::available_claims_by_backer(backer) - } - - fn estimated_creator_rewards( - creator: CreatorId, - ) -> Balance { - CreatorStaking::estimated_creator_rewards(creator) - } - - fn available_claims_by_creator( - creator: CreatorId, - ) -> Vec { - CreatorStaking::available_claims_by_creator(creator) - } - } - - impl pallet_domains_rpc_runtime_api::DomainsApi for Runtime { - fn calculate_price(subdomain: Vec) -> Option { - Domains::calculate_price(&subdomain) - } - } - - impl pallet_posts_rpc_runtime_api::PostsApi for Runtime { - fn can_create_post( - account: AccountId, - space_id: SpaceId, - content_opt: Option, - ) -> DispatchResult { - Posts::can_create_regular_post(account, space_id, content_opt) - } - - fn can_create_comment( - account: AccountId, - root_post_id: PostId, - parent_id_opt: Option, - content_opt: Option - ) -> DispatchResult { - Posts::can_create_comment(account, root_post_id, parent_id_opt, content_opt) - } - } + // impl pallet_creator_staking_rpc_runtime_api::CreatorStakingApi + // for Runtime + // { + // fn estimated_backer_rewards_by_creators( + // backer: AccountId, + // creators: Vec, + // ) -> Vec<(CreatorId, Balance)> { + // CreatorStaking::estimated_backer_rewards_by_creators(backer, creators) + // } + // + // fn withdrawable_amounts_from_inactive_creators( + // backer: AccountId, + // ) -> Vec<(CreatorId, Balance)> { + // CreatorStaking::withdrawable_amounts_from_inactive_creators(backer) + // } + // + // fn available_claims_by_backer( + // backer: AccountId, + // ) -> Vec<(CreatorId, u32)> { + // CreatorStaking::available_claims_by_backer(backer) + // } + // + // fn estimated_creator_rewards( + // creator: CreatorId, + // ) -> Balance { + // CreatorStaking::estimated_creator_rewards(creator) + // } + // + // fn available_claims_by_creator( + // creator: CreatorId, + // ) -> Vec { + // CreatorStaking::available_claims_by_creator(creator) + // } + // } + // + // impl pallet_domains_rpc_runtime_api::DomainsApi for Runtime { + // fn calculate_price(subdomain: Vec) -> Option { + // Domains::calculate_price(&subdomain) + // } + // } + // + // impl pallet_posts_rpc_runtime_api::PostsApi for Runtime { + // fn can_create_post( + // account: AccountId, + // space_id: SpaceId, + // content_opt: Option, + // ) -> DispatchResult { + // Posts::can_create_regular_post(account, space_id, content_opt) + // } + // + // fn can_create_comment( + // account: AccountId, + // root_post_id: PostId, + // parent_id_opt: Option, + // content_opt: Option + // ) -> DispatchResult { + // Posts::can_create_comment(account, root_post_id, parent_id_opt, content_opt) + // } + // } #[cfg(feature = "try-runtime")] impl frame_try_runtime::TryRuntime for Runtime { @@ -1188,32 +1200,31 @@ impl_runtime_apis! { list_benchmarks!(list, extra); let storage_info = AllPalletsWithSystem::storage_info(); - return (list, storage_info) + (list, storage_info) } fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig ) -> Result, sp_runtime::RuntimeString> { - use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey}; + use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch}; use frame_system_benchmarking::Pallet as SystemBench; - impl frame_system_benchmarking::Config for Runtime {} + impl frame_system_benchmarking::Config for Runtime { + fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); + Ok(()) + } + + fn verify_set_code() { + System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); + } + } use cumulus_pallet_session_benchmarking::Pallet as SessionBench; impl cumulus_pallet_session_benchmarking::Config for Runtime {} - let whitelist: Vec = vec![ - // Block Number - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), - // Total Issuance - hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), - // Execution Phase - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), - // Event Count - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), - // System Events - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), - ]; + use frame_support::traits::WhitelistedStorageKeys; + let whitelist = AllPalletsWithSystem::whitelisted_storage_keys(); let mut batches = Vec::::new(); let params = (&config, &whitelist); diff --git a/runtime/src/weights/mod.rs b/runtime/src/weights/mod.rs index c367d4ed..0c78061f 100644 --- a/runtime/src/weights/mod.rs +++ b/runtime/src/weights/mod.rs @@ -21,7 +21,7 @@ pub mod block_weights; pub mod extrinsic_weights; pub mod paritydb_weights; pub mod rocksdb_weights; -pub mod pallet_xcm; +// pub mod pallet_xcm; pub use block_weights::constants::BlockExecutionWeight; pub use extrinsic_weights::constants::ExtrinsicBaseWeight; diff --git a/runtime/src/xcm_config.rs b/runtime/src/xcm_config.rs index c46f7ed1..cb7fa57a 100644 --- a/runtime/src/xcm_config.rs +++ b/runtime/src/xcm_config.rs @@ -11,17 +11,21 @@ use super::{ use frame_support::{ parameter_types, traits::{ConstU32, Everything, Nothing}, + weights::Weight, }; +use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use polkadot_runtime_common::impls::ToAuthor; -use xcm::{prelude::*, v3::Weight as XCMWeight}; +use xcm::latest::prelude::*; use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, - CurrencyAdapter, EnsureXcmOrigin, FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - UsingComponents, + AccountId32Aliases, AllowTopLevelPaidExecutionFrom, + CurrencyAdapter, EnsureXcmOrigin, + FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset, RelayChainAsNative, + SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, + UsingComponents, WithUniqueTopic, AllowKnownQueryResponses, + AllowSubscriptionsFrom, }; use xcm_executor::XcmExecutor; @@ -82,12 +86,12 @@ pub type XcmOriginToTransactDispatchOrigin = ( parameter_types! { // TODO: change when possible // One XCM operation is 200_000_000 weight - almost certainly a conservative estimate. - pub UnitWeightCost: XCMWeight = XCMWeight::from_parts(200_000_000u64, 0); + pub UnitWeightCost: Weight = Weight::from_parts(200_000_000u64, 0); pub const MaxInstructions: u32 = 100; } /// Additional filters that specify whether the XCM instruction should be executed at all. -pub type Barrier = ( +pub type Barrier = TrailingSetTopicAsId<( // Execution barrier that just takes max_weight from weight_credit TakeWeightCredit, // Ensures that execution time is bought with BuyExecution instruction @@ -96,7 +100,7 @@ pub type Barrier = ( AllowKnownQueryResponses, // Subscriptions for version tracking are OK. AllowSubscriptionsFrom, -); +)>; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { @@ -126,6 +130,7 @@ impl xcm_executor::Config for XcmConfig { type UniversalAliases = Nothing; type CallDispatcher = RuntimeCall; type SafeCallFilter = Nothing; + type Aliasers = Nothing; } /// No local origins on this chain are allowed to dispatch XCM sends/executions. @@ -133,12 +138,12 @@ pub type LocalOriginToLocation = SignedToAccountId32, // ..and XCMP to communicate with the sibling chains. XcmpQueue, -); +)>; #[cfg(feature = "runtime-benchmarks")] parameter_types! { @@ -170,9 +175,12 @@ impl pallet_xcm::Config for Runtime { type TrustedLockers = (); type SovereignAccountOf = (); type MaxLockers = ConstU32<8>; - type WeightInfo = crate::weights::pallet_xcm::SubstrateWeight; + type WeightInfo = pallet_xcm::TestWeightInfo/*crate::weights::pallet_xcm::SubstrateWeight*/; #[cfg(feature = "runtime-benchmarks")] type ReachableDest = ReachableDest; + type AdminOrigin = EnsureRoot; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); } impl cumulus_pallet_xcm::Config for Runtime {