difftreelog
Merge pull request #943 from UniqueNetwork/fix/clippy-warnings
in: master
36 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -110,7 +110,7 @@
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
- TPublic::Pair::from_string(&format!("//{}", seed), None)
+ TPublic::Pair::from_string(&format!("//{seed}"), None)
.expect("static values are valid; qed")
.public()
}
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -83,7 +83,7 @@
"" | "local" => Box::new(chain_spec::local_testnet_config()),
path => {
let path = std::path::PathBuf::from(path);
- let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)
+ let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path)?)
as Box<dyn sc_service::ChainSpec>;
match chain_spec.runtime_id() {
@@ -352,7 +352,7 @@
&polkadot_cli,
config.tokio_handle.clone(),
)
- .map_err(|err| format!("Relay chain argument error: {}", err))?;
+ .map_err(|err| format!("Relay chain argument error: {err}"))?;
cmd.run(config, polkadot_config)
})
@@ -464,7 +464,7 @@
runner.run_node_until_exit(|config| async move {
let hwbench = if !cli.no_hardware_benchmarks {
config.database.path().map(|database_path| {
- let _ = std::fs::create_dir_all(&database_path);
+ let _ = std::fs::create_dir_all(database_path);
sc_sysinfo::gather_hwbench(Some(database_path))
})
} else {
@@ -512,7 +512,7 @@
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))?;
+ .map_err(|e| format!("{e:?}"))?;
let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));
let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));
@@ -521,7 +521,7 @@
&polkadot_cli,
config.tokio_handle.clone(),
)
- .map_err(|err| format!("Relay chain argument error: {}", err))?;
+ .map_err(|err| format!("Relay chain argument error: {err}"))?;
info!("Parachain id: {:?}", para_id);
info!("Parachain Account: {}", parachain_account);
node/cli/src/service.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// std18use std::sync::Arc;19use std::sync::Mutex;20use std::collections::BTreeMap;21use std::time::Duration;22use std::pin::Pin;23use fc_rpc_core::types::FeeHistoryCache;24use futures::{25 Stream, StreamExt,26 stream::select,27 task::{Context, Poll},28};29use sp_keystore::KeystorePtr;30use tokio::time::Interval;3132use unique_rpc::overrides_handle;3334use serde::{Serialize, Deserialize};3536// Cumulus Imports37use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};38use cumulus_client_consensus_common::{39 ParachainConsensus, ParachainBlockImport as TParachainBlockImport,40};41use cumulus_client_service::{42 prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,43};44use cumulus_client_cli::CollatorOptions;45use cumulus_client_network::BlockAnnounceValidator;46use cumulus_primitives_core::ParaId;47use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;48use cumulus_relay_chain_interface::{RelayChainInterface, RelayChainResult};49use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;5051// Substrate Imports52use sp_api::BlockT;53use sc_executor::NativeElseWasmExecutor;54use sc_executor::NativeExecutionDispatch;55use sc_network::NetworkBlock;56use sc_network_sync::SyncingService;57use sc_service::{BasePath, Configuration, PartialComponents, TaskManager};58use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};59use sp_runtime::traits::BlakeTwo256;60use substrate_prometheus_endpoint::Registry;61use sc_client_api::BlockchainEvents;62use sc_consensus::ImportQueue;6364use polkadot_service::CollatorPair;6566// Frontier Imports67use fc_rpc_core::types::FilterPool;68use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6970use up_common::types::opaque::*;7172use crate::chain_spec::RuntimeIdentification;7374/// Unique native executor instance.75#[cfg(feature = "unique-runtime")]76pub struct UniqueRuntimeExecutor;7778#[cfg(feature = "quartz-runtime")]79/// Quartz native executor instance.80pub struct QuartzRuntimeExecutor;8182/// Opal native executor instance.83pub struct OpalRuntimeExecutor;8485#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]86pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;8788#[cfg(all(89 not(feature = "unique-runtime"),90 feature = "quartz-runtime",91 feature = "runtime-benchmarks"92))]93pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;9495#[cfg(all(96 not(feature = "unique-runtime"),97 not(feature = "quartz-runtime"),98 feature = "runtime-benchmarks"99))]100pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;101102#[cfg(feature = "unique-runtime")]103impl NativeExecutionDispatch for UniqueRuntimeExecutor {104 /// Only enable the benchmarking host functions when we actually want to benchmark.105 #[cfg(feature = "runtime-benchmarks")]106 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;107 /// Otherwise we only use the default Substrate host functions.108 #[cfg(not(feature = "runtime-benchmarks"))]109 type ExtendHostFunctions = ();110111 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {112 unique_runtime::api::dispatch(method, data)113 }114115 fn native_version() -> sc_executor::NativeVersion {116 unique_runtime::native_version()117 }118}119120#[cfg(feature = "quartz-runtime")]121impl NativeExecutionDispatch for QuartzRuntimeExecutor {122 /// Only enable the benchmarking host functions when we actually want to benchmark.123 #[cfg(feature = "runtime-benchmarks")]124 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;125 /// Otherwise we only use the default Substrate host functions.126 #[cfg(not(feature = "runtime-benchmarks"))]127 type ExtendHostFunctions = ();128129 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {130 quartz_runtime::api::dispatch(method, data)131 }132133 fn native_version() -> sc_executor::NativeVersion {134 quartz_runtime::native_version()135 }136}137138impl NativeExecutionDispatch for OpalRuntimeExecutor {139 /// Only enable the benchmarking host functions when we actually want to benchmark.140 #[cfg(feature = "runtime-benchmarks")]141 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;142 /// Otherwise we only use the default Substrate host functions.143 #[cfg(not(feature = "runtime-benchmarks"))]144 type ExtendHostFunctions = ();145146 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {147 opal_runtime::api::dispatch(method, data)148 }149150 fn native_version() -> sc_executor::NativeVersion {151 opal_runtime::native_version()152 }153}154155pub struct AutosealInterval {156 interval: Interval,157}158159impl AutosealInterval {160 pub fn new(config: &Configuration, interval: Duration) -> Self {161 let _tokio_runtime = config.tokio_handle.enter();162 let interval = tokio::time::interval(interval);163164 Self { interval }165 }166}167168impl Stream for AutosealInterval {169 type Item = tokio::time::Instant;170171 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {172 self.interval.poll_tick(cx).map(Some)173 }174}175176pub fn open_frontier_backend<Block: BlockT, C: sp_blockchain::HeaderBackend<Block>>(177 client: Arc<C>,178 config: &Configuration,179) -> Result<Arc<fc_db::Backend<Block>>, String> {180 let config_dir = config181 .base_path182 .as_ref()183 .map(|base_path| base_path.config_dir(config.chain_spec.id()))184 .unwrap_or_else(|| {185 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())186 });187 let database_dir = config_dir.join("frontier").join("db");188189 Ok(Arc::new(fc_db::Backend::<Block>::new(190 client,191 &fc_db::DatabaseSettings {192 source: fc_db::DatabaseSource::RocksDb {193 path: database_dir,194 cache_size: 0,195 },196 },197 )?))198}199200type FullClient<RuntimeApi, ExecutorDispatch> =201 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;202type FullBackend = sc_service::TFullBackend<Block>;203type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;204type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =205 TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;206207/// Starts a `ServiceBuilder` for a full service.208///209/// Use this macro if you don't actually need the full service, but just the builder in order to210/// be able to perform chain operations.211#[allow(clippy::type_complexity)]212pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(213 config: &Configuration,214 build_import_queue: BIQ,215) -> Result<216 PartialComponents<217 FullClient<RuntimeApi, ExecutorDispatch>,218 FullBackend,219 FullSelectChain,220 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,221 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,222 (223 Option<Telemetry>,224 Option<FilterPool>,225 Arc<fc_db::Backend<Block>>,226 Option<TelemetryWorkerHandle>,227 FeeHistoryCache,228 ),229 >,230 sc_service::Error,231>232where233 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,234 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>235 + Send236 + Sync237 + 'static,238 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,239 ExecutorDispatch: NativeExecutionDispatch + 'static,240 BIQ: FnOnce(241 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,242 Arc<FullBackend>,243 &Configuration,244 Option<TelemetryHandle>,245 &TaskManager,246 ) -> Result<247 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,248 sc_service::Error,249 >,250{251 let _telemetry = config252 .telemetry_endpoints253 .clone()254 .filter(|x| !x.is_empty())255 .map(|endpoints| -> Result<_, sc_telemetry::Error> {256 let worker = TelemetryWorker::new(16)?;257 let telemetry = worker.handle().new_telemetry(endpoints);258 Ok((worker, telemetry))259 })260 .transpose()?;261262 let telemetry = config263 .telemetry_endpoints264 .clone()265 .filter(|x| !x.is_empty())266 .map(|endpoints| -> Result<_, sc_telemetry::Error> {267 let worker = TelemetryWorker::new(16)?;268 let telemetry = worker.handle().new_telemetry(endpoints);269 Ok((worker, telemetry))270 })271 .transpose()?;272273 let executor = sc_service::new_native_or_wasm_executor(config);274275 let (client, backend, keystore_container, task_manager) =276 sc_service::new_full_parts::<Block, RuntimeApi, _>(277 config,278 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),279 executor,280 )?;281 let client = Arc::new(client);282283 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());284285 let telemetry = telemetry.map(|(worker, telemetry)| {286 task_manager287 .spawn_handle()288 .spawn("telemetry", None, worker.run());289 telemetry290 });291292 let select_chain = sc_consensus::LongestChain::new(backend.clone());293294 let transaction_pool = sc_transaction_pool::BasicPool::new_full(295 config.transaction_pool.clone(),296 config.role.is_authority().into(),297 config.prometheus_registry(),298 task_manager.spawn_essential_handle(),299 client.clone(),300 );301302 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));303304 let frontier_backend = open_frontier_backend(client.clone(), config)?;305306 let import_queue = build_import_queue(307 client.clone(),308 backend.clone(),309 config,310 telemetry.as_ref().map(|telemetry| telemetry.handle()),311 &task_manager,312 )?;313 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));314315 let params = PartialComponents {316 backend,317 client,318 import_queue,319 keystore_container,320 task_manager,321 transaction_pool,322 select_chain,323 other: (324 telemetry,325 filter_pool,326 frontier_backend,327 telemetry_worker_handle,328 fee_history_cache,329 ),330 };331332 Ok(params)333}334335async fn build_relay_chain_interface(336 polkadot_config: Configuration,337 parachain_config: &Configuration,338 telemetry_worker_handle: Option<TelemetryWorkerHandle>,339 task_manager: &mut TaskManager,340 collator_options: CollatorOptions,341 hwbench: Option<sc_sysinfo::HwBench>,342) -> RelayChainResult<(343 Arc<(dyn RelayChainInterface + 'static)>,344 Option<CollatorPair>,345)> {346 if collator_options.relay_chain_rpc_urls.is_empty() {347 build_inprocess_relay_chain(348 polkadot_config,349 parachain_config,350 telemetry_worker_handle,351 task_manager,352 hwbench,353 )354 } else {355 build_minimal_relay_chain_node(356 polkadot_config,357 task_manager,358 collator_options.relay_chain_rpc_urls,359 )360 .await361 }362}363364macro_rules! clone {365 ($($i:ident),* $(,)?) => {366 $(367 let $i = $i.clone();368 )*369 };370}371372/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.373///374/// This is the actual implementation that is abstract over the executor and the runtime api.375#[sc_tracing::logging::prefix_logs_with("Parachain")]376async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(377 parachain_config: Configuration,378 polkadot_config: Configuration,379 collator_options: CollatorOptions,380 id: ParaId,381 build_import_queue: BIQ,382 build_consensus: BIC,383 hwbench: Option<sc_sysinfo::HwBench>,384) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>385where386 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,387 Runtime: RuntimeInstance + Send + Sync + 'static,388 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,389 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,390 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>391 + Send392 + Sync393 + 'static,394 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>395 + fp_rpc::EthereumRuntimeRPCApi<Block>396 + fp_rpc::ConvertTransactionRuntimeApi<Block>397 + sp_session::SessionKeys<Block>398 + sp_block_builder::BlockBuilder<Block>399 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>400 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>401 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>402 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>403 + up_pov_estimate_rpc::PovEstimateApi<Block>404 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>405 + sp_api::Metadata<Block>406 + sp_offchain::OffchainWorkerApi<Block>407 + cumulus_primitives_core::CollectCollationInfo<Block>,408 ExecutorDispatch: NativeExecutionDispatch + 'static,409 BIQ: FnOnce(410 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,411 Arc<FullBackend>,412 &Configuration,413 Option<TelemetryHandle>,414 &TaskManager,415 ) -> Result<416 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,417 sc_service::Error,418 >,419 BIC: FnOnce(420 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,421 Arc<FullBackend>,422 Option<&Registry>,423 Option<TelemetryHandle>,424 &TaskManager,425 Arc<dyn RelayChainInterface>,426 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,427 Arc<SyncingService<Block>>,428 KeystorePtr,429 bool,430 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,431{432 let parachain_config = prepare_node_config(parachain_config);433434 let params =435 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;436 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =437 params.other;438439 let client = params.client.clone();440 let backend = params.backend.clone();441 let mut task_manager = params.task_manager;442443 let (relay_chain_interface, collator_key) = build_relay_chain_interface(444 polkadot_config,445 ¶chain_config,446 telemetry_worker_handle,447 &mut task_manager,448 collator_options.clone(),449 hwbench.clone(),450 )451 .await452 .map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;453454 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);455456 let force_authoring = parachain_config.force_authoring;457 let validator = parachain_config.role.is_authority();458 let prometheus_registry = parachain_config.prometheus_registry().cloned();459 let transaction_pool = params.transaction_pool.clone();460 let import_queue_service = params.import_queue.service();461462 let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =463 sc_service::build_network(sc_service::BuildNetworkParams {464 config: ¶chain_config,465 client: client.clone(),466 transaction_pool: transaction_pool.clone(),467 spawn_handle: task_manager.spawn_handle(),468 import_queue: params.import_queue,469 block_announce_validator_builder: Some(Box::new(|_| {470 Box::new(block_announce_validator)471 })),472 warp_sync_params: None,473 })?;474475 let select_chain = params.select_chain.clone();476477 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(478 task_manager.spawn_handle(),479 overrides_handle::<_, _, Runtime>(client.clone()),480 50,481 50,482 prometheus_registry.clone(),483 ));484485 let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<486 fc_mapping_sync::EthereumBlockNotification<Block>,487 > = Default::default();488 let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);489490 task_manager.spawn_essential_handle().spawn(491 "frontier-mapping-sync-worker",492 Some("frontier"),493 MappingSyncWorker::new(494 client.import_notification_stream(),495 Duration::new(6, 0),496 client.clone(),497 backend.clone(),498 overrides_handle::<_, _, Runtime>(client.clone()),499 frontier_backend.clone(),500 3,501 0,502 SyncStrategy::Normal,503 sync_service.clone(),504 pubsub_notification_sinks.clone(),505 )506 .for_each(|()| futures::future::ready(())),507 );508509 let runtime_id = parachain_config.chain_spec.runtime_id();510511 let rpc_builder = Box::new({512 clone!(513 client,514 backend,515 pubsub_notification_sinks,516 transaction_pool,517 network,518 sync_service,519 frontier_backend,520 );521 move |deny_unsafe, subscription_task_executor| {522 clone!(523 backend,524 runtime_id,525 client,526 transaction_pool,527 filter_pool,528 network,529 select_chain,530 block_data_cache,531 fee_history_cache,532 pubsub_notification_sinks,533 frontier_backend,534 );535536 #[cfg(not(feature = "pov-estimate"))]537 let _ = backend;538539 let full_deps = unique_rpc::FullDeps {540 runtime_id,541542 #[cfg(feature = "pov-estimate")]543 exec_params: uc_rpc::pov_estimate::ExecutorParams {544 wasm_method: parachain_config.wasm_method,545 default_heap_pages: parachain_config.default_heap_pages,546 max_runtime_instances: parachain_config.max_runtime_instances,547 runtime_cache_size: parachain_config.runtime_cache_size,548 },549550 #[cfg(feature = "pov-estimate")]551 backend,552553 eth_backend: frontier_backend,554 deny_unsafe,555 client,556 graph: transaction_pool.pool().clone(),557 pool: transaction_pool,558 // TODO: Unhardcode559 enable_dev_signer: false,560 filter_pool,561 network,562 sync: sync_service.clone(),563 select_chain,564 is_authority: validator,565 // TODO: Unhardcode566 max_past_logs: 10000,567 block_data_cache,568 fee_history_cache,569 // TODO: Unhardcode570 fee_history_limit: 2048,571 pubsub_notification_sinks,572 };573574 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(575 full_deps,576 subscription_task_executor,577 )578 .map_err(Into::into)579 }580 });581582 sc_service::spawn_tasks(sc_service::SpawnTasksParams {583 rpc_builder,584 client: client.clone(),585 transaction_pool: transaction_pool.clone(),586 task_manager: &mut task_manager,587 config: parachain_config,588 keystore: params.keystore_container.keystore(),589 backend: backend.clone(),590 network: network.clone(),591 sync_service: sync_service.clone(),592 system_rpc_tx,593 telemetry: telemetry.as_mut(),594 tx_handler_controller,595 })?;596597 if let Some(hwbench) = hwbench {598 sc_sysinfo::print_hwbench(&hwbench);599600 if let Some(ref mut telemetry) = telemetry {601 let telemetry_handle = telemetry.handle();602 task_manager.spawn_handle().spawn(603 "telemetry_hwbench",604 None,605 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),606 );607 }608 }609610 let announce_block = {611 let sync_service = sync_service.clone();612 Arc::new(Box::new(move |hash, data| {613 sync_service.announce_block(hash, data)614 }))615 };616617 let relay_chain_slot_duration = Duration::from_secs(6);618619 let overseer_handle = relay_chain_interface620 .overseer_handle()621 .map_err(|e| sc_service::Error::Application(Box::new(e)))?;622623 if validator {624 let parachain_consensus = build_consensus(625 client.clone(),626 backend.clone(),627 prometheus_registry.as_ref(),628 telemetry.as_ref().map(|t| t.handle()),629 &task_manager,630 relay_chain_interface.clone(),631 transaction_pool,632 sync_service.clone(),633 params.keystore_container.keystore(),634 force_authoring,635 )?;636637 let spawner = task_manager.spawn_handle();638639 let params = StartCollatorParams {640 para_id: id,641 block_status: client.clone(),642 announce_block,643 client: client.clone(),644 task_manager: &mut task_manager,645 spawner,646 parachain_consensus,647 import_queue: import_queue_service,648 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),649 relay_chain_interface,650 relay_chain_slot_duration,651 recovery_handle: Box::new(overseer_handle),652 sync_service,653 };654655 start_collator(params).await?;656 } else {657 let params = StartFullNodeParams {658 client: client.clone(),659 announce_block,660 task_manager: &mut task_manager,661 para_id: id,662 import_queue: import_queue_service,663 relay_chain_interface,664 relay_chain_slot_duration,665 recovery_handle: Box::new(overseer_handle),666 sync_service,667 };668669 start_full_node(params)?;670 }671672 start_network.start_network();673674 Ok((task_manager, client))675}676677/// Build the import queue for the the parachain runtime.678pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(679 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,680 backend: Arc<FullBackend>,681 config: &Configuration,682 telemetry: Option<TelemetryHandle>,683 task_manager: &TaskManager,684) -> Result<685 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,686 sc_service::Error,687>688where689 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>690 + Send691 + Sync692 + 'static,693 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>694 + sp_block_builder::BlockBuilder<Block>695 + sp_consensus_aura::AuraApi<Block, AuraId>696 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,697 ExecutorDispatch: NativeExecutionDispatch + 'static,698{699 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;700701 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());702703 cumulus_client_consensus_aura::import_queue::<704 sp_consensus_aura::sr25519::AuthorityPair,705 _,706 _,707 _,708 _,709 _,710 >(cumulus_client_consensus_aura::ImportQueueParams {711 block_import,712 client: client.clone(),713 create_inherent_data_providers: move |_, _| async move {714 let time = sp_timestamp::InherentDataProvider::from_system_time();715716 let slot =717 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(718 *time,719 slot_duration,720 );721722 Ok((slot, time))723 },724 registry: config.prometheus_registry(),725 spawner: &task_manager.spawn_essential_handle(),726 telemetry,727 })728 .map_err(Into::into)729}730731/// Start a normal parachain node.732pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(733 parachain_config: Configuration,734 polkadot_config: Configuration,735 collator_options: CollatorOptions,736 id: ParaId,737 hwbench: Option<sc_sysinfo::HwBench>,738) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>739where740 Runtime: RuntimeInstance + Send + Sync + 'static,741 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,742 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,743 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>744 + Send745 + Sync746 + 'static,747 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>748 + fp_rpc::EthereumRuntimeRPCApi<Block>749 + fp_rpc::ConvertTransactionRuntimeApi<Block>750 + sp_session::SessionKeys<Block>751 + sp_block_builder::BlockBuilder<Block>752 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>753 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>754 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>755 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>756 + up_pov_estimate_rpc::PovEstimateApi<Block>757 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>758 + sp_api::Metadata<Block>759 + sp_offchain::OffchainWorkerApi<Block>760 + cumulus_primitives_core::CollectCollationInfo<Block>761 + sp_consensus_aura::AuraApi<Block, AuraId>,762 ExecutorDispatch: NativeExecutionDispatch + 'static,763{764 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(765 parachain_config,766 polkadot_config,767 collator_options,768 id,769 parachain_build_import_queue,770 |client,771 backend,772 prometheus_registry,773 telemetry,774 task_manager,775 relay_chain_interface,776 transaction_pool,777 sync_oracle,778 keystore,779 force_authoring| {780 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;781782 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(783 task_manager.spawn_handle(),784 client.clone(),785 transaction_pool,786 prometheus_registry,787 telemetry.clone(),788 );789790 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());791792 Ok(AuraConsensus::build::<793 sp_consensus_aura::sr25519::AuthorityPair,794 _,795 _,796 _,797 _,798 _,799 _,800 >(BuildAuraConsensusParams {801 proposer_factory,802 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {803 let relay_chain_interface = relay_chain_interface.clone();804 async move {805 let parachain_inherent =806 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(807 relay_parent,808 &relay_chain_interface,809 &validation_data,810 id,811 ).await;812813 let time = sp_timestamp::InherentDataProvider::from_system_time();814815 let slot =816 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(817 *time,818 slot_duration,819 );820821 let parachain_inherent = parachain_inherent.ok_or_else(|| {822 Box::<dyn std::error::Error + Send + Sync>::from(823 "Failed to create parachain inherent",824 )825 })?;826 Ok((slot, time, parachain_inherent))827 }828 },829 block_import,830 para_client: client,831 backoff_authoring_blocks: Option::<()>::None,832 sync_oracle,833 keystore,834 force_authoring,835 slot_duration,836 // We got around 500ms for proposing837 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),838 telemetry,839 max_block_proposal_slot_portion: None,840 }))841 },842 hwbench,843 )844 .await845}846847fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(848 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,849 _: Arc<FullBackend>,850 config: &Configuration,851 _: Option<TelemetryHandle>,852 task_manager: &TaskManager,853) -> Result<854 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,855 sc_service::Error,856>857where858 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>859 + Send860 + Sync861 + 'static,862 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>863 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,864 ExecutorDispatch: NativeExecutionDispatch + 'static,865{866 Ok(sc_consensus_manual_seal::import_queue(867 Box::new(client.clone()),868 &task_manager.spawn_essential_handle(),869 config.prometheus_registry(),870 ))871}872873/// Builds a new development service. This service uses instant seal, and mocks874/// the parachain inherent875pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(876 config: Configuration,877 autoseal_interval: Duration,878) -> sc_service::error::Result<TaskManager>879where880 Runtime: RuntimeInstance + Send + Sync + 'static,881 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,882 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,883 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>884 + Send885 + Sync886 + 'static,887 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>888 + fp_rpc::EthereumRuntimeRPCApi<Block>889 + fp_rpc::ConvertTransactionRuntimeApi<Block>890 + sp_session::SessionKeys<Block>891 + sp_block_builder::BlockBuilder<Block>892 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>893 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>894 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>895 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>896 + up_pov_estimate_rpc::PovEstimateApi<Block>897 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>898 + sp_api::Metadata<Block>899 + sp_offchain::OffchainWorkerApi<Block>900 + cumulus_primitives_core::CollectCollationInfo<Block>901 + sp_consensus_aura::AuraApi<Block, AuraId>,902 ExecutorDispatch: NativeExecutionDispatch + 'static,903{904 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};905 use fc_consensus::FrontierBlockImport;906 use sc_client_api::HeaderBackend;907908 let sc_service::PartialComponents {909 client,910 backend,911 mut task_manager,912 import_queue,913 keystore_container,914 select_chain: maybe_select_chain,915 transaction_pool,916 other:917 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),918 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(919 &config,920 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,921 )?;922 let prometheus_registry = config.prometheus_registry().cloned();923924 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(925 task_manager.spawn_handle(),926 overrides_handle::<_, _, Runtime>(client.clone()),927 50,928 50,929 prometheus_registry.clone(),930 ));931932 let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<933 fc_mapping_sync::EthereumBlockNotification<Block>,934 > = Default::default();935 let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);936937 let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =938 sc_service::build_network(sc_service::BuildNetworkParams {939 config: &config,940 client: client.clone(),941 transaction_pool: transaction_pool.clone(),942 spawn_handle: task_manager.spawn_handle(),943 import_queue,944 block_announce_validator_builder: None,945 warp_sync_params: None,946 })?;947948 if config.offchain_worker.enabled {949 sc_service::build_offchain_workers(950 &config,951 task_manager.spawn_handle(),952 client.clone(),953 network.clone(),954 );955 }956957 let collator = config.role.is_authority();958959 let select_chain = maybe_select_chain.clone();960961 if collator {962 let block_import =963 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());964965 let env = sc_basic_authorship::ProposerFactory::new(966 task_manager.spawn_handle(),967 client.clone(),968 transaction_pool.clone(),969 prometheus_registry.as_ref(),970 telemetry.as_ref().map(|x| x.handle()),971 );972973 let transactions_commands_stream: Box<974 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,975 > = Box::new(976 transaction_pool977 .pool()978 .validated_pool()979 .import_notification_stream()980 .map(|_| EngineCommand::SealNewBlock {981 create_empty: true,982 finalize: false, // todo:collator finalize true983 parent_hash: None,984 sender: None,985 }),986 );987988 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));989 let idle_commands_stream: Box<990 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,991 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {992 create_empty: true,993 finalize: false, // todo:collator finalize true994 parent_hash: None,995 sender: None,996 }));997998 let commands_stream = select(transactions_commands_stream, idle_commands_stream);9991000 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;1001 let client_set_aside_for_cidp = client.clone();10021003 task_manager.spawn_essential_handle().spawn_blocking(1004 "authorship_task",1005 Some("block-authoring"),1006 run_manual_seal(ManualSealParams {1007 block_import,1008 env,1009 client: client.clone(),1010 pool: transaction_pool.clone(),1011 commands_stream,1012 select_chain: select_chain.clone(),1013 consensus_data_provider: None,1014 create_inherent_data_providers: move |block: Hash, ()| {1015 let current_para_block = client_set_aside_for_cidp1016 .number(block)1017 .expect("Header lookup should succeed")1018 .expect("Header passed in as parent should be present in backend.");10191020 let client_for_xcm = client_set_aside_for_cidp.clone();1021 async move {1022 let time = sp_timestamp::InherentDataProvider::from_system_time();10231024 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {1025 current_para_block,1026 relay_offset: 1000,1027 relay_blocks_per_para_block: 2,1028 para_blocks_per_relay_epoch: 0,1029 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(1030 &*client_for_xcm,1031 block,1032 Default::default(),1033 Default::default(),1034 ),1035 relay_randomness_config: (),1036 raw_downward_messages: vec![],1037 raw_horizontal_messages: vec![],1038 };10391040 let slot =1041 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(1042 *time,1043 slot_duration,1044 );10451046 Ok((time, slot, mocked_parachain))1047 }1048 },1049 }),1050 );1051 }10521053 task_manager.spawn_essential_handle().spawn(1054 "frontier-mapping-sync-worker",1055 Some("block-authoring"),1056 MappingSyncWorker::new(1057 client.import_notification_stream(),1058 Duration::new(6, 0),1059 client.clone(),1060 backend.clone(),1061 overrides_handle::<_, _, Runtime>(client.clone()),1062 frontier_backend.clone(),1063 3,1064 0,1065 SyncStrategy::Normal,1066 sync_service.clone(),1067 pubsub_notification_sinks.clone(),1068 )1069 .for_each(|()| futures::future::ready(())),1070 );10711072 #[cfg(feature = "pov-estimate")]1073 let rpc_backend = backend.clone();10741075 let runtime_id = config.chain_spec.runtime_id();10761077 let rpc_builder = Box::new({1078 clone!(1079 backend,1080 client,1081 sync_service,1082 frontier_backend,1083 network,1084 transaction_pool,1085 pubsub_notification_sinks1086 );1087 move |deny_unsafe, subscription_executor| {1088 clone!(1089 backend,1090 block_data_cache,1091 client,1092 fee_history_cache,1093 filter_pool,1094 network,1095 pubsub_notification_sinks,1096 );10971098 #[cfg(not(feature = "pov-estimate"))]1099 let _ = backend;11001101 let full_deps = unique_rpc::FullDeps {1102 runtime_id: runtime_id.clone(),11031104 #[cfg(feature = "pov-estimate")]1105 exec_params: uc_rpc::pov_estimate::ExecutorParams {1106 wasm_method: config.wasm_method,1107 default_heap_pages: config.default_heap_pages,1108 max_runtime_instances: config.max_runtime_instances,1109 runtime_cache_size: config.runtime_cache_size,1110 },11111112 #[cfg(feature = "pov-estimate")]1113 backend,1114 eth_backend: frontier_backend.clone(),1115 deny_unsafe,1116 client,1117 pool: transaction_pool.clone(),1118 graph: transaction_pool.pool().clone(),1119 // TODO: Unhardcode1120 enable_dev_signer: false,1121 filter_pool,1122 network,1123 sync: sync_service.clone(),1124 select_chain: select_chain.clone(),1125 is_authority: collator,1126 // TODO: Unhardcode1127 max_past_logs: 10000,1128 block_data_cache,1129 fee_history_cache,1130 // TODO: Unhardcode1131 fee_history_limit: 2048,1132 pubsub_notification_sinks,1133 };11341135 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1136 full_deps,1137 subscription_executor,1138 )1139 .map_err(Into::into)1140 }1141 });11421143 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1144 network,1145 sync_service,1146 client,1147 keystore: keystore_container.keystore(),1148 task_manager: &mut task_manager,1149 transaction_pool,1150 rpc_builder,1151 backend,1152 system_rpc_tx,1153 config,1154 telemetry: None,1155 tx_handler_controller,1156 })?;11571158 network_starter.start_network();1159 Ok(task_manager)1160}node/rpc/src/lib.rsdiffbeforeafterboth--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -289,7 +289,7 @@
io.merge(
Net::new(
client.clone(),
- network.clone(),
+ network,
// Whether to format the `peer_count` response as Hex (default) or not.
true,
)
pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -296,7 +296,7 @@
if !block_pending.is_empty() {
block_pending.into_iter().for_each(|(staker, amount)| {
- Self::get_frozen_balance(&staker).map(|b| {
+ if let Some(b) = Self::get_frozen_balance(&staker) {
let new_state = b.checked_sub(&amount).unwrap_or_default();
// In this case, setting a new state for the frozen funds cannot fail
@@ -305,7 +305,7 @@
// that we cannot (in the current implementation) unfreeze more funds
// than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.
Self::set_freeze_unchecked(&staker, new_state);
- });
+ };
});
}
@@ -598,8 +598,8 @@
// this value is set for the stakers to whom the recalculation will be performed
let next_recalc_block = current_recalc_block + config.recalculation_interval;
- let mut storage_iterator = Self::get_next_calculated_key()
- .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));
+ let storage_iterator =
+ Self::get_next_calculated_key().map_or(Staked::<T>::iter(), Staked::<T>::iter_from);
PreviousCalculatedRecord::<T>::set(None);
@@ -658,10 +658,8 @@
// stakers_number - keeps the remaining number of iterations (staker addresses to handle)
// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out
// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)
- while let Some((
- (current_id, staked_block),
- (amount, next_recalc_block_for_stake),
- )) = storage_iterator.next()
+ for ((current_id, staked_block), (amount, next_recalc_block_for_stake)) in
+ storage_iterator
{
// last_id is not equal current_id when we switch to handling a new staker address
// or just start handling the very first address. In the latter case last_id will be None and
@@ -859,11 +857,11 @@
if acc_amount < balance_per_block {
let res = (block, balance_per_block - acc_amount);
acc_amount = <BalanceOf<T>>::default();
- return Some(res);
+ Some(res)
} else {
acc_amount -= balance_per_block;
will_deleted_stakes_count += 1;
- return Some((block, <BalanceOf<T>>::default()));
+ Some((block, <BalanceOf<T>>::default()))
}
})
.collect::<Vec<_>>();
@@ -926,7 +924,7 @@
if amount.is_zero() {
<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(
&T::FreezeIdentifier::get(),
- &staker,
+ staker,
)
} else {
<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(
@@ -1026,10 +1024,10 @@
) {
let income = Self::calculate_income(base, iters);
- base.checked_add(&income).map(|res| {
+ if let Some(res) = base.checked_add(&income) {
<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));
*income_acc += income;
- });
+ };
}
fn calculate_income<I>(base: I, iters: u32) -> I
pallets/app-promotion/src/types.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/types.rs
+++ b/pallets/app-promotion/src/types.rs
@@ -149,16 +149,16 @@
Self {
recalculation_interval: config
.recalculation_interval
- .unwrap_or_else(|| T::RecalculationInterval::get()),
+ .unwrap_or_else(T::RecalculationInterval::get),
pending_interval: config
.pending_interval
- .unwrap_or_else(|| T::PendingInterval::get()),
+ .unwrap_or_else(T::PendingInterval::get),
interval_income: config
.interval_income
- .unwrap_or_else(|| T::IntervalIncome::get()),
+ .unwrap_or_else(T::IntervalIncome::get),
max_stakers_per_calculation: config
.max_stakers_per_calculation
- .unwrap_or_else(|| MAX_NUMBER_PAYOUTS),
+ .unwrap_or(MAX_NUMBER_PAYOUTS),
}
}
}
pallets/balances-adapter/src/lib.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -31,6 +31,12 @@
}
}
+impl<T: Config> Default for NativeFungibleHandle<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {
fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
&self.0
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -136,7 +136,7 @@
fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {
let key = evm_coder::types::String::from_utf8(from.key.into())
- .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;
+ .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {e}")))?;
let value = evm_coder::types::Bytes(from.value.to_vec());
Ok(Property { key, value })
}
@@ -201,10 +201,7 @@
pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {
Self {
field,
- value: match value {
- Some(value) => Some(value.into()),
- None => None,
- },
+ value: value.map(|value| value.into()),
}
}
/// Whether the field contains a value.
@@ -222,8 +219,7 @@
.ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;
let value = Some(value.try_into().map_err(|error| {
Self::Error::Revert(format!(
- "can't convert value to u32 \"{}\" because: \"{error}\"",
- value
+ "can't convert value to u32 \"{value}\" because: \"{error}\""
))
})?);
@@ -249,10 +245,8 @@
limits.sponsored_data_size = value;
}
CollectionLimitField::SponsoredDataRateLimit => {
- limits.sponsored_data_rate_limit = match value {
- Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),
- None => None,
- };
+ limits.sponsored_data_rate_limit =
+ value.map(up_data_structs::SponsoringRateLimit::Blocks);
}
CollectionLimitField::TokenLimit => {
limits.token_limit = value;
@@ -454,9 +448,9 @@
}
}
-impl Into<up_data_structs::AccessMode> for AccessMode {
- fn into(self) -> up_data_structs::AccessMode {
- match self {
+impl From<AccessMode> for up_data_structs::AccessMode {
+ fn from(value: AccessMode) -> Self {
+ match value {
AccessMode::Normal => up_data_structs::AccessMode::Normal,
AccessMode::AllowList => up_data_structs::AccessMode::AllowList,
}
pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -260,9 +260,9 @@
message: Some(msg), ..
}) => ExError::Revert(msg.into()),
DispatchError::Module(ModuleError { index, error, .. }) => {
- ExError::Revert(format!("error {:?} in pallet {}", error, index))
+ ExError::Revert(format!("error {error:?} in pallet {index}"))
}
- e => ExError::Revert(format!("substrate error: {:?}", e)),
+ e => ExError::Revert(format!("substrate error: {e:?}")),
}
}
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -184,10 +184,9 @@
/// @param contractAddress The contract for which a sponsor is requested.
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
fn sponsor(&self, contract_address: Address) -> Result<Option<eth::CrossAddress>> {
- Ok(match Pallet::<T>::get_sponsor(contract_address) {
- Some(ref value) => Some(eth::CrossAddress::from_sub_cross_account::<T>(value)),
- None => None,
- })
+ Ok(Pallet::<T>::get_sponsor(contract_address)
+ .as_ref()
+ .map(eth::CrossAddress::from_sub_cross_account::<T>))
}
/// Check tat contract has confirmed sponsor.
@@ -275,7 +274,7 @@
self.recorder().consume_sstore()?;
<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;
- <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())
+ <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit)
.map_err(dispatch_to_evm::<T>)?;
Ok(())
}
pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -376,7 +376,7 @@
<SponsoringMode<T>>::get(contract)
.or_else(|| {
#[allow(deprecated)]
- <SelfSponsoring<T>>::get(contract).then(|| SponsoringModeT::Allowlisted)
+ <SelfSponsoring<T>>::get(contract).then_some(SponsoringModeT::Allowlisted)
})
.unwrap_or_default()
}
@@ -410,7 +410,7 @@
/// Is user added to allowlist, or he is owner of specified contract
pub fn allowed(contract: H160, user: H160) -> bool {
- <Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user
+ <Allowlist<T>>::get(contract, user) || <Owner<T>>::get(contract) == user
}
/// Toggle contract allowlist access
@@ -425,7 +425,7 @@
/// Throw error if user is not allowed to reconfigure target contract
pub fn ensure_owner(contract: H160, user: H160) -> DispatchResult {
- ensure!(<Owner<T>>::get(&contract) == user, Error::<T>::NoPermission);
+ ensure!(<Owner<T>>::get(contract) == user, Error::<T>::NoPermission);
Ok(())
}
}
pallets/evm-migration/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-migration/src/lib.rs
+++ b/pallets/evm-migration/src/lib.rs
@@ -78,7 +78,7 @@
pub fn begin(origin: OriginFor<T>, address: H160) -> DispatchResult {
ensure_root(origin)?;
ensure!(
- <PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(&address),
+ <PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(address),
<Error<T>>::AccountNotEmpty,
);
@@ -97,12 +97,12 @@
) -> DispatchResult {
ensure_root(origin)?;
ensure!(
- <MigrationPending<T>>::get(&address),
+ <MigrationPending<T>>::get(address),
<Error<T>>::AccountIsNotMigrating,
);
for (k, v) in data {
- <pallet_evm::AccountStorages<T>>::insert(&address, k, v);
+ <pallet_evm::AccountStorages<T>>::insert(address, k, v);
}
Ok(())
}
@@ -115,11 +115,11 @@
pub fn finish(origin: OriginFor<T>, address: H160, code: Vec<u8>) -> DispatchResult {
ensure_root(origin)?;
ensure!(
- <MigrationPending<T>>::get(&address),
+ <MigrationPending<T>>::get(address),
<Error<T>>::AccountIsNotMigrating,
);
- <pallet_evm::AccountCodes<T>>::insert(&address, code);
+ <pallet_evm::AccountCodes<T>>::insert(address, code);
<MigrationPending<T>>::remove(address);
Ok(())
}
@@ -166,7 +166,7 @@
pub struct OnMethodCall<T>(PhantomData<T>);
impl<T: Config> pallet_evm::OnMethodCall<T> for OnMethodCall<T> {
fn is_reserved(contract: &H160) -> bool {
- <MigrationPending<T>>::get(&contract)
+ <MigrationPending<T>>::get(contract)
}
fn is_used(_contract: &H160) -> bool {
pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -333,7 +333,7 @@
&Value::new(0),
)?;
- Ok(amount.into())
+ Ok(amount)
}
}
}
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -161,7 +161,7 @@
fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
log::trace!(target: "fassets::get_currency_id", "call");
- Pallet::<T>::location_to_currency_ids(multi_location).map(|id| AssetIds::ForeignAssetId(id))
+ Pallet::<T>::location_to_currency_ids(multi_location).map(AssetIds::ForeignAssetId)
}
}
@@ -378,7 +378,7 @@
foreign_asset_id,
|maybe_location| -> DispatchResult {
ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);
- *maybe_location = Some(location.clone());
+ *maybe_location = Some(*location);
AssetMetadatas::<T>::try_mutate(
AssetIds::ForeignAssetId(foreign_asset_id),
@@ -422,7 +422,7 @@
// modify location
if location != old_multi_locations {
- LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());
+ LocationToCurrencyIds::<T>::remove(*old_multi_locations);
LocationToCurrencyIds::<T>::try_mutate(
location,
|maybe_currency_ids| -> DispatchResult {
@@ -437,7 +437,7 @@
)?;
}
*maybe_asset_metadatas = Some(metadata.clone());
- *old_multi_locations = location.clone();
+ *old_multi_locations = *location;
Ok(())
},
)
pallets/identity/src/types.rsdiffbeforeafterboth--- a/pallets/identity/src/types.rs
+++ b/pallets/identity/src/types.rs
@@ -104,7 +104,7 @@
Data::Raw(ref x) => {
let l = x.len().min(32);
let mut r = vec![l as u8 + 1; l + 1];
- r[1..].copy_from_slice(&x[..l as usize]);
+ r[1..].copy_from_slice(&x[..l]);
r
}
Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),
@@ -287,7 +287,7 @@
fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
let field = u64::decode(input)?;
Ok(Self(
- <BitFlags<IdentityField>>::from_bits(field as u64).map_err(|_| "invalid value")?,
+ <BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,
))
}
}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -20,6 +20,8 @@
//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
extern crate alloc;
+
+use alloc::string::ToString;
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
@@ -356,8 +358,7 @@
.transpose()
.map_err(|e| {
Error::Revert(alloc::format!(
- "Can not convert value \"baseURI\" to string with error \"{}\"",
- e
+ "Can not convert value \"baseURI\" to string with error \"{e}\""
))
})?;
@@ -675,7 +676,7 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
<Pallet<T>>::create_item(
self,
@@ -717,7 +718,7 @@
.map(Clone::clone)
.ok_or_else(|| {
let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();
- Error::Revert(alloc::format!("No permission for key {}", key))
+ Error::Revert(alloc::format!("No permission for key {key}"))
})?;
Ok(a)
}
@@ -752,14 +753,14 @@
/// @param tokenId Id for the token.
#[solidity(hide)]
fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::owner_of_cross(&self, token_id)
+ Self::owner_of_cross(self, token_id)
}
/// Returns the owner (in cross format) of the token.
///
/// @param tokenId Id for the token.
fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::token_owner(&self, token_id.try_into()?)
+ Self::token_owner(self, token_id.try_into()?)
.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
.map_err(|_| Error::Revert("token not found".into()))
}
@@ -789,7 +790,7 @@
.collect::<Result<Vec<_>>>()?;
<Self as CommonCollectionOperations<T>>::token_properties(
- &self,
+ self,
token_id.try_into()?,
if keys.is_empty() { None } else { Some(keys) },
)
@@ -1021,7 +1022,7 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
data.push(CreateItemData::<T> {
properties,
@@ -1056,7 +1057,7 @@
.map(eth::Property::try_into)
.collect::<Result<Vec<_>>>()?
.try_into()
- .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;
+ .map_err(|_| Error::Revert("too many properties".to_string()))?;
let caller = T::CrossAccountId::from_eth(caller);
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -166,10 +166,7 @@
#[pallet::config]
pub trait Config:
- frame_system::Config
- + pallet_common::Config
- + pallet_structure::Config
- + pallet_evm::Config
+ frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config
{
type WeightInfo: WeightInfo;
}
@@ -860,13 +857,7 @@
<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);
- <TokenData<T>>::insert(
- (collection.id, token),
- ItemData {
- owner: to.clone(),
- ..token_data
- },
- );
+ <TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });
if let Some(balance_to) = balance_to {
// from != to
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,6 +21,7 @@
extern crate alloc;
+use alloc::string::ToString;
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
@@ -353,8 +354,7 @@
.transpose()
.map_err(|e| {
Error::Revert(alloc::format!(
- "Can not convert value \"baseURI\" to string with error \"{}\"",
- e
+ "Can not convert value \"baseURI\" to string with error \"{e}\""
))
})?;
@@ -482,8 +482,8 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- let balance = balance(&self, token, &from)?;
- ensure_single_owner(&self, token, balance)?;
+ let balance = balance(self, token, &from)?;
+ ensure_single_owner(self, token, balance)?;
<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)
.map_err(dispatch_to_evm::<T>)?;
@@ -575,8 +575,8 @@
let caller = T::CrossAccountId::from_eth(caller);
let token = token_id.try_into()?;
- let balance = balance(&self, token, &caller)?;
- ensure_single_owner(&self, token, balance)?;
+ let balance = balance(self, token, &caller)?;
+ ensure_single_owner(self, token, balance)?;
<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;
Ok(())
@@ -622,7 +622,7 @@
return Err("item id should be next".into());
}
- let users = [(to.clone(), 1)]
+ let users = [(to, 1)]
.into_iter()
.collect::<BTreeMap<_, _>>()
.try_into()
@@ -706,9 +706,9 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
- let users = [(to.clone(), 1)]
+ let users = [(to, 1)]
.into_iter()
.collect::<BTreeMap<_, _>>()
.try_into()
@@ -750,7 +750,7 @@
.map(Clone::clone)
.ok_or_else(|| {
let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();
- Error::Revert(alloc::format!("No permission for key {}", key))
+ Error::Revert(alloc::format!("No permission for key {key}"))
})?;
Ok(a)
}
@@ -785,14 +785,14 @@
/// @param tokenId Id for the token.
#[solidity(hide)]
fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::owner_of_cross(&self, token_id)
+ Self::owner_of_cross(self, token_id)
}
/// Returns the owner (in cross format) of the token.
///
/// @param tokenId Id for the token.
fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::token_owner(&self, token_id.try_into()?)
+ Self::token_owner(self, token_id.try_into()?)
.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
.or_else(|err| match err {
TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),
@@ -827,7 +827,7 @@
.collect::<Result<Vec<_>>>()?;
<Self as CommonCollectionOperations<T>>::token_properties(
- &self,
+ self,
token_id.try_into()?,
if keys.is_empty() { None } else { Some(keys) },
)
@@ -1004,7 +1004,7 @@
}
expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
}
- let users = [(to.clone(), 1)]
+ let users = [(to, 1)]
.into_iter()
.collect::<BTreeMap<_, _>>()
.try_into()
@@ -1046,7 +1046,7 @@
.weight_calls_budget(<StructureWeight<T>>::find_parent());
let mut data = Vec::with_capacity(tokens.len());
- let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]
+ let users: BoundedBTreeMap<_, _, _> = [(to, 1)]
.into_iter()
.collect::<BTreeMap<_, _>>()
.try_into()
@@ -1067,7 +1067,7 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
let create_item_data = CreateItemData::<T> {
users: users.clone(),
@@ -1103,7 +1103,7 @@
.map(eth::Property::try_into)
.collect::<Result<Vec<_>>>()?
.try_into()
- .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;
+ .map_err(|_| Error::Revert("too many properties".to_string()))?;
let caller = T::CrossAccountId::from_eth(caller);
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1124,7 +1124,7 @@
if collection.ignores_token_restrictions(spender) {
return Ok(Self::compute_allowance_decrease(
- collection, token, from, &spender, amount,
+ collection, token, from, spender, amount,
));
}
@@ -1143,7 +1143,7 @@
return Ok(None);
}
- let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);
+ let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);
if allowance.is_some() {
return Ok(allowance);
}
pallets/scheduler-v2/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/lib.rs
+++ b/pallets/scheduler-v2/src/lib.rs
@@ -969,7 +969,7 @@
call: ScheduledCall<T>,
) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
// ensure id it is unique
- if Lookup::<T>::contains_key(&id) {
+ if Lookup::<T>::contains_key(id) {
return Err(Error::<T>::FailedToSchedule.into());
}
pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -280,7 +280,7 @@
) -> DispatchResultWithPostInfo {
let dispatch = T::CollectionDispatch::dispatch(collection)?;
let dispatch = dispatch.as_dyn();
- dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)
+ dispatch.burn_item_recursively(from, token, self_budget, breadth_budget)
}
/// Check if `token` indirectly owned by `user`
@@ -396,7 +396,7 @@
account: &T::CrossAccountId,
action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,
) -> DispatchResult {
- if is_collection(&account.as_eth()) {
+ if is_collection(account.as_eth()) {
fail!(<Error<T>>::CantNestTokenUnderCollection);
}
let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -113,13 +113,9 @@
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(
- caller.clone(),
- collection_helpers_address,
- data,
- Default::default(),
- )
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id =
+ T::CollectionDispatch::create(caller, collection_helpers_address, data, Default::default())
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
@@ -132,8 +128,7 @@
.expect("Collection creation price should be convertible to u128");
if value != creation_price {
return Err(format!(
- "Sent amount not equals to collection creation price ({0})",
- creation_price
+ "Sent amount not equals to collection creation price ({creation_price})",
)
.into());
}
@@ -383,8 +378,7 @@
map_eth_to_id(&collection_address)
.map(|id| id.0)
.ok_or(Error::Revert(format!(
- "failed to convert address {} into collectionId.",
- collection_address
+ "failed to convert address {collection_address} into collectionId."
)))
}
}
@@ -422,5 +416,5 @@
generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);
fn error_field_too_long(feild: &str, bound: usize) -> Error {
- Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))
+ Error::Revert(format!("{feild} is too long. Max length is {bound}."))
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -507,7 +507,7 @@
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let new_owner = T::CrossAccountId::from_sub(new_owner);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.change_owner(sender, new_owner.clone())
+ target_collection.change_owner(sender, new_owner)
}
/// Add an admin to a collection.
@@ -667,7 +667,7 @@
/// * `owner`: Address of the initial owner of the item.
/// * `data`: Token data describing the item to store on chain.
#[pallet::call_index(11)]
- #[pallet::weight(T::CommonWeightInfo::create_item(&data))]
+ #[pallet::weight(T::CommonWeightInfo::create_item(data))]
pub fn create_item(
origin: OriginFor<T>,
collection_id: CollectionId,
@@ -701,7 +701,7 @@
/// * `owner`: Address of the initial owner of the tokens.
/// * `items_data`: Vector of data describing each item to be created.
#[pallet::call_index(12)]
- #[pallet::weight(T::CommonWeightInfo::create_multiple_items(&items_data))]
+ #[pallet::weight(T::CommonWeightInfo::create_multiple_items(items_data))]
pub fn create_multiple_items(
origin: OriginFor<T>,
collection_id: CollectionId,
@@ -889,7 +889,7 @@
/// * `collection_id`: ID of the collection to which the tokens would belong.
/// * `data`: Explicit item creation data.
#[pallet::call_index(18)]
- #[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(&data))]
+ #[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(data))]
pub fn create_multiple_items_ex(
origin: OriginFor<T>,
collection_id: CollectionId,
@@ -1313,7 +1313,7 @@
collection_id: CollectionId,
) -> DispatchResult {
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.force_set_sponsor(sponsor.clone())
+ target_collection.force_set_sponsor(sponsor)
}
/// Force remove `sponsor` for `collection`.
primitives/data-structs/src/bounded.rsdiffbeforeafterboth--- a/primitives/data-structs/src/bounded.rs
+++ b/primitives/data-structs/src/bounded.rs
@@ -63,7 +63,7 @@
V: fmt::Debug,
{
use core::fmt::Debug;
- (&v as &Vec<V>).fmt(f)
+ (v as &Vec<V>).fmt(f)
}
#[cfg(feature = "serde1")]
@@ -114,7 +114,7 @@
V: fmt::Debug,
{
use core::fmt::Debug;
- (&v as &BTreeMap<K, V>).fmt(f)
+ (v as &BTreeMap<K, V>).fmt(f)
}
#[cfg(feature = "serde1")]
@@ -157,5 +157,5 @@
K: fmt::Debug + Ord,
{
use core::fmt::Debug;
- (&v as &BTreeSet<K>).fmt(f)
+ (v as &BTreeSet<K>).fmt(f)
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -536,7 +536,7 @@
type Target = Vec<u8>;
fn deref(&self) -> &Self::Target {
- return &self.0;
+ &self.0
}
}
@@ -816,6 +816,11 @@
Self(Default::default())
}
}
+impl Default for OwnerRestrictedSet {
+ fn default() -> Self {
+ Self::new()
+ }
+}
impl core::ops::Deref for OwnerRestrictedSet {
type Target = OwnerRestrictedSetInner;
fn deref(&self) -> &Self::Target {
@@ -1098,9 +1103,9 @@
pub value: PropertyValue,
}
-impl Into<(PropertyKey, PropertyValue)> for Property {
- fn into(self) -> (PropertyKey, PropertyValue) {
- (self.key, self.value)
+impl From<Property> for (PropertyKey, PropertyValue) {
+ fn from(value: Property) -> Self {
+ (value.key, value.value)
}
}
@@ -1116,9 +1121,9 @@
pub permission: PropertyPermission,
}
-impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {
- fn into(self) -> (PropertyKey, PropertyPermission) {
- (self.key, self.permission)
+impl From<PropertyKeyPermission> for (PropertyKey, PropertyPermission) {
+ fn from(value: PropertyKeyPermission) -> Self {
+ (value.key, value.permission)
}
}
@@ -1415,7 +1420,7 @@
value: Self::Value,
) -> Result<Option<Self::Value>, PropertiesError> {
let key_size = scoped_slice_size(scope, &key);
- let value_size = slice_size(&value) as u32;
+ let value_size = slice_size(&value);
if self.consumed_space + value_size + key_size > S && !cfg!(feature = "runtime-benchmarks")
{
@@ -1425,7 +1430,7 @@
let old_value = self.map.try_scoped_set(scope, key, value)?;
if let Some(old_value) = old_value.as_ref() {
- let old_value_size = slice_size(&old_value);
+ let old_value_size = slice_size(old_value);
self.consumed_space = self.consumed_space.saturating_sub(old_value_size) + value_size;
} else {
self.consumed_space += key_size + value_size;
runtime/common/config/xcm/foreignassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/foreignassets.rs
+++ b/runtime/common/config/xcm/foreignassets.rs
@@ -65,7 +65,7 @@
return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));
}
- match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {
+ match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {
ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))
}
@@ -206,9 +206,7 @@
return Some(AssetIds::NativeAssetId(NativeCurrency::Parent));
}
- if let Some(currency_id) =
- XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location.clone())
- {
+ if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
return Some(currency_id);
}
runtime/common/ethereum/precompiles/mod.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/mod.rs
+++ b/runtime/common/ethereum/precompiles/mod.rs
@@ -37,6 +37,16 @@
[hash(1), hash(20482)]
}
}
+
+impl<R> Default for UniquePrecompiles<R>
+where
+ R: pallet_evm::Config,
+{
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl<R> PrecompileSet for UniquePrecompiles<R>
where
R: pallet_evm::Config,
runtime/common/ethereum/precompiles/sr25519.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/sr25519.rs
+++ b/runtime/common/ethereum/precompiles/sr25519.rs
@@ -64,7 +64,7 @@
// Parse arguments
let public: sr25519::Public =
- sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?).into();
+ sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?);
let signature_bytes: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
let message: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
runtime/common/ethereum/precompiles/utils/data.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/utils/data.rs
+++ b/runtime/common/ethereum/precompiles/utils/data.rs
@@ -60,7 +60,7 @@
}
impl Into<Vec<u8>> for Bytes {
- fn into(self: Self) -> Vec<u8> {
+ fn into(self) -> Vec<u8> {
self.0
}
}
runtime/common/ethereum/precompiles/utils/mod.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/utils/mod.rs
+++ b/runtime/common/ethereum/precompiles/utils/mod.rs
@@ -73,7 +73,6 @@
}
}
- #[must_use]
/// Check that a function call is compatible with the context it is
/// called into.
pub fn check_function_modifier(
runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -78,7 +78,7 @@
let token_id: TokenId = token_id.try_into().ok()?;
withdraw_set_token_property::<T>(
&collection,
- &who,
+ who,
&token_id,
key.len() + value.len(),
)
@@ -88,7 +88,7 @@
ERC721UniqueExtensionsCall::Transfer { token_id, .. },
) => {
let token_id: TokenId = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
+ withdraw_transfer::<T>(&collection, who, &token_id).map(|()| sponsor)
}
UniqueNFTCall::ERC721UniqueMintable(
ERC721UniqueMintableCall::Mint { .. }
@@ -97,7 +97,7 @@
| ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },
) => withdraw_create_item::<T>(
&collection,
- &who,
+ who,
&CreateItemData::NFT(CreateNftData::default()),
)
.map(|()| sponsor),
runtime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -16,7 +16,6 @@
//! Implements EVM sponsoring logic via TransactionValidityHack
-use core::convert::TryInto;
use pallet_common::CollectionHandle;
use pallet_evm::account::CrossAccountId;
use pallet_fungible::Config as FungibleConfig;
@@ -95,7 +94,7 @@
..
} => {
let token_id = TokenId::try_from(token_id).ok()?;
- withdraw_set_token_property::<T>(&collection, &who, &token_id, key.len() + value.len())
+ withdraw_set_token_property::<T>(&collection, who, &token_id, key.len() + value.len())
}
}
}
@@ -242,7 +241,7 @@
MintCross { .. } => withdraw_create_item::<T>(
&collection,
- &who,
+ who,
&CreateItemData::NFT(CreateNftData::default()),
),
@@ -250,7 +249,7 @@
| TransferFromCross { token_id, .. }
| Transfer { token_id, .. } => {
let token_id = TokenId::try_from(token_id).ok()?;
- withdraw_transfer::<T>(&collection, &who, &token_id)
+ withdraw_transfer::<T>(&collection, who, &token_id)
}
}
}
@@ -275,7 +274,7 @@
| MintWithTokenUri { .. }
| MintWithTokenUriCheckId { .. } => withdraw_create_item::<T>(
&collection,
- &who,
+ who,
&CreateItemData::NFT(CreateNftData::default()),
),
}
@@ -311,18 +310,15 @@
Transfer { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&handle, &who, &token_id)
+ withdraw_transfer::<T>(&handle, who, &token_id)
}
TransferFrom { from, .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
let from = T::CrossAccountId::from_eth(from);
withdraw_transfer::<T>(&handle, &from, &token_id)
}
Approve { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
}
}
@@ -351,13 +347,11 @@
TransferCross { .. } | TransferFromCross { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&handle, &who, &token_id)
+ withdraw_transfer::<T>(&handle, who, &token_id)
}
ApproveCross { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
}
}
runtime/common/mod.rsdiffbeforeafterboth--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -204,10 +204,7 @@
&[],
);
- let should_upgrade = match version {
- None => true,
- Some(_) => false,
- };
+ let should_upgrade = version.is_none();
if should_upgrade {
log::info!(
@@ -220,7 +217,7 @@
.cloned()
.filter_map(|authority_id| {
weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));
- let vec = authority_id.clone().to_raw_vec();
+ let vec = authority_id.to_raw_vec();
let slice = vec.as_slice();
let array: Option<[u8; 32]> = match slice.try_into() {
Ok(a) => Some(a),
@@ -248,20 +245,20 @@
.into_iter()
.map(|(acc, aura)| {
(
- acc.clone(), // account id
- acc, // validator id
- SessionKeys { aura: aura.clone() }, // session keys
+ acc.clone(), // account id
+ acc, // validator id
+ SessionKeys { aura }, // session keys
)
})
.collect::<Vec<_>>();
- for (account, val, keys) in keys.iter().cloned() {
+ for (account, val, keys) in keys.iter() {
for id in <Runtime as pallet_session::Config>::Keys::key_ids() {
- <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), &val)
+ <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), val)
}
- <pallet_session::NextKeys<Runtime>>::insert(&val, &keys);
+ <pallet_session::NextKeys<Runtime>>::insert(val, keys);
// todo exercise caution, the following is taken from genesis
- if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(&account)
+ if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(account)
.is_err()
{
log::warn!(
@@ -271,7 +268,7 @@
// genesis) so it's really not a big deal and we assume that the user wants to
// do this since it's the only way a non-endowed account can contain a session
// key.
- frame_system::Pallet::<Runtime>::inc_providers(&account);
+ frame_system::Pallet::<Runtime>::inc_providers(account);
}
}
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -84,7 +84,7 @@
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
let budget = up_data_structs::budget::Value::new(10);
- Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)
+ <pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)
}
fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
runtime/common/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -240,7 +240,7 @@
withdraw_set_token_property(
&collection,
&T::CrossAccountId::from_sub(who.clone()),
- &token_id,
+ token_id,
// No overflow may happen, as data larger than usize can't reach here
properties.iter().map(|p| p.key.len() + p.value.len()).sum(),
)
test-pallets/utils/src/lib.rsdiffbeforeafterboth--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -170,7 +170,7 @@
fn ensure_origin_and_enabled(origin: OriginFor<T>) -> DispatchResult {
ensure_signed(origin)?;
<Enabled<T>>::get()
- .then(|| ())
+ .then_some(())
.ok_or(<Error<T>>::TestPalletDisabled.into())
}
}