From 365e60532bc7c5c28d0c01a8de22119b0c118055 Mon Sep 17 00:00:00 2001 From: Juan Ignacio Rios Date: Tue, 13 Aug 2024 11:53:55 +0200 Subject: [PATCH] cargo clippy changes --- clippy.toml | 0 nodes/parachain/src/chain_spec/common.rs | 6 +- .../parachain/src/chain_spec/polimec_paseo.rs | 2 +- nodes/parachain/src/command.rs | 4 +- nodes/parachain/src/service.rs | 10 +- pallets/democracy/src/conviction.rs | 11 +- pallets/democracy/src/lib.rs | 12 +- pallets/democracy/src/tests/cancellation.rs | 2 +- pallets/democracy/src/tests/decoders.rs | 4 +- pallets/democracy/src/tests/scheduling.rs | 2 +- pallets/dispenser/src/extensions.rs | 6 +- pallets/dispenser/src/lib.rs | 4 +- pallets/elections-phragmen/src/lib.rs | 25 ++- pallets/funding/src/functions/6_settlement.rs | 6 +- .../funding/src/functions/7_ct_migration.rs | 4 +- pallets/funding/src/functions/misc.rs | 8 +- .../funding/src/instantiator/calculations.rs | 11 +- .../src/instantiator/chain_interactions.rs | 2 +- pallets/funding/src/instantiator/macros.rs | 4 +- pallets/funding/src/instantiator/tests.rs | 12 +- pallets/funding/src/instantiator/types.rs | 4 +- pallets/funding/src/runtime_api.rs | 7 +- pallets/funding/src/tests/1_application.rs | 2 +- pallets/funding/src/tests/2_evaluation.rs | 17 +- pallets/funding/src/tests/3_auction.rs | 18 +- pallets/funding/src/tests/4_contribution.rs | 14 +- pallets/funding/src/tests/6_settlement.rs | 14 +- pallets/funding/src/tests/7_ct_migration.rs | 6 +- pallets/funding/src/tests/misc.rs | 22 +-- pallets/funding/src/tests/mod.rs | 6 +- pallets/funding/src/tests/runtime_api.rs | 16 +- pallets/funding/src/types.rs | 14 +- pallets/oracle-ocw/src/lib.rs | 11 +- pallets/oracle-ocw/src/mock.rs | 10 +- pallets/oracle-ocw/src/tests.rs | 12 +- pallets/oracle-ocw/src/traits.rs | 4 +- .../parachain-staking/src/auto_compound.rs | 10 +- pallets/parachain-staking/src/inflation.rs | 4 +- pallets/parachain-staking/src/mock.rs | 34 ++-- pallets/parachain-staking/src/tests.rs | 174 +++++++++--------- pallets/parachain-staking/src/types.rs | 2 +- pallets/xcm-executor/src/lib.rs | 44 ++--- pallets/xcm-executor/src/polimec_traits.rs | 2 + polimec-common/common/src/credentials/mod.rs | 6 +- runtimes/polimec/build.rs | 2 +- 45 files changed, 286 insertions(+), 304 deletions(-) create mode 100644 clippy.toml diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 000000000..e69de29bb diff --git a/nodes/parachain/src/chain_spec/common.rs b/nodes/parachain/src/chain_spec/common.rs index 7405f9b39..30283fbf6 100644 --- a/nodes/parachain/src/chain_spec/common.rs +++ b/nodes/parachain/src/chain_spec/common.rs @@ -139,9 +139,9 @@ pub fn genesis_config(genesis_config_params: GenesisConfigParams) -> serde_json: ], // (id, account_id, amount) "accounts": vec![ - (usdt_id, funding_assets_owner.clone(), 1000000000000u64), - (usdc_id, funding_assets_owner.clone(), 1000000000000u64), - (dot_id, funding_assets_owner.clone(), 1000000000000u64) + (usdt_id, funding_assets_owner.clone(), 1_000_000_000_000_u64), + (usdc_id, funding_assets_owner.clone(), 1_000_000_000_000_u64), + (dot_id, funding_assets_owner.clone(), 1_000_000_000_000_u64) ], }, "parachainStaking": { diff --git a/nodes/parachain/src/chain_spec/polimec_paseo.rs b/nodes/parachain/src/chain_spec/polimec_paseo.rs index 7387bf20b..6c5a47091 100644 --- a/nodes/parachain/src/chain_spec/polimec_paseo.rs +++ b/nodes/parachain/src/chain_spec/polimec_paseo.rs @@ -20,7 +20,7 @@ use sc_service::ChainType; -use crate::chain_spec::{common::*, get_properties, Extensions, GenericChainSpec, DEFAULT_PARA_ID}; +use crate::chain_spec::{common::{GenesisConfigParams, alice, bob, charlie, dave, eve, genesis_config}, get_properties, Extensions, GenericChainSpec, DEFAULT_PARA_ID}; use polimec_runtime::{AccountId, MinCandidateStk}; pub fn get_local_chain_spec() -> GenericChainSpec { diff --git a/nodes/parachain/src/command.rs b/nodes/parachain/src/command.rs index 3d10d809b..6e1ec5e09 100644 --- a/nodes/parachain/src/command.rs +++ b/nodes/parachain/src/command.rs @@ -190,7 +190,7 @@ pub fn run() -> Result<()> { &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) }) @@ -280,7 +280,7 @@ pub fn run() -> Result<()> { 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))?; + .map_err(|err| format!("Relay chain argument error: {err}"))?; info!("Parachain Account: {parachain_account}"); info!("Is collating: {}", if config.role.is_authority() { "yes" } else { "no" }); diff --git a/nodes/parachain/src/service.rs b/nodes/parachain/src/service.rs index 8acf9bc94..54f0dcb88 100644 --- a/nodes/parachain/src/service.rs +++ b/nodes/parachain/src/service.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Service and ServiceFactory implementation. Specialized wrapper over substrate service. +//! Service and `ServiceFactory` implementation. Specialized wrapper over substrate service. // std use std::{sync::Arc, time::Duration}; @@ -61,7 +61,7 @@ type ParachainBackend = TFullBackend; type ParachainBlockImport = TParachainBlockImport, ParachainBackend>; -/// Assembly of PartialComponents (enough to run chain ops subcommands) +/// Assembly of `PartialComponents` (enough to run chain ops subcommands) pub type Service = PartialComponents< ParachainClient, ParachainBackend, @@ -126,7 +126,7 @@ pub fn new_partial(config: &Configuration) -> Result client.clone(), block_import.clone(), config, - telemetry.as_ref().map(|telemetry| telemetry.handle()), + telemetry.as_ref().map(sc_telemetry::Telemetry::handle), &task_manager, )?; @@ -291,7 +291,7 @@ async fn start_node_impl( backend.clone(), block_import, prometheus_registry.as_ref(), - telemetry.as_ref().map(|t| t.handle()), + telemetry.as_ref().map(sc_telemetry::Telemetry::handle), &task_manager, relay_chain_interface.clone(), transaction_pool, @@ -329,7 +329,7 @@ fn build_import_queue( >( client, block_import, - move |_, _| async move { + move |_, ()| async move { let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); Ok(timestamp) }, diff --git a/pallets/democracy/src/conviction.rs b/pallets/democracy/src/conviction.rs index 26bffb002..513c0b613 100644 --- a/pallets/democracy/src/conviction.rs +++ b/pallets/democracy/src/conviction.rs @@ -21,9 +21,12 @@ use sp_runtime::{ use sp_std::{prelude::*, result::Result}; /// A value denoting the strength of conviction of a vote. -#[derive(Encode, MaxEncodedLen, Decode, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug, TypeInfo)] +#[derive( + Encode, MaxEncodedLen, Decode, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug, TypeInfo, Default, +)] pub enum Conviction { /// 0.1x votes, unlocked. + #[default] None, /// 1x votes, locked for an enactment period following a successful vote. Locked1x, @@ -39,12 +42,6 @@ pub enum Conviction { Locked6x, } -impl Default for Conviction { - fn default() -> Self { - Conviction::None - } -} - impl From for u8 { fn from(c: Conviction) -> u8 { match c { diff --git a/pallets/democracy/src/lib.rs b/pallets/democracy/src/lib.rs index 552e6167a..80f2bf514 100644 --- a/pallets/democracy/src/lib.rs +++ b/pallets/democracy/src/lib.rs @@ -813,12 +813,12 @@ pub mod pallet { return Err(Error::::NoProposal.into()); } - let mut existing_vetoers = >::get(&proposal_hash).map(|pair| pair.1).unwrap_or_default(); + let mut existing_vetoers = >::get(proposal_hash).map(|pair| pair.1).unwrap_or_default(); let insert_position = existing_vetoers.binary_search(&who).err().ok_or(Error::::AlreadyVetoed)?; existing_vetoers.try_insert(insert_position, who.clone()).map_err(|_| Error::::TooMany)?; let until = >::block_number().saturating_add(T::CooloffPeriod::get()); - >::insert(&proposal_hash, (until, existing_vetoers)); + >::insert(proposal_hash, (until, existing_vetoers)); Self::deposit_event(Event::::Vetoed { who, proposal_hash, until }); >::kill(); @@ -1020,7 +1020,7 @@ pub mod pallet { // Insert the proposal into the blacklist. let permanent = (BlockNumberFor::::max_value(), BoundedVec::::default()); - Blacklist::::insert(&proposal_hash, permanent); + Blacklist::::insert(proposal_hash, permanent); // Remove the queued proposal, if it's there. PublicProps::::mutate(|props| { @@ -1229,7 +1229,7 @@ impl Pallet { /// Actually enact a vote, if legit. fn try_vote(who: &T::AccountId, ref_index: ReferendumIndex, vote: AccountVote>) -> DispatchResult { let mut status = Self::referendum_status(ref_index)?; - ensure!(vote.balance() <= T::Fungible::total_balance(&who), Error::::InsufficientFunds); + ensure!(vote.balance() <= T::Fungible::total_balance(who), Error::::InsufficientFunds); VotingOf::::try_mutate(who, |voting| -> DispatchResult { if let Voting::Direct { ref mut votes, delegations, .. } = voting { match votes.binary_search_by_key(&ref_index, |i| i.0) { @@ -1479,7 +1479,7 @@ impl Pallet { Self::transfer_metadata(MetadataOwner::External, MetadataOwner::Referendum(ref_index)); Ok(()) } else { - return Err(Error::::NoneWaiting.into()); + Err(Error::::NoneWaiting.into()) } } @@ -1509,7 +1509,7 @@ impl Pallet { } Ok(()) } else { - return Err(Error::::NoneWaiting.into()); + Err(Error::::NoneWaiting.into()) } } diff --git a/pallets/democracy/src/tests/cancellation.rs b/pallets/democracy/src/tests/cancellation.rs index f60d1c265..61ba57ca8 100644 --- a/pallets/democracy/src/tests/cancellation.rs +++ b/pallets/democracy/src/tests/cancellation.rs @@ -18,7 +18,7 @@ fn cancel_referendum_should_work() { new_test_ext().execute_with(|| { let r = Democracy::inject_referendum(2, set_balance_proposal(2), VoteThreshold::SuperMajorityApprove, 0); assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r, aye(1))); - assert_ok!(Democracy::cancel_referendum(RuntimeOrigin::root(), r.into())); + assert_ok!(Democracy::cancel_referendum(RuntimeOrigin::root(), r)); assert_eq!(Democracy::lowest_unbaked(), 0); next_block(); diff --git a/pallets/democracy/src/tests/decoders.rs b/pallets/democracy/src/tests/decoders.rs index acafa04a2..0b61c958d 100644 --- a/pallets/democracy/src/tests/decoders.rs +++ b/pallets/democracy/src/tests/decoders.rs @@ -24,7 +24,7 @@ fn test_decode_compact_u32_at() { migration::put_storage_value(b"test", b"", &[], v); assert_eq!(decode_compact_u32_at(b"test"), None); - for v in vec![0, 10, u32::MAX] { + for v in [0, 10, u32::MAX] { let compact_v = parity_scale_codec::Compact(v); unhashed::put(b"test", &compact_v); assert_eq!(decode_compact_u32_at(b"test"), Some(v)); @@ -38,7 +38,7 @@ fn test_decode_compact_u32_at() { #[test] fn len_of_deposit_of() { new_test_ext().execute_with(|| { - for l in vec![0, 1, 200, 1000] { + for l in [0, 1, 200, 1000] { let value: (BoundedVec, u64) = ((0..l).map(|_| Default::default()).collect::>().try_into().unwrap(), 3u64); DepositOf::::insert(2, value); diff --git a/pallets/democracy/src/tests/scheduling.rs b/pallets/democracy/src/tests/scheduling.rs index 9140c9e06..20dcddd2f 100644 --- a/pallets/democracy/src/tests/scheduling.rs +++ b/pallets/democracy/src/tests/scheduling.rs @@ -93,7 +93,7 @@ fn lowest_unbaked_should_be_sensible() { assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r1, aye(1))); assert_ok!(Democracy::vote(RuntimeOrigin::signed(1), r2, aye(1))); // r3 is canceled - assert_ok!(Democracy::cancel_referendum(RuntimeOrigin::root(), r3.into())); + assert_ok!(Democracy::cancel_referendum(RuntimeOrigin::root(), r3)); assert_eq!(Democracy::lowest_unbaked(), 0); next_block(); diff --git a/pallets/dispenser/src/extensions.rs b/pallets/dispenser/src/extensions.rs index b56e92b1a..0d2342185 100644 --- a/pallets/dispenser/src/extensions.rs +++ b/pallets/dispenser/src/extensions.rs @@ -219,10 +219,8 @@ where len: usize, result: &DispatchResult, ) -> Result<(), TransactionValidityError> { - if let Some(pre) = pre { - if let Some(pre) = pre { - S::post_dispatch(Some(pre), info, post_info, len, result)?; - } + if let Some(Some(pre)) = pre { + S::post_dispatch(Some(pre), info, post_info, len, result)?; } Ok(()) } diff --git a/pallets/dispenser/src/lib.rs b/pallets/dispenser/src/lib.rs index 5b3982a02..72594415d 100644 --- a/pallets/dispenser/src/lib.rs +++ b/pallets/dispenser/src/lib.rs @@ -145,9 +145,9 @@ pub mod pallet { impl Pallet { #[pallet::feeless_if( | origin: &OriginFor, jwt: &UntrustedToken | -> bool { if let Ok((_, did, _, _)) = T::InvestorOrigin::ensure_origin(origin.clone(), jwt, T::VerifierPublicKey::get()) { - return Dispensed::::get(did).is_none() + Dispensed::::get(did).is_none() } else { - return false + false } })] #[pallet::call_index(0)] diff --git a/pallets/elections-phragmen/src/lib.rs b/pallets/elections-phragmen/src/lib.rs index 304d14b4b..5de6fc328 100644 --- a/pallets/elections-phragmen/src/lib.rs +++ b/pallets/elections-phragmen/src/lib.rs @@ -102,7 +102,6 @@ use frame_support::{ }, weights::Weight, }; -use log; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_npos_elections::{ElectionResult, ExtendedBalance}; @@ -572,7 +571,7 @@ pub mod pallet { #[pallet::call_index(5)] #[pallet::weight(T::WeightInfo::clean_defunct_voters(*num_voters, *num_defunct))] pub fn clean_defunct_voters(origin: OriginFor, num_voters: u32, num_defunct: u32) -> DispatchResult { - let _ = ensure_root(origin)?; + ensure_root(origin)?; >::iter() .take(num_voters as usize) @@ -729,7 +728,7 @@ pub mod pallet { // once this genesis voter is removed, and for now it is okay because // remove_lock is noop if lock is not there. >::insert( - &member, + member, Voter { votes: vec![member.clone()], stake: *stake, lockup_till: T::VotingLockPeriod::get() }, ); @@ -1373,7 +1372,7 @@ mod tests { self } - pub fn build_and_execute(self, test: impl FnOnce() -> ()) { + pub fn build_and_execute(self, test: impl FnOnce()) { sp_tracing::try_init_simple(); MEMBERS.with(|m| *m.borrow_mut() = self.genesis_members.iter().map(|(m, _)| *m).collect::>()); let mut ext: sp_io::TestExternalities = RuntimeGenesisConfig { @@ -2002,7 +2001,7 @@ mod tests { assert_ok!(vote(RuntimeOrigin::signed(2), vec![5], 20)); assert_ok!(vote(RuntimeOrigin::signed(3), vec![5], 30)); - assert_eq_uvec!(all_voters(), vec![2, 3]); + assert_eq_uvec!(all_voters(), [2, 3]); assert_eq!(balances(&2), (20, 0)); assert_eq!(locked_stake_of(&2), 20); assert_eq!(balances(&3), (30, 0)); @@ -2014,12 +2013,12 @@ mod tests { System::set_block_number(3); assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); - assert_eq_uvec!(all_voters(), vec![3]); + assert_eq_uvec!(all_voters(), [3]); assert!(votes_of(&2).is_empty()); assert_eq!(locked_stake_of(&2), 0); assert_eq!(balances(&2), (20, 0)); - assert_eq!(Balances::locks(&2).len(), 0); + assert_eq!(Balances::locks(2).len(), 0); }); } @@ -2074,7 +2073,7 @@ mod tests { assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 15)); assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); - assert_eq_uvec!(all_voters(), vec![2, 3, 4]); + assert_eq_uvec!(all_voters(), [2, 3, 4]); assert_eq!(votes_of(&2), vec![5]); assert_eq!(votes_of(&3), vec![3]); @@ -2094,7 +2093,7 @@ mod tests { assert_eq!(members_and_stake(), vec![(3, 30), (5, 20)]); assert!(Elections::runners_up().is_empty()); - assert_eq_uvec!(all_voters(), vec![2, 3, 4]); + assert_eq_uvec!(all_voters(), [2, 3, 4]); assert!(candidate_ids().is_empty()); assert_eq!(>::decode_len(), None); @@ -2170,7 +2169,7 @@ mod tests { // candidate 4 is affected by an old vote. assert_eq!(members_and_stake(), vec![(4, 30), (5, 50)]); assert_eq!(Elections::election_rounds(), 2); - assert_eq_uvec!(all_voters(), vec![3, 5]); + assert_eq_uvec!(all_voters(), [3, 5]); }); } @@ -2402,7 +2401,7 @@ mod tests { // no new candidates but old members and runners-up are always added. assert!(candidate_ids().is_empty()); assert_eq!(Elections::election_rounds(), b / 5); - assert_eq_uvec!(all_voters(), vec![2, 3, 4, 5]); + assert_eq_uvec!(all_voters(), [2, 3, 4, 5]); }; // this state will always persist when no further input is given. @@ -2533,7 +2532,7 @@ mod tests { System::set_block_number(5); Elections::on_initialize(System::block_number()); - assert_eq_uvec!(members_ids(), vec![3, 4]); + assert_eq_uvec!(members_ids(), [3, 4]); assert_eq!(Elections::election_rounds(), 1); }); } @@ -2941,7 +2940,7 @@ mod tests { // wrong member to remove. ExtBuilder::default().desired_runners_up(1).build_and_execute(|| { setup(); - assert!(matches!(Elections::remove_and_replace_member(&2, false), Err(_))); + assert!(Elections::remove_and_replace_member(&2, false).is_err()); }); } diff --git a/pallets/funding/src/functions/6_settlement.rs b/pallets/funding/src/functions/6_settlement.rs index eca7da42d..47140744c 100644 --- a/pallets/funding/src/functions/6_settlement.rs +++ b/pallets/funding/src/functions/6_settlement.rs @@ -135,10 +135,8 @@ impl Pallet { pub fn do_settle_bid(bid: BidInfoOf, project_id: ProjectId) -> DispatchResult { let project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; let project_metadata = ProjectsMetadata::::get(project_id).ok_or(Error::::ProjectMetadataNotFound)?; - let funding_success = match project_details.status { - ProjectStatus::SettlementStarted(FundingOutcome::Success) => true, - _ => false, - }; + let funding_success = + matches!(project_details.status, ProjectStatus::SettlementStarted(FundingOutcome::Success)); let wap = project_details.weighted_average_price.ok_or(Error::::ImpossibleState)?; ensure!( diff --git a/pallets/funding/src/functions/7_ct_migration.rs b/pallets/funding/src/functions/7_ct_migration.rs index 310fcd6f5..f0bb2a94e 100644 --- a/pallets/funding/src/functions/7_ct_migration.rs +++ b/pallets/funding/src/functions/7_ct_migration.rs @@ -92,7 +92,7 @@ impl Pallet { // TODO: set these constants with a proper value const EXECUTION_DOT: MultiAsset = MultiAsset { id: Concrete(MultiLocation { parents: 0, interior: Here }), - fun: Fungible(1_0_000_000_000u128), + fun: Fungible(10_000_000_000_u128), }; const MAX_WEIGHT: Weight = Weight::from_parts(20_000_000_000, 1_000_000); @@ -466,7 +466,7 @@ impl Pallet { Self::change_migration_status(project_id, participant.clone(), MigrationStatus::Sent(query_id))?; // * Process Data * - let xcm = Self::construct_migration_xcm_message(migrations.into(), query_id, pallet_index); + let xcm = Self::construct_migration_xcm_message(migrations, query_id, pallet_index); >::send_xcm(Here, project_multilocation, xcm).map_err(|_| Error::::XcmFailed)?; ActiveMigrationQueue::::insert(query_id, (project_id, participant.clone())); diff --git a/pallets/funding/src/functions/misc.rs b/pallets/funding/src/functions/misc.rs index a94f20305..0cf2aaa9b 100644 --- a/pallets/funding/src/functions/misc.rs +++ b/pallets/funding/src/functions/misc.rs @@ -393,11 +393,9 @@ impl Pallet { ensure!(project_details.status == current_round, Error::::IncorrectRound); ensure!(project_details.round_duration.ended(now) || skip_end_check, Error::::TooEarlyForRound); - let round_end = if let Some(round_duration) = maybe_round_duration { - Some(now.saturating_add(round_duration).saturating_sub(One::one())) - } else { - None - }; + let round_end = + maybe_round_duration.map(|round_duration| now.saturating_add(round_duration).saturating_sub(One::one())); + project_details.round_duration = BlockNumberPair::new(Some(now), round_end); project_details.status = next_round.clone(); diff --git a/pallets/funding/src/instantiator/calculations.rs b/pallets/funding/src/instantiator/calculations.rs index 36cd3a257..86f358e58 100644 --- a/pallets/funding/src/instantiator/calculations.rs +++ b/pallets/funding/src/instantiator/calculations.rs @@ -1,4 +1,5 @@ use super::*; +use core::cmp::Ordering; use itertools::GroupBy; use polimec_common::USD_DECIMALS; @@ -676,12 +677,10 @@ impl< bucket.amount_left = mid_point; let new_wap = bucket.calculate_wap(auction_allocation); - if new_wap == target_wap { - return bucket - } else if new_wap < target_wap { - upper_bound = mid_point.saturating_sub(1u32.into()); - } else { - lower_bound = mid_point.saturating_add(1u32.into()); + match new_wap.cmp(&target_wap) { + Ordering::Equal => return bucket, + Ordering::Less => upper_bound = mid_point.saturating_sub(1u32.into()), + Ordering::Greater => lower_bound = mid_point.saturating_add(1u32.into()), } } diff --git a/pallets/funding/src/instantiator/chain_interactions.rs b/pallets/funding/src/instantiator/chain_interactions.rs index 12a8798e3..1f4c03bbe 100644 --- a/pallets/funding/src/instantiator/chain_interactions.rs +++ b/pallets/funding/src/instantiator/chain_interactions.rs @@ -735,7 +735,7 @@ impl< let amount = if let EvaluatorsOutcome::Rewarded(ref info) = evaluators_outcome { assert!(is_successful); - Pallet::::calculate_evaluator_reward(&evaluation, &info) + Pallet::::calculate_evaluator_reward(&evaluation, info) } else { assert!(!is_successful); Zero::zero() diff --git a/pallets/funding/src/instantiator/macros.rs b/pallets/funding/src/instantiator/macros.rs index 4f7bba1be..9156a83c2 100644 --- a/pallets/funding/src/instantiator/macros.rs +++ b/pallets/funding/src/instantiator/macros.rs @@ -58,8 +58,8 @@ macro_rules! find_event { let events = frame_system::Pallet::<$runtime>::events(); events.iter().find_map(|event_record| { let runtime_event = event_record.event.clone(); - let runtime_event = <<$runtime as crate::Config>::RuntimeEvent>::from(runtime_event); - if let Ok(funding_event) = TryInto::>::try_into(runtime_event) { + let runtime_event = <<$runtime as $crate::Config>::RuntimeEvent>::from(runtime_event); + if let Ok(funding_event) = TryInto::<$crate::Event<$runtime>>::try_into(runtime_event) { if let $pattern = funding_event { let mut is_match = true; $( diff --git a/pallets/funding/src/instantiator/tests.rs b/pallets/funding/src/instantiator/tests.rs index 3e732a77e..d64666930 100644 --- a/pallets/funding/src/instantiator/tests.rs +++ b/pallets/funding/src/instantiator/tests.rs @@ -24,7 +24,7 @@ fn dry_run_wap() { const ANNA: u32 = 64; const DAMIAN: u32 = 65; - let accounts = vec![ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN]; + let accounts = [ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN]; let bounded_name = bounded_name(); let bounded_symbol = bounded_symbol(); @@ -58,12 +58,12 @@ fn dry_run_wap() { // overfund with plmc let plmc_fundings = accounts .iter() - .map(|acc| UserToPLMCBalance { account: acc.clone(), plmc_amount: PLMC * 1_000_000 }) + .map(|acc| UserToPLMCBalance { account: *acc, plmc_amount: PLMC * 1_000_000 }) .collect_vec(); let usdt_fundings = accounts .iter() .map(|acc| UserToFundingAsset { - account: acc.clone(), + account: *acc, asset_amount: USD_UNIT * 1_000_000, asset_id: AcceptedFundingAsset::USDT.id(), }) @@ -106,7 +106,7 @@ fn find_bucket_for_wap() { const ANNA: u32 = 64; const DAMIAN: u32 = 65; - let accounts = vec![ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN]; + let accounts = [ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN]; let bounded_name = bounded_name(); let bounded_symbol = bounded_symbol(); @@ -140,12 +140,12 @@ fn find_bucket_for_wap() { // overfund with plmc let plmc_fundings = accounts .iter() - .map(|acc| UserToPLMCBalance { account: acc.clone(), plmc_amount: PLMC * 1_000_000 }) + .map(|acc| UserToPLMCBalance { account: *acc, plmc_amount: PLMC * 1_000_000 }) .collect_vec(); let usdt_fundings = accounts .iter() .map(|acc| UserToFundingAsset { - account: acc.clone(), + account: *acc, asset_amount: USD_UNIT * 1_000_000, asset_id: AcceptedFundingAsset::USDT.id(), }) diff --git a/pallets/funding/src/instantiator/types.rs b/pallets/funding/src/instantiator/types.rs index ab219e4c1..96eddbc3c 100644 --- a/pallets/funding/src/instantiator/types.rs +++ b/pallets/funding/src/instantiator/types.rs @@ -205,7 +205,7 @@ impl AccountMerge for Vec> { let mut btree = BTreeMap::new(); for UserToFundingAsset { account, asset_amount, asset_id } in self.iter() { btree - .entry((account.clone(), asset_id.clone())) + .entry((account.clone(), asset_id)) .and_modify(|e: &mut BalanceOf| { *e = match ops { MergeOperation::Add => e.saturating_add(*asset_amount), @@ -216,7 +216,7 @@ impl AccountMerge for Vec> { } btree .into_iter() - .map(|((account, asset_id), asset_amount)| UserToFundingAsset::new(account, asset_amount, asset_id)) + .map(|((account, asset_id), asset_amount)| UserToFundingAsset::new(account, asset_amount, *asset_id)) .collect() } diff --git a/pallets/funding/src/runtime_api.rs b/pallets/funding/src/runtime_api.rs index 61edaa376..68edfdb71 100644 --- a/pallets/funding/src/runtime_api.rs +++ b/pallets/funding/src/runtime_api.rs @@ -198,17 +198,14 @@ impl Pallet { map.entry(account_id).or_insert_with(|| (Vec::new(), Vec::new(), Vec::new())).2.push(contribution_id); } - let output = map - .into_iter() + map.into_iter() .map(|(account, (evaluation_ids, bid_ids, contribution_ids))| ProjectParticipationIds { account, evaluation_ids, bid_ids, contribution_ids, }) - .collect(); - - output + .collect() } pub fn usd_target_percent_reached(project_id: ProjectId) -> FixedU128 { diff --git a/pallets/funding/src/tests/1_application.rs b/pallets/funding/src/tests/1_application.rs index 094ae0f48..747fc11f6 100644 --- a/pallets/funding/src/tests/1_application.rs +++ b/pallets/funding/src/tests/1_application.rs @@ -825,7 +825,7 @@ mod edit_project_extrinsic { project_id, project_metadata.clone() ))); - let next_project_id = inst.execute(|| NextProjectId::::get()); + let next_project_id = inst.execute(NextProjectId::::get); assert_eq!(project_id, next_project_id - 1); let projects_details = inst.execute(|| ProjectsDetails::::iter_keys().collect_vec()); let project_metadatas = inst.execute(|| ProjectsMetadata::::iter_keys().collect_vec()); diff --git a/pallets/funding/src/tests/2_evaluation.rs b/pallets/funding/src/tests/2_evaluation.rs index 4b3b1f3f7..59b4fd8f3 100644 --- a/pallets/funding/src/tests/2_evaluation.rs +++ b/pallets/funding/src/tests/2_evaluation.rs @@ -123,7 +123,7 @@ mod round_flow { let issuer: AccountIdOf = (10_000 + inst.get_new_nonce()).try_into().unwrap(); let project_id = inst.create_evaluating_project(project_metadata.clone(), issuer, None); - let evaluation_threshold = inst.execute(|| ::EvaluationSuccessThreshold::get()); + let evaluation_threshold = inst.execute(::EvaluationSuccessThreshold::get); let evaluation_threshold_ct = evaluation_threshold * project_metadata.total_allocation_size; evaluation_ct_thresholds.push(evaluation_threshold_ct); @@ -662,7 +662,7 @@ mod evaluate_extrinsic { let evaluation_held_balance = inst.get_reserved_plmc_balance_for(EVALUATOR_4, HoldReason::Evaluation(project_id).into()); let frozen_balance = inst.execute(|| mock::Balances::balance_frozen(&(), &EVALUATOR_4)); - let account_data = inst.execute(|| System::account(&EVALUATOR_4)).data; + let account_data = inst.execute(|| System::account(EVALUATOR_4)).data; let post_slash_evaluation_plmc = frozen_amount - (::EvaluatorSlash::get() * frozen_amount); @@ -747,8 +747,7 @@ mod evaluate_extrinsic { let evaluating_plmc = inst.calculate_evaluation_plmc_spent(evaluations.clone(), false); let mut plmc_insufficient_existential_deposit = evaluating_plmc.accounts().existential_deposits(); - plmc_insufficient_existential_deposit[0].plmc_amount = - plmc_insufficient_existential_deposit[0].plmc_amount / 2; + plmc_insufficient_existential_deposit[0].plmc_amount /= 2; inst.mint_plmc_to(evaluating_plmc); inst.mint_plmc_to(plmc_insufficient_existential_deposit); @@ -764,7 +763,7 @@ mod evaluate_extrinsic { let mut inst = MockInstantiator::new(Some(RefCell::new(new_test_ext()))); let project_metadata = default_project_metadata(ISSUER_1); let evaluations = (0u32..::MaxEvaluationsPerProject::get()) - .map(|i| UserToUSDBalance::::new(i as u32 + 420u32, (100u128 * CT_UNIT).into())) + .map(|i| UserToUSDBalance::::new(i + 420u32, (100u128 * CT_UNIT))) .collect_vec(); let failing_evaluation = UserToUSDBalance::new(EVALUATOR_1, 1000 * CT_UNIT); @@ -792,7 +791,7 @@ mod evaluate_extrinsic { let mut inst = MockInstantiator::new(Some(RefCell::new(new_test_ext()))); let project_metadata = default_project_metadata(ISSUER_1); let evaluations = (0u32..::MaxEvaluationsPerUser::get()) - .map(|_| UserToUSDBalance::::new(EVALUATOR_1, (100u128 * USD_UNIT).into())) + .map(|_| UserToUSDBalance::::new(EVALUATOR_1, (100u128 * USD_UNIT))) .collect_vec(); let failing_evaluation = UserToUSDBalance::new(EVALUATOR_1, 100 * USD_UNIT); @@ -933,13 +932,13 @@ mod evaluate_extrinsic { project_metadata.clone().policy_ipfs_cid.unwrap(), ); - inst.mint_plmc_to(vec![(evaluator.clone(), 2000 * PLMC).into()]); + inst.mint_plmc_to(vec![(evaluator, 2000 * PLMC).into()]); // Cannot evaluate with 0 USD inst.execute(|| { assert_noop!( Pallet::::evaluate( - RuntimeOrigin::signed(evaluator.clone()), + RuntimeOrigin::signed(evaluator), jwt.clone(), project_id, 0 @@ -952,7 +951,7 @@ mod evaluate_extrinsic { inst.execute(|| { assert_noop!( Pallet::::evaluate( - RuntimeOrigin::signed(evaluator.clone()), + RuntimeOrigin::signed(evaluator), jwt.clone(), project_id, 99 * USD_UNIT diff --git a/pallets/funding/src/tests/3_auction.rs b/pallets/funding/src/tests/3_auction.rs index 4703b3168..acee8f830 100644 --- a/pallets/funding/src/tests/3_auction.rs +++ b/pallets/funding/src/tests/3_auction.rs @@ -508,7 +508,7 @@ mod bid_extrinsic { ) -> DispatchResultWithPostInfo { let project_policy = inst.get_project_metadata(project_id).policy_ipfs_cid.unwrap(); let jwt = get_mock_jwt_with_cid( - bidder.clone(), + bidder, investor_type, generate_did_from_account(BIDDER_1), project_policy, @@ -518,7 +518,7 @@ mod bid_extrinsic { if u8_multiplier > 0 { let bid = BidParams:: { - bidder: bidder.clone(), + bidder: bidder, amount, multiplier, asset: AcceptedFundingAsset::USDT, @@ -1020,7 +1020,7 @@ mod bid_extrinsic { inst.generate_successful_evaluations(project_metadata.clone(), vec![EVALUATOR_1], vec![100u8]); let max_bids_per_project: u32 = ::MaxBidsPerProject::get(); let bids = - (0u32..max_bids_per_project - 1).map(|i| (i as u32 + 420u32, 5000 * CT_UNIT).into()).collect_vec(); + (0u32..max_bids_per_project - 1).map(|i| (i + 420u32, 5000 * CT_UNIT).into()).collect_vec(); let project_id = inst.create_auctioning_project(project_metadata.clone(), ISSUER_1, None, evaluations); @@ -1586,7 +1586,7 @@ mod end_auction_extrinsic { const ANNA: u32 = 64; const DAMIAN: u32 = 65; - let accounts = vec![ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN]; + let accounts = [ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN]; let bounded_name = bounded_name(); let bounded_symbol = bounded_symbol(); @@ -1627,12 +1627,12 @@ mod end_auction_extrinsic { // overfund with plmc let plmc_fundings = accounts .iter() - .map(|acc| UserToPLMCBalance { account: acc.clone(), plmc_amount: PLMC * 1_000_000 }) + .map(|acc| UserToPLMCBalance { account: *acc, plmc_amount: PLMC * 1_000_000 }) .collect_vec(); let usdt_fundings = accounts .iter() .map(|acc| UserToFundingAsset { - account: acc.clone(), + account: *acc, asset_amount: USD_UNIT * 1_000_000, asset_id: AcceptedFundingAsset::USDT.id(), }) @@ -1815,7 +1815,7 @@ mod end_auction_extrinsic { const ANNA: u32 = 64; const DAMIAN: u32 = 65; - let accounts = vec![ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN]; + let accounts = [ADAM, TOM, SOFIA, FRED, ANNA, DAMIAN]; let mut project_metadata = default_project_metadata(ISSUER_1); project_metadata.total_allocation_size = 100_000 * CT_UNIT; project_metadata.participation_currencies = @@ -1824,7 +1824,7 @@ mod end_auction_extrinsic { // overfund with plmc let plmc_fundings = accounts .iter() - .map(|acc| UserToPLMCBalance { account: acc.clone(), plmc_amount: PLMC * 1_000_000 }) + .map(|acc| UserToPLMCBalance { account: *acc, plmc_amount: PLMC * 1_000_000 }) .collect_vec(); let fundings = [AcceptedFundingAsset::USDT, AcceptedFundingAsset::USDC, AcceptedFundingAsset::DOT]; @@ -1838,7 +1838,7 @@ mod end_auction_extrinsic { let asset_id = accepted_asset.id(); let asset_decimals = inst.execute(|| ::FundingCurrency::decimals(asset_id)); let asset_unit = 10u128.checked_pow(asset_decimals.into()).unwrap(); - UserToFundingAsset { account: acc.clone(), asset_amount: asset_unit * 1_000_000, asset_id } + UserToFundingAsset { account: *acc, asset_amount: asset_unit * 1_000_000, asset_id } }) .collect_vec(); inst.mint_plmc_to(plmc_fundings); diff --git a/pallets/funding/src/tests/4_contribution.rs b/pallets/funding/src/tests/4_contribution.rs index 67c003c71..0895f38b3 100644 --- a/pallets/funding/src/tests/4_contribution.rs +++ b/pallets/funding/src/tests/4_contribution.rs @@ -478,7 +478,7 @@ mod contribute_extrinsic { bids_plmc.remove(2); inst.mint_plmc_to(bids_plmc.clone()); - assert_eq!(inst.execute(|| Balances::free_balance(&bob)), inst.get_ed()); + assert_eq!(inst.execute(|| Balances::free_balance(bob)), inst.get_ed()); let bids_funding_assets = inst.calculate_auction_funding_asset_charged_from_all_bids_made_or_with_bucket( &bids, @@ -488,7 +488,7 @@ mod contribute_extrinsic { inst.mint_funding_asset_to(bids_funding_assets.clone()); inst.bid_for_users(project_id, bids).unwrap(); - assert_eq!(inst.execute(|| Balances::free_balance(&bob)), inst.get_ed()); + assert_eq!(inst.execute(|| Balances::free_balance(bob)), inst.get_ed()); assert!(matches!(inst.go_to_next_state(project_id), ProjectStatus::CommunityRound(..))); @@ -496,7 +496,7 @@ mod contribute_extrinsic { inst.execute(|| { PolimecFunding::settle_bid(RuntimeOrigin::signed(bob), project_id, bob, 1).unwrap(); }); - let bob_plmc = inst.execute(|| Balances::free_balance(&bob)); + let bob_plmc = inst.execute(|| Balances::free_balance(bob)); assert_close_enough!(bob_plmc, inst.get_ed() + usable_bond, Perquintill::from_float(0.9999)); // Calculate how much CTs can bob buy with his evaluation PLMC bond @@ -527,7 +527,7 @@ mod contribute_extrinsic { // Check he had no free PLMC assert_close_enough!( - inst.execute(|| Balances::free_balance(&bob)), + inst.execute(|| Balances::free_balance(bob)), inst.get_ed(), Perquintill::from_float(0.999) ); @@ -587,7 +587,7 @@ mod contribute_extrinsic { ) -> DispatchResultWithPostInfo { let project_policy = inst.get_project_metadata(project_id).policy_ipfs_cid.unwrap(); let jwt = get_mock_jwt_with_cid( - contributor.clone(), + contributor, investor_type, generate_did_from_account(contributor), project_policy, @@ -598,7 +598,7 @@ mod contribute_extrinsic { if u8_multiplier > 0 { let contribution = ContributionParams:: { - contributor: contributor.clone(), + contributor: contributor, amount, multiplier, asset: AcceptedFundingAsset::USDT, @@ -1078,7 +1078,7 @@ mod contribute_extrinsic { let plmc_bond_stored = inst.execute(|| { ::NativeCurrency::balance_on_hold( - &HoldReason::Participation(project_id.into()).into(), + &HoldReason::Participation(project_id).into(), &CONTRIBUTOR, ) }); diff --git a/pallets/funding/src/tests/6_settlement.rs b/pallets/funding/src/tests/6_settlement.rs index 83b640c6d..fe89167b6 100644 --- a/pallets/funding/src/tests/6_settlement.rs +++ b/pallets/funding/src/tests/6_settlement.rs @@ -68,7 +68,7 @@ mod start_settlement_extrinsic { assert_eq!(project_details.funding_end_block, None); assert_eq!(project_details.status, ProjectStatus::FundingSuccessful); inst.execute(|| { - assert_eq!(::ContributionTokenCurrency::asset_exists(project_id), false) + assert!(!::ContributionTokenCurrency::asset_exists(project_id)) }); inst.advance_time(::SuccessToSettlementTime::get()); @@ -80,7 +80,7 @@ mod start_settlement_extrinsic { assert_eq!(project_details.funding_end_block, Some(inst.current_block())); assert_eq!(project_details.status, ProjectStatus::SettlementStarted(FundingOutcome::Success)); inst.execute(|| { - assert_eq!(::ContributionTokenCurrency::asset_exists(project_id), true) + assert!(::ContributionTokenCurrency::asset_exists(project_id)) }); inst.assert_ct_balance(project_id, ct_treasury, treasury_allocation); @@ -94,7 +94,7 @@ mod start_settlement_extrinsic { assert_eq!(project_details.funding_end_block, None); assert_eq!(project_details.status, ProjectStatus::FundingFailed); inst.execute(|| { - assert_eq!(::ContributionTokenCurrency::asset_exists(project_id), false) + assert!(!::ContributionTokenCurrency::asset_exists(project_id)) }); inst.advance_time(::SuccessToSettlementTime::get()); @@ -106,7 +106,7 @@ mod start_settlement_extrinsic { assert_eq!(project_details.funding_end_block, Some(inst.current_block())); assert_eq!(project_details.status, ProjectStatus::SettlementStarted(FundingOutcome::Failure)); inst.execute(|| { - assert_eq!(::ContributionTokenCurrency::asset_exists(project_id), false) + assert!(!::ContributionTokenCurrency::asset_exists(project_id)) }); } } @@ -240,9 +240,9 @@ mod settle_evaluation_extrinsic { // Evaluation 2 Total reward = Evaluation 2 Early reward + Evaluation 2 Normal reward = 1_080 + 4_033 = 5'117.383177570093458 CT // Evaluation 3 Total reward = Evaluation 3 Early reward + Evaluation 3 Normal reward = 1_080 + 5_201 = 6'247.850467289719626 CT - const EVAL_1_REWARD: u128 = 10_234_766355140186916; - const EVAL_2_REWARD: u128 = 5_117_383177570093458; - const EVAL_3_REWARD: u128 = 6_247_850467289719626; + const EVAL_1_REWARD: u128 = 10_234_766_355_140_186_916; + const EVAL_2_REWARD: u128 = 5_117_383_177_570_093_458; + const EVAL_3_REWARD: u128 = 6_247_850_467_289_719_626; let prev_ct_balances = inst.get_ct_asset_balances_for(project_id, vec![ISSUER_1, ISSUER_2, ISSUER_3]); assert!(prev_ct_balances.iter().all(|x| *x == Zero::zero())); diff --git a/pallets/funding/src/tests/7_ct_migration.rs b/pallets/funding/src/tests/7_ct_migration.rs index 789644d6d..eb75c47b6 100644 --- a/pallets/funding/src/tests/7_ct_migration.rs +++ b/pallets/funding/src/tests/7_ct_migration.rs @@ -41,7 +41,7 @@ mod pallet_migration { assert_ok!(crate::Pallet::::do_start_pallet_migration( &ISSUER_1, project_id, - ParaId::from(2006u32).into(), + ParaId::from(2006u32), )); }); @@ -105,7 +105,7 @@ mod pallet_migration { let inst = MockInstantiator::new(Some(RefCell::new(new_test_ext()))); let (project_id, mut inst) = create_pallet_migration_project(inst); - inst.execute(|| fake_hrmp_establishment()); + inst.execute(fake_hrmp_establishment); let project_details = inst.get_project_details(project_id); assert_eq!( @@ -130,7 +130,7 @@ mod pallet_migration { fn pallet_readiness_check() { let inst = MockInstantiator::new(Some(RefCell::new(new_test_ext()))); let (project_id, mut inst) = create_pallet_migration_project(inst); - inst.execute(|| fake_hrmp_establishment()); + inst.execute(fake_hrmp_establishment); // At this point, we sent the pallet check xcm to the project chain, and we are awaiting a query response message. // query id 0 is the CT balance of the Polimec SA diff --git a/pallets/funding/src/tests/misc.rs b/pallets/funding/src/tests/misc.rs index a7550667d..2d1454c0b 100644 --- a/pallets/funding/src/tests/misc.rs +++ b/pallets/funding/src/tests/misc.rs @@ -249,33 +249,33 @@ mod helper_functions { const CONTRIBUTOR_1: AccountIdOf = 1u32; const TOKEN_AMOUNT_1: u128 = 120 * CT_UNIT; const MULTIPLIER_1: u8 = 1u8; - const _TICKET_SIZE_USD_1: u128 = 1_958_4_000_000_000_u128; - const EXPECTED_PLMC_AMOUNT_1: f64 = 233.1_428_571_428f64; + const _TICKET_SIZE_USD_1: u128 = 19_584_000_000_000_u128; + const EXPECTED_PLMC_AMOUNT_1: f64 = 233.142_857_142_8_f64; const CONTRIBUTOR_2: AccountIdOf = 2u32; const TOKEN_AMOUNT_2: u128 = 5023 * CT_UNIT; const MULTIPLIER_2: u8 = 2u8; - const _TICKET_SIZE_USD_2: u128 = 81_975_3_600_000_000_u128; - const EXPECTED_PLMC_AMOUNT_2: f64 = 4_879.4_857_142_857f64; + const _TICKET_SIZE_USD_2: u128 = 819_753_600_000_000_u128; + const EXPECTED_PLMC_AMOUNT_2: f64 = 4_879.485_714_285_7_f64; const CONTRIBUTOR_3: AccountIdOf = 3u32; const TOKEN_AMOUNT_3: u128 = 20_000 * CT_UNIT; const MULTIPLIER_3: u8 = 17u8; - const _TICKET_SIZE_USD_3: u128 = 326_400_0_000_000_000_u128; - const EXPECTED_PLMC_AMOUNT_3: f64 = 2_285.7_142_857_142f64; + const _TICKET_SIZE_USD_3: u128 = 3_264_000_000_000_000_u128; + const EXPECTED_PLMC_AMOUNT_3: f64 = 2_285.714_285_714_2_f64; const CONTRIBUTOR_4: AccountIdOf = 4u32; const TOKEN_AMOUNT_4: u128 = 1_000_000 * CT_UNIT; const MULTIPLIER_4: u8 = 25u8; - const _TICKET_SIZE_4: u128 = 16_320_000_0_000_000_000_u128; - const EXPECTED_PLMC_AMOUNT_4: f64 = 77_714.2_857_142_857f64; + const _TICKET_SIZE_4: u128 = 163_200_000_000_000_000_u128; + const EXPECTED_PLMC_AMOUNT_4: f64 = 77_714.285_714_285_7_f64; const CONTRIBUTOR_5: AccountIdOf = 5u32; // 0.1233 CTs const TOKEN_AMOUNT_5: u128 = 1_233 * CT_UNIT / 10_000; const MULTIPLIER_5: u8 = 10u8; - const _TICKET_SIZE_5: u128 = 2_0_122_562_000_u128; - const EXPECTED_PLMC_AMOUNT_5: f64 = 0.0_239_554_285f64; + const _TICKET_SIZE_5: u128 = 20_122_562_000_u128; + const EXPECTED_PLMC_AMOUNT_5: f64 = 0.023_955_428_5_f64; assert_eq!( ::PriceProvider::get_price(PLMC_FOREIGN_ID).unwrap(), @@ -381,7 +381,7 @@ fn project_state_transition_event() { true, ); - let events = inst.execute(|| System::events()); + let events = inst.execute(System::events); let transition_events = events .into_iter() .filter_map(|event| { diff --git a/pallets/funding/src/tests/mod.rs b/pallets/funding/src/tests/mod.rs index 837d9dca5..13a66805e 100644 --- a/pallets/funding/src/tests/mod.rs +++ b/pallets/funding/src/tests/mod.rs @@ -123,7 +123,8 @@ pub mod defaults { CT_DECIMALS, ) .unwrap(); - let project_metadata = ProjectMetadataOf:: { + + ProjectMetadataOf:: { token_information: CurrencyMetadata { name: bounded_name, symbol: bounded_symbol, decimals: CT_DECIMALS }, mainnet_token_max_supply: 8_000_000 * CT_UNIT, total_allocation_size: 100_000 * CT_UNIT, @@ -143,8 +144,7 @@ pub mod defaults { participation_currencies: vec![AcceptedFundingAsset::USDT].try_into().unwrap(), funding_destination_account: ISSUER_1, policy_ipfs_cid: Some(metadata_hash), - }; - project_metadata + } } pub fn default_plmc_balances() -> Vec> { diff --git a/pallets/funding/src/tests/runtime_api.rs b/pallets/funding/src/tests/runtime_api.rs index e0c20bc45..b3bb4780d 100644 --- a/pallets/funding/src/tests/runtime_api.rs +++ b/pallets/funding/src/tests/runtime_api.rs @@ -310,7 +310,7 @@ fn contribution_tokens() { inst.execute(|| { let block_hash = System::block_hash(System::block_number()); - let bob_items = TestRuntime::contribution_tokens(&TestRuntime, block_hash, bob.clone()).unwrap(); + let bob_items = TestRuntime::contribution_tokens(&TestRuntime, block_hash, bob).unwrap(); assert_eq!(bob_items, expected_items); }); } @@ -326,7 +326,7 @@ fn funding_asset_to_ct_amount() { PriceOf::::from_float(69.0f64) ); - let dot_amount: u128 = 1350_0_000_000_000; + let dot_amount: u128 = 13_500_000_000_000; // USD Ticket = 93_150 USD // Easy case, wap is already calculated, we want to know how many tokens at wap we can buy with `x` USDT @@ -432,7 +432,7 @@ fn funding_asset_to_ct_amount() { dbg!(current_bucket.current_price.saturating_mul_int(current_bucket.amount_left)); - let dot_amount: u128 = 217_0_000_000_000; + let dot_amount: u128 = 2_170_000_000_000; let expected_ct_amount: u128 = 935_812_500_000_000_000; inst.execute(|| { @@ -454,7 +454,7 @@ fn funding_asset_to_ct_amount() { // We need to buy 50k at 16 , 50k at 17, and 13.5k at 18 = 1893k USD // Amount needed to spend 1893k USD through several buckets with DOT at 69 USD/DOT - let dot_amount = 27_434_7_826_086_956u128; + let dot_amount = 274_347_826_086_956_u128; let expected_ct_amount = 113_500 * CT_UNIT; inst.execute(|| { @@ -511,12 +511,12 @@ fn all_project_participations_by_did() { ); let community_contributions_plmc = inst.calculate_contributed_plmc_spent( community_contributions.clone(), - project_metadata.minimum_price.clone(), + project_metadata.minimum_price, true, ); let remainder_contributions_plmc = inst.calculate_contributed_plmc_spent( remainder_contributions.clone(), - project_metadata.minimum_price.clone(), + project_metadata.minimum_price, true, ); let all_plmc = inst.generic_map_operation( @@ -532,11 +532,11 @@ fn all_project_participations_by_did() { ); let community_contributions_usdt = inst.calculate_contributed_funding_asset_spent( community_contributions.clone(), - project_metadata.minimum_price.clone(), + project_metadata.minimum_price, ); let remainder_contributions_usdt = inst.calculate_contributed_funding_asset_spent( remainder_contributions.clone(), - project_metadata.minimum_price.clone(), + project_metadata.minimum_price, ); let all_usdt = inst.generic_map_operation( vec![bids_usdt, community_contributions_usdt, remainder_contributions_usdt], diff --git a/pallets/funding/src/types.rs b/pallets/funding/src/types.rs index 30159362b..07ea79fde 100644 --- a/pallets/funding/src/types.rs +++ b/pallets/funding/src/types.rs @@ -111,9 +111,9 @@ pub mod config_types { } } - impl Into for Multiplier { - fn into(self) -> u8 { - self.0 + impl From for u8 { + fn from(val: Multiplier) -> Self { + val.0 } } @@ -504,12 +504,12 @@ pub mod storage_types { let sum = bucket_sizes.iter().map(|x| x.0).fold(Balance::zero(), |acc, x| acc.saturating_add(x)); - let wap = bucket_sizes + + + bucket_sizes .into_iter() .map(|x| ::saturating_from_rational(x.0, sum).saturating_mul(x.1)) - .fold(Price::zero(), |acc: Price, p: Price| acc.saturating_add(p)); - - return wap + .fold(Price::zero(), |acc: Price, p: Price| acc.saturating_add(p)) } } } diff --git a/pallets/oracle-ocw/src/lib.rs b/pallets/oracle-ocw/src/lib.rs index c39de5abc..354af1394 100644 --- a/pallets/oracle-ocw/src/lib.rs +++ b/pallets/oracle-ocw/src/lib.rs @@ -27,7 +27,7 @@ use core::ops::Rem; use frame_system::offchain::{AppCrypto, CreateSignedTransaction, SendSignedTransaction, Signer}; pub use pallet::*; use sp_runtime::{ - traits::{Convert, Saturating, Zero}, + traits::{Convert, Saturating}, FixedU128, RuntimeAppPublic, }; use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec}; @@ -152,9 +152,8 @@ pub mod pallet { ]), }; // Fix for missing PLMC in last_send_for_assets for old nodes, that did not have PLMC in the list. - if !last_send_for_assets.contains_key(&AssetName::PLMC) { - last_send_for_assets.insert(AssetName::PLMC, Zero::zero()); - }; + last_send_for_assets.entry(AssetName::PLMC).or_insert_with(Zero::zero); + let assets = last_send_for_assets .iter() .filter_map(|(asset_name, last_send)| { @@ -254,11 +253,11 @@ pub mod pallet { match result { Some((_, Ok(_))) => { log::trace!(target: LOG_TARGET, "offchain tx sent successfully"); - return Ok(()); + Ok(()) }, _ => { log::trace!(target: LOG_TARGET, "failure: offchain_signed_tx"); - return Err(()); + Err(()) }, } } diff --git a/pallets/oracle-ocw/src/mock.rs b/pallets/oracle-ocw/src/mock.rs index 6b0f701f4..e0168330d 100644 --- a/pallets/oracle-ocw/src/mock.rs +++ b/pallets/oracle-ocw/src/mock.rs @@ -170,7 +170,7 @@ pub fn new_test_ext_with_offchain_storage( // let (pool, pool_state) = testing::TestTransactionPoolExt::new(); let (pool, pool_state) = testing::TestTransactionPoolExt::new(); let keystore = MemoryKeystore::new(); - keystore.sr25519_generate_new(crate::crypto::POLIMEC_ORACLE, Some(&format!("{}", PHRASE))).unwrap(); + keystore.sr25519_generate_new(crate::crypto::POLIMEC_ORACLE, Some(&PHRASE.to_string())).unwrap(); let storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); let mut t: sp_io::TestExternalities = storage.into(); @@ -185,7 +185,7 @@ pub fn price_oracle_response(state: &mut testing::OffchainState) { for (asset, response) in KRAKEN_RESPONSES.iter() { state.expect_request(testing::PendingRequest { method: "GET".into(), - uri: format!("https://api.kraken.com/0/public/OHLC?pair={}&interval=1", asset).into(), + uri: format!("https://api.kraken.com/0/public/OHLC?pair={}&interval=1", asset), response: Some(response.to_vec()), sent: true, ..Default::default() @@ -195,7 +195,7 @@ pub fn price_oracle_response(state: &mut testing::OffchainState) { for (asset, response) in BITFINEX_RESPONSES.iter() { state.expect_request(testing::PendingRequest { method: "GET".into(), - uri: format!("https://api-pub.bitfinex.com/v2/candles/trade%3A1m%3At{}/hist?limit=15", asset).into(), + uri: format!("https://api-pub.bitfinex.com/v2/candles/trade%3A1m%3At{}/hist?limit=15", asset), response: Some(response.to_vec()), sent: true, ..Default::default() @@ -204,7 +204,7 @@ pub fn price_oracle_response(state: &mut testing::OffchainState) { for (asset, response) in BITSTAMP_RESPONSES.iter() { state.expect_request(testing::PendingRequest { method: "GET".into(), - uri: format!("https://www.bitstamp.net/api/v2/ohlc/{}/?step=60&limit=15", asset).into(), + uri: format!("https://www.bitstamp.net/api/v2/ohlc/{}/?step=60&limit=15", asset), response: Some(response.to_vec()), sent: true, ..Default::default() @@ -213,7 +213,7 @@ pub fn price_oracle_response(state: &mut testing::OffchainState) { for (asset, response) in COINBASE_RESPONSES.iter() { state.expect_request(testing::PendingRequest { method: "GET".into(), - uri: format!("https://api.exchange.coinbase.com/products/{}/candles?granularity=60", asset).into(), + uri: format!("https://api.exchange.coinbase.com/products/{}/candles?granularity=60", asset), response: Some(response.to_vec()), sent: true, ..Default::default() diff --git a/pallets/oracle-ocw/src/tests.rs b/pallets/oracle-ocw/src/tests.rs index f5802bbd0..168447fee 100644 --- a/pallets/oracle-ocw/src/tests.rs +++ b/pallets/oracle-ocw/src/tests.rs @@ -40,10 +40,10 @@ fn call_offchain_worker() { RuntimeCall::Oracle(orml_oracle::Call::feed_values { values }) => for (asset, price) in values { match asset { - 0 => assert_close_enough(price, FixedU128::from_float(6.138485575453039783)), - 1984 => assert_close_enough(price, FixedU128::from_float(1.000154206100002620)), - 1337 => assert_close_enough(price, FixedU128::from_float(1.000093378020633965)), - 3344 => assert_close_enough(price, FixedU128::from_float(0.414564170729477207)), + 0 => assert_close_enough(price, FixedU128::from_float(6.138_485_575_453_04)), + 1984 => assert_close_enough(price, FixedU128::from_float(1.000_154_206_100_002_6)), + 1337 => assert_close_enough(price, FixedU128::from_float(1.000_093_378_020_634)), + 3344 => assert_close_enough(price, FixedU128::from_float(0.414_564_170_729_477_2)), _ => panic!("Unexpected asset"), } }, @@ -53,9 +53,9 @@ fn call_offchain_worker() { } fn test_fetcher_against_real_api() { - for asset in vec![AssetName::DOT, AssetName::USDC, AssetName::USDT, AssetName::PLMC] { + for asset in [AssetName::DOT, AssetName::USDC, AssetName::USDT, AssetName::PLMC] { let url = F::get_url(asset); - if url == "" { + if url.is_empty() { continue; } let body = do_request(url); diff --git a/pallets/oracle-ocw/src/traits.rs b/pallets/oracle-ocw/src/traits.rs index 708d3b19e..d3bead1ed 100644 --- a/pallets/oracle-ocw/src/traits.rs +++ b/pallets/oracle-ocw/src/traits.rs @@ -13,13 +13,13 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use super::*; - +use crate::{AssetName, AssetRequest, OpenCloseVolume}; use sp_runtime::{ offchain::{ http::{self, PendingRequest}, Duration, }, + traits::Zero, FixedU128, Saturating, }; diff --git a/pallets/parachain-staking/src/auto_compound.rs b/pallets/parachain-staking/src/auto_compound.rs index 900df941c..32b8525fe 100644 --- a/pallets/parachain-staking/src/auto_compound.rs +++ b/pallets/parachain-staking/src/auto_compound.rs @@ -290,7 +290,7 @@ mod tests { #[test] fn test_set_for_delegator_inserts_config_and_returns_true_if_entry_missing() { let mut delegations_config = AutoCompoundDelegations::::new(vec![].try_into().expect("must succeed")); - assert_eq!(true, delegations_config.set_for_delegator(1, Percent::from_percent(50)).expect("must succeed")); + assert!(delegations_config.set_for_delegator(1, Percent::from_percent(50)).expect("must succeed")); assert_eq!( vec![AutoCompoundConfig { delegator: 1, value: Percent::from_percent(50) }], delegations_config.into_inner().into_inner(), @@ -304,7 +304,7 @@ mod tests { .try_into() .expect("must succeed"), ); - assert_eq!(true, delegations_config.set_for_delegator(1, Percent::from_percent(50)).expect("must succeed")); + assert!(delegations_config.set_for_delegator(1, Percent::from_percent(50)).expect("must succeed")); assert_eq!( vec![AutoCompoundConfig { delegator: 1, value: Percent::from_percent(50) }], delegations_config.into_inner().into_inner(), @@ -318,7 +318,7 @@ mod tests { .try_into() .expect("must succeed"), ); - assert_eq!(false, delegations_config.set_for_delegator(1, Percent::from_percent(10)).expect("must succeed")); + assert!(!delegations_config.set_for_delegator(1, Percent::from_percent(10)).expect("must succeed")); assert_eq!( vec![AutoCompoundConfig { delegator: 1, value: Percent::from_percent(10) }], delegations_config.into_inner().into_inner(), @@ -328,7 +328,7 @@ mod tests { #[test] fn test_remove_for_delegator_returns_false_if_entry_was_missing() { let mut delegations_config = AutoCompoundDelegations::::new(vec![].try_into().expect("must succeed")); - assert_eq!(false, delegations_config.remove_for_delegator(&1),); + assert!(!delegations_config.remove_for_delegator(&1),); } #[test] @@ -338,6 +338,6 @@ mod tests { .try_into() .expect("must succeed"), ); - assert_eq!(true, delegations_config.remove_for_delegator(&1)); + assert!(delegations_config.remove_for_delegator(&1)); } } diff --git a/pallets/parachain-staking/src/inflation.rs b/pallets/parachain-staking/src/inflation.rs index 62c5fabc5..495ab382c 100644 --- a/pallets/parachain-staking/src/inflation.rs +++ b/pallets/parachain-staking/src/inflation.rs @@ -169,9 +169,9 @@ mod tests { }; mock_round_issuance_range(u32::MAX.into(), mock_annual_to_round(schedule, u32::MAX)); mock_round_issuance_range(u64::MAX.into(), mock_annual_to_round(schedule, u32::MAX)); - mock_round_issuance_range(u128::MAX.into(), mock_annual_to_round(schedule, u32::MAX)); + mock_round_issuance_range(u128::MAX, mock_annual_to_round(schedule, u32::MAX)); mock_round_issuance_range(u32::MAX.into(), mock_annual_to_round(schedule, 1)); mock_round_issuance_range(u64::MAX.into(), mock_annual_to_round(schedule, 1)); - mock_round_issuance_range(u128::MAX.into(), mock_annual_to_round(schedule, 1)); + mock_round_issuance_range(u128::MAX, mock_annual_to_round(schedule, 1)); } } diff --git a/pallets/parachain-staking/src/mock.rs b/pallets/parachain-staking/src/mock.rs index 4b0570b36..376bd218b 100644 --- a/pallets/parachain-staking/src/mock.rs +++ b/pallets/parachain-staking/src/mock.rs @@ -25,7 +25,7 @@ use frame_support::{ weights::{constants::RocksDbWeight, Weight}, }; use frame_system::pallet_prelude::BlockNumberFor; -use sp_io; + use sp_runtime::{traits::IdentityLookup, BuildStorage, Perbill, Percent}; pub type AccountId = u64; @@ -349,7 +349,7 @@ pub(crate) fn events() -> Vec> { #[macro_export] macro_rules! assert_no_events { () => { - similar_asserts::assert_eq!(Vec::>::new(), crate::mock::events()) + similar_asserts::assert_eq!(Vec::>::new(), $crate::mock::events()) }; } @@ -367,7 +367,7 @@ macro_rules! assert_no_events { #[macro_export] macro_rules! assert_events_eq { ($event:expr) => { - similar_asserts::assert_eq!(vec![$event], crate::mock::events()); + similar_asserts::assert_eq!(vec![$event], $crate::mock::events()); }; ($($events:expr,)+) => { similar_asserts::assert_eq!(vec![$($events,)+], crate::mock::events()); @@ -388,7 +388,7 @@ macro_rules! assert_events_eq { macro_rules! assert_events_emitted { ($event:expr) => { [$event].into_iter().for_each(|e| assert!( - crate::mock::events().into_iter().find(|x| x == &e).is_some(), + $crate::mock::events().into_iter().find(|x| x == &e).is_some(), "Event {:?} was not found in events: \n{:#?}", e, crate::mock::events() @@ -418,7 +418,7 @@ macro_rules! assert_events_emitted { macro_rules! assert_events_not_emitted { ($event:expr) => { [$event].into_iter().for_each(|e| assert!( - crate::mock::events().into_iter().find(|x| x != &e).is_some(), + $crate::mock::events().into_iter().find(|x| x != &e).is_some(), "Event {:?} was unexpectedly found in events: \n{:#?}", e, crate::mock::events() @@ -450,7 +450,7 @@ macro_rules! assert_events_eq_match { ($index:expr;) => { assert_eq!( $index, - crate::mock::events().len(), + $crate::mock::events().len(), "Found {} extra event(s): \n{:#?}", crate::mock::events().len()-$index, crate::mock::events() @@ -491,7 +491,7 @@ macro_rules! assert_events_eq_match { macro_rules! assert_events_emitted_match { ($event:pat_param) => { assert!( - crate::mock::events().into_iter().any(|x| matches!(x, $event)), + $crate::mock::events().into_iter().any(|x| matches!(x, $event)), "Event {:?} was not found in events: \n{:#?}", stringify!($event), crate::mock::events() @@ -519,7 +519,7 @@ macro_rules! assert_events_emitted_match { macro_rules! assert_events_not_emitted_match { ($event:pat_param) => { assert!( - crate::mock::events().into_iter().any(|x| !matches!(x, $event)), + $crate::mock::events().into_iter().any(|x| !matches!(x, $event)), "Event {:?} was unexpectedly found in events: \n{:#?}", stringify!($event), crate::mock::events() @@ -550,27 +550,27 @@ fn geneses() { assert!(System::events().is_empty()); // collators assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&1), 500); - assert_eq!(Balances::reserved_balance(&1), 500); + assert_eq!(Balances::reserved_balance(1), 500); assert!(ParachainStaking::is_candidate(&1)); - assert_eq!(Balances::reserved_balance(&2), 200); + assert_eq!(Balances::reserved_balance(2), 200); assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&2), 100); assert!(ParachainStaking::is_candidate(&2)); // delegators for x in 3..7 { assert!(ParachainStaking::is_delegator(&x)); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&x), 0); - assert_eq!(Balances::reserved_balance(&x), 100); + assert_eq!(Balances::reserved_balance(x), 100); } // uninvolved for x in 7..10 { assert!(!ParachainStaking::is_delegator(&x)); } // no delegator staking locks - assert_eq!(Balances::reserved_balance(&7), 0); + assert_eq!(Balances::reserved_balance(7), 0); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&7), 100); - assert_eq!(Balances::reserved_balance(&8), 0); + assert_eq!(Balances::reserved_balance(8), 0); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&8), 9); - assert_eq!(Balances::reserved_balance(&9), 0); + assert_eq!(Balances::reserved_balance(9), 0); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&9), 4); // no collator staking locks assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&7), 100); @@ -598,16 +598,16 @@ fn geneses() { // collators for x in 1..5 { assert!(ParachainStaking::is_candidate(&x)); - assert_eq!(Balances::reserved_balance(&x), 20); + assert_eq!(Balances::reserved_balance(x), 20); assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&x), 80); } assert!(ParachainStaking::is_candidate(&5)); - assert_eq!(Balances::reserved_balance(&5), 10); + assert_eq!(Balances::reserved_balance(5), 10); assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&5), 90); // delegators for x in 6..11 { assert!(ParachainStaking::is_delegator(&x)); - assert_eq!(Balances::reserved_balance(&x), 10); + assert_eq!(Balances::reserved_balance(x), 10); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&x), 90); } }); diff --git a/pallets/parachain-staking/src/tests.rs b/pallets/parachain-staking/src/tests.rs index 4a9bb4a72..01f40be95 100644 --- a/pallets/parachain-staking/src/tests.rs +++ b/pallets/parachain-staking/src/tests.rs @@ -782,7 +782,7 @@ fn execute_leave_candidates_removes_pending_delegation_requests() { .build() .execute_with(|| { assert_ok!(ParachainStaking::schedule_delegator_bond_less(RuntimeOrigin::signed(2), 1, 5)); - let state = ParachainStaking::delegation_scheduled_requests(&1); + let state = ParachainStaking::delegation_scheduled_requests(1); assert_eq!( state, vec![ScheduledRequest { delegator: 2, when_executable: 3, action: DelegationAction::Decrease(5) }], @@ -795,10 +795,10 @@ fn execute_leave_candidates_removes_pending_delegation_requests() { assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(1), 1, 1)); assert!(ParachainStaking::candidate_info(1).is_none()); assert!( - !ParachainStaking::delegation_scheduled_requests(&1).iter().any(|x| x.delegator == 2), + !ParachainStaking::delegation_scheduled_requests(1).iter().any(|x| x.delegator == 2), "delegation request not removed" ); - assert!(!>::contains_key(&1), "the key was not removed from storage"); + assert!(!>::contains_key(1), "the key was not removed from storage"); }); } @@ -836,7 +836,7 @@ fn cancel_leave_candidates_updates_candidate_state() { ExtBuilder::default().with_balances(vec![(1, 10)]).with_candidates(vec![(1, 10)]).build().execute_with(|| { assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(1), 1u32)); assert_ok!(ParachainStaking::cancel_leave_candidates(RuntimeOrigin::signed(1), 1)); - let candidate = ParachainStaking::candidate_info(&1).expect("just cancelled leave so exists"); + let candidate = ParachainStaking::candidate_info(1).expect("just cancelled leave so exists"); assert!(candidate.is_active()); }); } @@ -1144,7 +1144,7 @@ fn cancel_candidate_bond_less_updates_candidate_state() { ExtBuilder::default().with_balances(vec![(1, 30)]).with_candidates(vec![(1, 30)]).build().execute_with(|| { assert_ok!(ParachainStaking::schedule_candidate_bond_less(RuntimeOrigin::signed(1), 10)); assert_ok!(ParachainStaking::cancel_candidate_bond_less(RuntimeOrigin::signed(1))); - assert!(ParachainStaking::candidate_info(&1).unwrap().request.is_none()); + assert!(ParachainStaking::candidate_info(1).unwrap().request.is_none()); }); } @@ -1497,7 +1497,7 @@ fn execute_leave_delegators_unreserves_balance() { roll_to(10); assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1)); assert_eq!(ParachainStaking::get_delegator_stakable_free_balance(&2), 10); - assert_eq!(crate::mock::Balances::reserved_balance(&2), 0); + assert_eq!(crate::mock::Balances::reserved_balance(2), 0); }); } @@ -1542,7 +1542,7 @@ fn execute_leave_delegators_removes_pending_delegation_requests() { .build() .execute_with(|| { assert_ok!(ParachainStaking::schedule_delegator_bond_less(RuntimeOrigin::signed(2), 1, 5)); - let state = ParachainStaking::delegation_scheduled_requests(&1); + let state = ParachainStaking::delegation_scheduled_requests(1); assert_eq!( state, vec![ScheduledRequest { delegator: 2, when_executable: 3, action: DelegationAction::Decrease(5) }], @@ -1552,7 +1552,7 @@ fn execute_leave_delegators_removes_pending_delegation_requests() { assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 1)); assert!(ParachainStaking::delegator_state(2).is_none()); assert!( - !ParachainStaking::delegation_scheduled_requests(&1).iter().any(|x| x.delegator == 2), + !ParachainStaking::delegation_scheduled_requests(1).iter().any(|x| x.delegator == 2), "delegation request not removed" ) }); @@ -1694,7 +1694,7 @@ fn cancel_leave_delegators_updates_delegator_state() { .execute_with(|| { assert_ok!(ParachainStaking::schedule_leave_delegators(RuntimeOrigin::signed(2))); assert_ok!(ParachainStaking::cancel_leave_delegators(RuntimeOrigin::signed(2))); - let delegator = ParachainStaking::delegator_state(&2).expect("just cancelled exit so exists"); + let delegator = ParachainStaking::delegator_state(2).expect("just cancelled exit so exists"); assert!(delegator.is_active()); }); } @@ -1988,7 +1988,7 @@ fn delegator_bond_less_updates_delegator_state() { .build() .execute_with(|| { assert_ok!(ParachainStaking::schedule_delegator_bond_less(RuntimeOrigin::signed(2), 1, 5)); - let state = ParachainStaking::delegation_scheduled_requests(&1); + let state = ParachainStaking::delegation_scheduled_requests(1); assert_eq!( state, vec![ScheduledRequest { delegator: 2, when_executable: 3, action: DelegationAction::Decrease(5) }], @@ -2227,9 +2227,9 @@ fn execute_revoke_delegation_adds_revocation_to_delegator_state() { .with_delegations(vec![(2, 1, 10), (2, 3, 10)]) .build() .execute_with(|| { - assert!(!ParachainStaking::delegation_scheduled_requests(&1).iter().any(|x| x.delegator == 2)); + assert!(!ParachainStaking::delegation_scheduled_requests(1).iter().any(|x| x.delegator == 2)); assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - assert!(ParachainStaking::delegation_scheduled_requests(&1).iter().any(|x| x.delegator == 2)); + assert!(ParachainStaking::delegation_scheduled_requests(1).iter().any(|x| x.delegator == 2)); }); } @@ -2244,7 +2244,7 @@ fn execute_revoke_delegation_removes_revocation_from_delegator_state_upon_execut assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(2), 2, 1)); - assert!(!ParachainStaking::delegation_scheduled_requests(&1).iter().any(|x| x.delegator == 2)); + assert!(!ParachainStaking::delegation_scheduled_requests(1).iter().any(|x| x.delegator == 2)); }); } @@ -2260,7 +2260,7 @@ fn execute_revoke_delegation_removes_revocation_from_state_for_single_delegation roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(2), 2, 1)); assert!( - !ParachainStaking::delegation_scheduled_requests(&1).iter().any(|x| x.delegator == 2), + !ParachainStaking::delegation_scheduled_requests(1).iter().any(|x| x.delegator == 2), "delegation was not removed" ); }); @@ -2499,38 +2499,34 @@ fn execute_delegator_bond_less_updates_just_bottom_delegations() { .with_delegations(vec![(2, 1, 10), (3, 1, 11), (4, 1, 12), (5, 1, 14), (6, 1, 15)]) .build() .execute_with(|| { - let pre_call_candidate_info = ParachainStaking::candidate_info(&1).expect("delegated by all so exists"); - let pre_call_top_delegations = ParachainStaking::top_delegations(&1).expect("delegated by all so exists"); + let pre_call_candidate_info = ParachainStaking::candidate_info(1).expect("delegated by all so exists"); + let pre_call_top_delegations = ParachainStaking::top_delegations(1).expect("delegated by all so exists"); let pre_call_bottom_delegations = - ParachainStaking::bottom_delegations(&1).expect("delegated by all so exists"); + ParachainStaking::bottom_delegations(1).expect("delegated by all so exists"); assert_ok!(ParachainStaking::schedule_delegator_bond_less(RuntimeOrigin::signed(2), 1, 2)); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(2), 2, 1)); - let post_call_candidate_info = ParachainStaking::candidate_info(&1).expect("delegated by all so exists"); - let post_call_top_delegations = ParachainStaking::top_delegations(&1).expect("delegated by all so exists"); + let post_call_candidate_info = ParachainStaking::candidate_info(1).expect("delegated by all so exists"); + let post_call_top_delegations = ParachainStaking::top_delegations(1).expect("delegated by all so exists"); let post_call_bottom_delegations = - ParachainStaking::bottom_delegations(&1).expect("delegated by all so exists"); + ParachainStaking::bottom_delegations(1).expect("delegated by all so exists"); let mut not_equal = false; for Bond { owner, amount } in pre_call_bottom_delegations.delegations { for Bond { owner: post_owner, amount: post_amount } in &post_call_bottom_delegations.delegations { - if &owner == post_owner { - if &amount != post_amount { - not_equal = true; - break; - } - } + if &owner == post_owner && &amount != post_amount { + not_equal = true; + break; + } } } assert!(not_equal); let mut equal = true; for Bond { owner, amount } in pre_call_top_delegations.delegations { for Bond { owner: post_owner, amount: post_amount } in &post_call_top_delegations.delegations { - if &owner == post_owner { - if &amount != post_amount { - equal = false; - break; - } - } + if &owner == post_owner && &amount != post_amount { + equal = false; + break; + } } } assert!(equal); @@ -2546,38 +2542,34 @@ fn execute_delegator_bond_less_does_not_delete_bottom_delegations() { .with_delegations(vec![(2, 1, 10), (3, 1, 11), (4, 1, 12), (5, 1, 14), (6, 1, 15)]) .build() .execute_with(|| { - let pre_call_candidate_info = ParachainStaking::candidate_info(&1).expect("delegated by all so exists"); - let pre_call_top_delegations = ParachainStaking::top_delegations(&1).expect("delegated by all so exists"); + let pre_call_candidate_info = ParachainStaking::candidate_info(1).expect("delegated by all so exists"); + let pre_call_top_delegations = ParachainStaking::top_delegations(1).expect("delegated by all so exists"); let pre_call_bottom_delegations = - ParachainStaking::bottom_delegations(&1).expect("delegated by all so exists"); + ParachainStaking::bottom_delegations(1).expect("delegated by all so exists"); assert_ok!(ParachainStaking::schedule_delegator_bond_less(RuntimeOrigin::signed(6), 1, 4)); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(6), 6, 1)); - let post_call_candidate_info = ParachainStaking::candidate_info(&1).expect("delegated by all so exists"); - let post_call_top_delegations = ParachainStaking::top_delegations(&1).expect("delegated by all so exists"); + let post_call_candidate_info = ParachainStaking::candidate_info(1).expect("delegated by all so exists"); + let post_call_top_delegations = ParachainStaking::top_delegations(1).expect("delegated by all so exists"); let post_call_bottom_delegations = - ParachainStaking::bottom_delegations(&1).expect("delegated by all so exists"); + ParachainStaking::bottom_delegations(1).expect("delegated by all so exists"); let mut equal = true; for Bond { owner, amount } in pre_call_bottom_delegations.delegations { for Bond { owner: post_owner, amount: post_amount } in &post_call_bottom_delegations.delegations { - if &owner == post_owner { - if &amount != post_amount { - equal = false; - break; - } - } + if &owner == post_owner && &amount != post_amount { + equal = false; + break; + } } } assert!(equal); let mut not_equal = false; for Bond { owner, amount } in pre_call_top_delegations.delegations { for Bond { owner: post_owner, amount: post_amount } in &post_call_top_delegations.delegations { - if &owner == post_owner { - if &amount != post_amount { - not_equal = true; - break; - } - } + if &owner == post_owner && &amount != post_amount { + not_equal = true; + break; + } } } assert!(not_equal); @@ -2634,19 +2626,19 @@ fn cancel_revoke_delegation_updates_delegator_state() { .build() .execute_with(|| { assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); - let state = ParachainStaking::delegation_scheduled_requests(&1); + let state = ParachainStaking::delegation_scheduled_requests(1); assert_eq!( state, vec![ScheduledRequest { delegator: 2, when_executable: 3, action: DelegationAction::Revoke(10) }], ); assert_eq!( - ParachainStaking::delegator_state(&2).map(|x| x.less_total).expect("delegator state must exist"), + ParachainStaking::delegator_state(2).map(|x| x.less_total).expect("delegator state must exist"), 10 ); assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 1)); - assert!(!ParachainStaking::delegation_scheduled_requests(&1).iter().any(|x| x.delegator == 2)); + assert!(!ParachainStaking::delegation_scheduled_requests(1).iter().any(|x| x.delegator == 2)); assert_eq!( - ParachainStaking::delegator_state(&2).map(|x| x.less_total).expect("delegator state must exist"), + ParachainStaking::delegator_state(2).map(|x| x.less_total).expect("delegator state must exist"), 0 ); }); @@ -2684,19 +2676,19 @@ fn cancel_delegator_bond_less_updates_delegator_state() { .build() .execute_with(|| { assert_ok!(ParachainStaking::schedule_delegator_bond_less(RuntimeOrigin::signed(2), 1, 5)); - let state = ParachainStaking::delegation_scheduled_requests(&1); + let state = ParachainStaking::delegation_scheduled_requests(1); assert_eq!( state, vec![ScheduledRequest { delegator: 2, when_executable: 3, action: DelegationAction::Decrease(5) }], ); assert_eq!( - ParachainStaking::delegator_state(&2).map(|x| x.less_total).expect("delegator state must exist"), + ParachainStaking::delegator_state(2).map(|x| x.less_total).expect("delegator state must exist"), 5 ); assert_ok!(ParachainStaking::cancel_delegation_request(RuntimeOrigin::signed(2), 1)); - assert!(!ParachainStaking::delegation_scheduled_requests(&1).iter().any(|x| x.delegator == 2)); + assert!(!ParachainStaking::delegation_scheduled_requests(1).iter().any(|x| x.delegator == 2)); assert_eq!( - ParachainStaking::delegator_state(&2).map(|x| x.less_total).expect("delegator state must exist"), + ParachainStaking::delegator_state(2).map(|x| x.less_total).expect("delegator state must exist"), 0 ); }); @@ -2714,31 +2706,31 @@ fn delegator_schedule_revocation_total() { .execute_with(|| { assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 1)); assert_eq!( - ParachainStaking::delegator_state(&2).map(|x| x.less_total).expect("delegator state must exist"), + ParachainStaking::delegator_state(2).map(|x| x.less_total).expect("delegator state must exist"), 10 ); roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(2), 2, 1)); assert_eq!( - ParachainStaking::delegator_state(&2).map(|x| x.less_total).expect("delegator state must exist"), + ParachainStaking::delegator_state(2).map(|x| x.less_total).expect("delegator state must exist"), 0 ); assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 5, 10, 0, 2)); assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 3)); assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(2), 4)); assert_eq!( - ParachainStaking::delegator_state(&2).map(|x| x.less_total).expect("delegator state must exist"), + ParachainStaking::delegator_state(2).map(|x| x.less_total).expect("delegator state must exist"), 20, ); roll_to(20); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(2), 2, 3)); assert_eq!( - ParachainStaking::delegator_state(&2).map(|x| x.less_total).expect("delegator state must exist"), + ParachainStaking::delegator_state(2).map(|x| x.less_total).expect("delegator state must exist"), 10, ); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(2), 2, 4)); assert_eq!( - ParachainStaking::delegator_state(&2).map(|x| x.less_total).expect("delegator state must exist"), + ParachainStaking::delegator_state(2).map(|x| x.less_total).expect("delegator state must exist"), 0 ); }); @@ -2817,7 +2809,7 @@ fn collator_exit_executes_after_delay() { roll_to(11); assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(2), 2)); assert_events_eq!(Event::CandidateScheduledExit { exit_allowed_round: 3, candidate: 2, scheduled_exit: 5 }); - let info = ParachainStaking::candidate_info(&2).unwrap(); + let info = ParachainStaking::candidate_info(2).unwrap(); assert_eq!(info.status, CollatorStatus::Leaving(5)); roll_to(21); assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(2), 2, 2)); @@ -3093,17 +3085,17 @@ fn execute_leave_candidate_removes_delegations() { .build() .execute_with(|| { // Verifies the revocation request is initially empty - assert!(!ParachainStaking::delegation_scheduled_requests(&2).iter().any(|x| x.delegator == 3)); + assert!(!ParachainStaking::delegation_scheduled_requests(2).iter().any(|x| x.delegator == 3)); assert_ok!(ParachainStaking::schedule_leave_candidates(RuntimeOrigin::signed(2), 2)); assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(3), 2)); // Verifies the revocation request is present - assert!(ParachainStaking::delegation_scheduled_requests(&2).iter().any(|x| x.delegator == 3)); + assert!(ParachainStaking::delegation_scheduled_requests(2).iter().any(|x| x.delegator == 3)); roll_to(16); assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(2), 2, 2)); // Verifies the revocation request is again empty - assert!(!ParachainStaking::delegation_scheduled_requests(&2).iter().any(|x| x.delegator == 3)); + assert!(!ParachainStaking::delegation_scheduled_requests(2).iter().any(|x| x.delegator == 3)); }); } @@ -3824,13 +3816,13 @@ fn deferred_payment_steady_state_event_flow() { assert!(num_rounds_rolled <= 1, "expected to be at round begin already"); assert_events_eq!( - Event::CollatorChosen { round: round as u32, collator_account: 1, total_exposed_amount: 400 }, - Event::CollatorChosen { round: round as u32, collator_account: 2, total_exposed_amount: 400 }, - Event::CollatorChosen { round: round as u32, collator_account: 3, total_exposed_amount: 400 }, - Event::CollatorChosen { round: round as u32, collator_account: 4, total_exposed_amount: 400 }, + Event::CollatorChosen { round: round, collator_account: 1, total_exposed_amount: 400 }, + Event::CollatorChosen { round: round, collator_account: 2, total_exposed_amount: 400 }, + Event::CollatorChosen { round: round, collator_account: 3, total_exposed_amount: 400 }, + Event::CollatorChosen { round: round, collator_account: 4, total_exposed_amount: 400 }, Event::NewRound { starting_block: (round - 1) * 5, - round: round as u32, + round: round, selected_collators_number: 4, total_balance: 1600, }, @@ -3924,7 +3916,7 @@ fn delegation_kicked_from_bottom_removes_pending_request() { // check the event assert_events_emitted!(Event::DelegationKicked { delegator: 2, candidate: 1, unstaked_amount: 19 }); // ensure request DNE - assert!(!ParachainStaking::delegation_scheduled_requests(&1).iter().any(|x| x.delegator == 2)); + assert!(!ParachainStaking::delegation_scheduled_requests(1).iter().any(|x| x.delegator == 2)); }); } @@ -4367,19 +4359,19 @@ fn revoke_last_removes_lock() { .with_delegations(vec![(3, 1, 30), (3, 2, 25)]) .build() .execute_with(|| { - assert_eq!(crate::mock::Balances::reserved_balance(&3), 55); + assert_eq!(crate::mock::Balances::reserved_balance(3), 55); // schedule and remove one... assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(3), 1)); roll_to_round_begin(3); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(3), 3, 1)); - assert_eq!(crate::mock::Balances::reserved_balance(&3), 25); + assert_eq!(crate::mock::Balances::reserved_balance(3), 25); // schedule and remove the other... assert_ok!(ParachainStaking::schedule_revoke_delegation(RuntimeOrigin::signed(3), 2)); roll_to_round_begin(5); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(3), 3, 2)); - assert_eq!(crate::mock::Balances::reserved_balance(&3), 0); + assert_eq!(crate::mock::Balances::reserved_balance(3), 0); }); } @@ -4562,7 +4554,7 @@ fn test_set_auto_compound_inserts_if_not_exists() { }); assert_eq!( vec![AutoCompoundConfig { delegator: 2, value: Percent::from_percent(50) }], - ParachainStaking::auto_compounding_delegations(&1).into_inner(), + ParachainStaking::auto_compounding_delegations(1).into_inner(), ); }); } @@ -4596,7 +4588,7 @@ fn test_set_auto_compound_updates_if_existing() { }); assert_eq!( vec![AutoCompoundConfig { delegator: 2, value: Percent::from_percent(50) }], - ParachainStaking::auto_compounding_delegations(&1).into_inner(), + ParachainStaking::auto_compounding_delegations(1).into_inner(), ); }); } @@ -4618,7 +4610,7 @@ fn test_set_auto_compound_removes_if_auto_compound_zero_percent() { assert_ok!(ParachainStaking::set_auto_compound(RuntimeOrigin::signed(2), 1, Percent::zero(), 1, 1,)); assert_events_emitted!(Event::AutoCompoundSet { candidate: 1, delegator: 2, value: Percent::zero() }); - assert_eq!(0, ParachainStaking::auto_compounding_delegations(&1).len(),); + assert_eq!(0, ParachainStaking::auto_compounding_delegations(1).len(),); }); } @@ -4648,11 +4640,11 @@ fn test_execute_revoke_delegation_removes_auto_compounding_from_state_for_delega roll_to(10); assert_ok!(ParachainStaking::execute_delegation_request(RuntimeOrigin::signed(2), 2, 1)); assert!( - !ParachainStaking::auto_compounding_delegations(&1).iter().any(|x| x.delegator == 2), + !ParachainStaking::auto_compounding_delegations(1).iter().any(|x| x.delegator == 2), "delegation auto-compound config was not removed" ); assert!( - ParachainStaking::auto_compounding_delegations(&3).iter().any(|x| x.delegator == 2), + ParachainStaking::auto_compounding_delegations(3).iter().any(|x| x.delegator == 2), "delegation auto-compound config was erroneously removed" ); }); @@ -4686,11 +4678,11 @@ fn test_execute_leave_delegators_removes_auto_compounding_state() { assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 2,)); assert!( - !ParachainStaking::auto_compounding_delegations(&1).iter().any(|x| x.delegator == 2), + !ParachainStaking::auto_compounding_delegations(1).iter().any(|x| x.delegator == 2), "delegation auto-compound config was not removed" ); assert!( - !ParachainStaking::auto_compounding_delegations(&3).iter().any(|x| x.delegator == 2), + !ParachainStaking::auto_compounding_delegations(3).iter().any(|x| x.delegator == 2), "delegation auto-compound config was not removed" ); }); @@ -4729,11 +4721,11 @@ fn test_execute_leave_delegators_with_deprecated_status_leaving_removes_auto_com assert_ok!(ParachainStaking::execute_leave_delegators(RuntimeOrigin::signed(2), 2, 2,)); assert!( - !ParachainStaking::auto_compounding_delegations(&1).iter().any(|x| x.delegator == 2), + !ParachainStaking::auto_compounding_delegations(1).iter().any(|x| x.delegator == 2), "delegation auto-compound config was not removed" ); assert!( - !ParachainStaking::auto_compounding_delegations(&3).iter().any(|x| x.delegator == 2), + !ParachainStaking::auto_compounding_delegations(3).iter().any(|x| x.delegator == 2), "delegation auto-compound config was not removed" ); }); @@ -4767,11 +4759,11 @@ fn test_execute_leave_candidates_removes_auto_compounding_state() { assert_ok!(ParachainStaking::execute_leave_candidates(RuntimeOrigin::signed(1), 1, 1,)); assert!( - !ParachainStaking::auto_compounding_delegations(&1).iter().any(|x| x.delegator == 2), + !ParachainStaking::auto_compounding_delegations(1).iter().any(|x| x.delegator == 2), "delegation auto-compound config was not removed" ); assert!( - ParachainStaking::auto_compounding_delegations(&3).iter().any(|x| x.delegator == 2), + ParachainStaking::auto_compounding_delegations(3).iter().any(|x| x.delegator == 2), "delegation auto-compound config was erroneously removed" ); }); @@ -4819,7 +4811,7 @@ fn test_delegation_kicked_from_bottom_delegation_removes_auto_compounding_state( assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(10), 1, 20, 8, 0)); assert!( - !ParachainStaking::auto_compounding_delegations(&1).iter().any(|x| x.delegator == 2), + !ParachainStaking::auto_compounding_delegations(1).iter().any(|x| x.delegator == 2), "delegation auto-compound config was not removed" ); }); @@ -5028,7 +5020,7 @@ fn test_delegate_with_auto_compound_sets_auto_compound_config() { }); assert_eq!( vec![AutoCompoundConfig { delegator: 2, value: Percent::from_percent(50) }], - ParachainStaking::auto_compounding_delegations(&1).into_inner(), + ParachainStaking::auto_compounding_delegations(1).into_inner(), ); }, ); @@ -5047,7 +5039,7 @@ fn test_delegate_with_auto_compound_skips_storage_but_emits_event_for_zero_auto_ 0, 0, )); - assert_eq!(0, ParachainStaking::auto_compounding_delegations(&1).len(),); + assert_eq!(0, ParachainStaking::auto_compounding_delegations(1).len(),); assert_events_eq!(Event::Delegation { delegator: 2, locked_amount: 10, @@ -5352,7 +5344,7 @@ fn test_delegate_skips_auto_compound_storage_but_emits_event_for_zero_auto_compo // We already have an auto-compounding delegation from 3 -> 1, so the hint validation // would cause a failure if the auto-compounding isn't skipped properly. assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(2), 1, 10, 1, 0,)); - assert_eq!(1, ParachainStaking::auto_compounding_delegations(&1).len(),); + assert_eq!(1, ParachainStaking::auto_compounding_delegations(1).len(),); assert_events_eq!(Event::Delegation { delegator: 2, locked_amount: 10, diff --git a/pallets/parachain-staking/src/types.rs b/pallets/parachain-staking/src/types.rs index 96b985012..dabd14c02 100644 --- a/pallets/parachain-staking/src/types.rs +++ b/pallets/parachain-staking/src/types.rs @@ -1384,7 +1384,7 @@ impl< )?; } else { let additional_hold = Into::::into(self.total).saturating_sub(total_bonded); - T::Currency::hold(&HoldReason::StakingDelegator.into(), &self.id.clone().into(), additional_hold.into())?; + T::Currency::hold(&HoldReason::StakingDelegator.into(), &self.id.clone().into(), additional_hold)?; } Ok(()) diff --git a/pallets/xcm-executor/src/lib.rs b/pallets/xcm-executor/src/lib.rs index a04c573c9..43926092b 100644 --- a/pallets/xcm-executor/src/lib.rs +++ b/pallets/xcm-executor/src/lib.rs @@ -218,7 +218,7 @@ impl ExecuteXcm for XcmExecutor) -> Result> { match Config::Weigher::weight(&mut message) { Ok(weight) => Ok(WeighedMessage(weight, message)), - Err(_) => Err(message), + Err(()) => Err(message), } } @@ -267,7 +267,7 @@ impl ExecuteXcm for XcmExecutor XcmExecutor { let paid = if self.fees_mode.jit_withdraw { let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; for asset in fee.inner() { - Config::AssetTransactor::withdraw_asset(&asset, origin, Some(&self.context))?; + Config::AssetTransactor::withdraw_asset(asset, origin, Some(&self.context))?; } fee } else { @@ -452,7 +452,7 @@ impl XcmExecutor { Ok(match local_querier { None => None, Some(q) => Some( - q.reanchored(&destination, Config::UniversalLocation::get()).map_err(|_| XcmError::ReanchorFailed)?, + q.reanchored(destination, Config::UniversalLocation::get()).map_err(|_| XcmError::ReanchorFailed)?, ), }) } @@ -479,7 +479,7 @@ impl XcmExecutor { destination: &MultiLocation, ) -> Result<(MultiAsset, InteriorMultiLocation), XcmError> { let reanchor_context = Config::UniversalLocation::get(); - let asset = asset.reanchored(&destination, reanchor_context).map_err(|()| XcmError::ReanchorFailed)?; + let asset = asset.reanchored(destination, reanchor_context).map_err(|()| XcmError::ReanchorFailed)?; Ok((asset, reanchor_context)) } @@ -488,7 +488,7 @@ impl XcmExecutor { destination: &MultiLocation, ) -> Result<(MultiLocation, InteriorMultiLocation), XcmError> { let reanchor_context = Config::UniversalLocation::get(); - let location = location.reanchored(&destination, reanchor_context).map_err(|_| XcmError::ReanchorFailed)?; + let location = location.reanchored(destination, reanchor_context).map_err(|_| XcmError::ReanchorFailed)?; Ok((location, reanchor_context)) } @@ -547,7 +547,7 @@ impl XcmExecutor { }, Err(ref mut error) => if let Ok(x) = Config::Weigher::instr_weight(&instr) { - error.weight.saturating_accrue(x) + error.weight.saturating_accrue(x); }, } } @@ -565,7 +565,7 @@ impl XcmExecutor { WithdrawAsset(assets) => { // Take `assets` from the origin account (on-chain) and place in holding. let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; - for asset in assets.into_inner().into_iter() { + for asset in assets.into_inner() { Config::AssetTransactor::withdraw_asset(&asset, &origin, Some(&self.context))?; self.subsume_asset(asset)?; } @@ -574,7 +574,7 @@ impl XcmExecutor { ReserveAssetDeposited(assets) => { // check whether we trust origin to be our reserve location for this asset. let origin = *self.origin_ref().ok_or(XcmError::BadOrigin)?; - for asset in assets.into_inner().into_iter() { + for asset in assets.into_inner() { // Must ensure that we recognise the asset as being managed by the origin. ensure!(Config::IsReserve::contains(&asset, &origin), XcmError::UntrustedReserveLocation); self.subsume_asset(asset)?; @@ -585,7 +585,7 @@ impl XcmExecutor { // Take `assets` from the origin account (on-chain) and place into dest account. let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; for asset in assets.inner() { - Config::AssetTransactor::transfer_asset(&asset, origin, &beneficiary, &self.context)?; + Config::AssetTransactor::transfer_asset(asset, origin, &beneficiary, &self.context)?; } Ok(()) }, @@ -598,7 +598,7 @@ impl XcmExecutor { let reanchor_context = Config::UniversalLocation::get(); assets.reanchor(&dest, reanchor_context).map_err(|()| XcmError::LocationFull)?; let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; - message.extend(xcm.0.into_iter()); + message.extend(xcm.0); self.send(dest, Xcm(message), FeeReason::TransferReserveAsset)?; Ok(()) }, @@ -615,7 +615,7 @@ impl XcmExecutor { // innocent chain/user). Config::AssetTransactor::can_check_in(&origin, asset, &self.context)?; } - for asset in assets.into_inner().into_iter() { + for asset in assets.into_inner() { Config::AssetTransactor::check_in(&origin, &asset, &self.context); self.subsume_asset(asset)?; } @@ -633,7 +633,7 @@ impl XcmExecutor { })?; // TODO: #2841 #TRANSACTFILTER allow the trait to issue filters for the relay-chain - let message_call = call.take_decoded().map_err(|_| { + let message_call = call.take_decoded().map_err(|()| { log::trace!( target: "xcm::process_instruction::transact", "Failed to decode call", @@ -763,7 +763,7 @@ impl XcmExecutor { // be reanchored because we have already called `deposit_asset` on all assets. let assets = Self::reanchored(deposited, &dest, None); let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; - message.extend(xcm.0.into_iter()); + message.extend(xcm.0); self.send(dest, Xcm(message), FeeReason::DepositReserveAsset)?; Ok(()) }, @@ -772,7 +772,7 @@ impl XcmExecutor { // back into Holding. let assets = Self::reanchored(self.holding.saturating_take(assets), &reserve, Some(&mut self.holding)); let mut message = vec![WithdrawAsset(assets), ClearOrigin]; - message.extend(xcm.0.into_iter()); + message.extend(xcm.0); self.send(reserve, Xcm(message), FeeReason::InitiateReserveWithdraw)?; Ok(()) }, @@ -793,7 +793,7 @@ impl XcmExecutor { // be reanchored because we have already checked all assets out. let assets = Self::reanchored(assets, &dest, None); let mut message = vec![ReceiveTeleportedAsset(assets), ClearOrigin]; - message.extend(xcm.0.into_iter()); + message.extend(xcm.0); self.send(dest, Xcm(message), FeeReason::InitiateTeleport)?; Ok(()) }, @@ -842,7 +842,7 @@ impl XcmExecutor { let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; let ok = Config::AssetClaims::claim_assets(origin, &ticket, &assets, &self.context); ensure!(ok, XcmError::UnknownClaim); - for asset in assets.into_inner().into_iter() { + for asset in assets.into_inner() { self.subsume_asset(asset)?; } Ok(()) @@ -886,9 +886,9 @@ impl XcmExecutor { x.index as u32, x.name.as_bytes().into(), x.module_name.as_bytes().into(), - x.crate_version.major as u32, - x.crate_version.minor as u32, - x.crate_version.patch as u32, + u32::from(x.crate_version.major), + u32::from(x.crate_version.minor), + u32::from(x.crate_version.patch), ) }) .collect::, XcmError>>()?; @@ -907,9 +907,9 @@ impl XcmExecutor { .ok_or(XcmError::PalletNotFound)?; ensure!(pallet.name.as_bytes() == &name[..], XcmError::NameMismatch); ensure!(pallet.module_name.as_bytes() == &module_name[..], XcmError::NameMismatch); - let major = pallet.crate_version.major as u32; + let major = u32::from(pallet.crate_version.major); ensure!(major == crate_major, XcmError::VersionIncompatible); - let minor = pallet.crate_version.minor as u32; + let minor = u32::from(pallet.crate_version.minor); ensure!(minor >= min_crate_minor, XcmError::VersionIncompatible); Ok(()) }, diff --git a/pallets/xcm-executor/src/polimec_traits.rs b/pallets/xcm-executor/src/polimec_traits.rs index 7e4eabb00..0bba119b3 100644 --- a/pallets/xcm-executor/src/polimec_traits.rs +++ b/pallets/xcm-executor/src/polimec_traits.rs @@ -22,7 +22,9 @@ use xcm::v3::{ pub use xcm_executor::traits::*; pub trait HrmpHandler { + #[allow(clippy::missing_errors_doc)] fn handle_channel_open_request(message: Instruction) -> XcmResult; + #[allow(clippy::missing_errors_doc)] fn handle_channel_accepted(message: Instruction) -> XcmResult; } diff --git a/polimec-common/common/src/credentials/mod.rs b/polimec-common/common/src/credentials/mod.rs index 3a73b10ce..9d5ffd0eb 100644 --- a/polimec-common/common/src/credentials/mod.rs +++ b/polimec-common/common/src/credentials/mod.rs @@ -36,6 +36,7 @@ pub enum InvestorType { } impl InvestorType { + #[must_use] pub fn as_str(&self) -> &'static str { match self { InvestorType::Retail => "retail", @@ -87,7 +88,10 @@ where let Ok(now) = Now::::get().try_into() else { return Err(origin) }; let Some(date_time) = claims.expiration else { return Err(origin) }; - if claims.custom.subject == who && (date_time.timestamp_millis() as u64) >= now { + // Negative timestamp has unintended behavior with underflow. + let time_stamp: u64 = date_time.timestamp_millis().try_into().map_err(|_| origin.clone())?; + + if claims.custom.subject == who && time_stamp >= now { return Ok(( who, claims.custom.did.clone(), diff --git a/runtimes/polimec/build.rs b/runtimes/polimec/build.rs index 657bcc0d1..fcbbf573c 100644 --- a/runtimes/polimec/build.rs +++ b/runtimes/polimec/build.rs @@ -17,5 +17,5 @@ use substrate_wasm_builder::WasmBuilder; fn main() { - WasmBuilder::new().with_current_project().export_heap_base().import_memory().build() + WasmBuilder::new().with_current_project().export_heap_base().import_memory().build(); }