From 6f5a51ce1f3a6fb4380f9e7b8516c4640c6a069f Mon Sep 17 00:00:00 2001 From: brenzi Date: Wed, 7 Feb 2024 11:51:24 +0100 Subject: [PATCH] fixing benchmarks if genesis is pure defaults (#368) * fixing benchmarks if genesis is pure defaults * bump crate versions to publish * trying to pin stable for crates.io * another fix in ceremonies benchmakrs * lockfile * fmt +stable * clippy * fix tests --- Cargo.lock | 10 +- balances-tx-payment/rpc/src/lib.rs | 20 +--- balances/src/impl_fungibles.rs | 14 +-- balances/src/lib.rs | 6 +- bazaar/Cargo.toml | 4 +- bazaar/src/benchmarking.rs | 4 + ceremonies/Cargo.toml | 6 +- ceremonies/assignment/src/lib.rs | 14 +-- ceremonies/assignment/src/math.rs | 26 ++--- ceremonies/meetup-validation/src/lib.rs | 24 ++--- ceremonies/meetup-validation/src/tests.rs | 7 +- ceremonies/rpc/src/lib.rs | 6 +- ceremonies/src/benchmarking.rs | 33 ++++++- ceremonies/src/lib.rs | 99 ++++++++++--------- ceremonies/src/migrations.rs | 2 +- ceremonies/src/tests.rs | 22 ++--- communities/Cargo.toml | 4 +- communities/rpc/src/lib.rs | 4 +- communities/src/benchmarking.rs | 4 +- communities/src/lib.rs | 42 ++++---- communities/src/migrations.rs | 2 +- communities/src/tests.rs | 4 +- democracy/src/lib.rs | 20 ++-- democracy/src/tests.rs | 2 +- faucet/Cargo.toml | 4 +- faucet/src/benchmarking.rs | 2 + faucet/src/lib.rs | 10 +- faucet/src/mock.rs | 2 +- faucet/src/tests.rs | 2 +- primitives/core/src/bs58_verify.rs | 4 +- .../core/src/random_number_generator.rs | 2 +- primitives/src/balances.rs | 6 +- primitives/src/common.rs | 4 +- primitives/src/communities.rs | 21 ++-- primitives/src/democracy.rs | 10 +- primitives/src/lib.rs | 1 - reputation-commitments/src/lib.rs | 6 +- rust-toolchain.toml | 2 +- scheduler/Cargo.toml | 2 +- scheduler/src/benchmarking.rs | 22 +++++ scheduler/src/lib.rs | 10 +- test-utils/src/helpers.rs | 6 +- 42 files changed, 272 insertions(+), 223 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e223d66b..3ba76356 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4391,7 +4391,7 @@ dependencies = [ [[package]] name = "pallet-encointer-bazaar" -version = "3.0.2" +version = "3.0.3" dependencies = [ "encointer-primitives", "frame-benchmarking", @@ -4437,7 +4437,7 @@ dependencies = [ [[package]] name = "pallet-encointer-ceremonies" -version = "3.0.2" +version = "3.0.4" dependencies = [ "approx", "encointer-ceremonies-assignment", @@ -4494,7 +4494,7 @@ dependencies = [ [[package]] name = "pallet-encointer-communities" -version = "3.0.2" +version = "3.0.3" dependencies = [ "approx", "encointer-primitives", @@ -4571,7 +4571,7 @@ dependencies = [ [[package]] name = "pallet-encointer-faucet" -version = "3.0.2" +version = "3.0.3" dependencies = [ "approx", "encointer-primitives", @@ -4616,7 +4616,7 @@ dependencies = [ [[package]] name = "pallet-encointer-scheduler" -version = "3.0.2" +version = "3.0.3" dependencies = [ "encointer-primitives", "frame-benchmarking", diff --git a/balances-tx-payment/rpc/src/lib.rs b/balances-tx-payment/rpc/src/lib.rs index e47b5d0c..f17f198c 100644 --- a/balances-tx-payment/rpc/src/lib.rs +++ b/balances-tx-payment/rpc/src/lib.rs @@ -20,9 +20,9 @@ use encointer_balances_tx_payment_rpc_runtime_api::{ BalancesTxPaymentApi as BalancesTxPaymentApiRuntimeApi, Error, }; use jsonrpsee::{ - core::{Error as JsonRpseeError, RpcResult}, + core::RpcResult, proc_macros::rpc, - types::error::{CallError, ErrorCode, ErrorObject}, + types::error::{CallError, ErrorObject}, }; pub use pallet_transaction_payment::RuntimeDispatchInfo; use pallet_transaction_payment::{FeeDetails, InclusionFee}; @@ -107,16 +107,6 @@ where )) })?; - let try_into_rpc_balance = |value: AssetBalance| { - value.try_into().map_err(|_| { - JsonRpseeError::Call(CallError::Custom(ErrorObject::owned( - ErrorCode::InvalidParams.code(), - format!("{value} doesn't fit in NumberOrHex representation"), - None::<()>, - ))) - }) - }; - Ok(FeeDetails { inclusion_fee: if let Some(inclusion_fee) = fee_details.inclusion_fee { let base_fee = api @@ -147,9 +137,9 @@ where })?; Some(InclusionFee { - base_fee: try_into_rpc_balance(base_fee)?, - len_fee: try_into_rpc_balance(len_fee)?, - adjusted_weight_fee: try_into_rpc_balance(adjusted_weight_fee)?, + base_fee: base_fee.into(), + len_fee: len_fee.into(), + adjusted_weight_fee: adjusted_weight_fee.into(), }) } else { None diff --git a/balances/src/impl_fungibles.rs b/balances/src/impl_fungibles.rs index d4703663..9510d925 100644 --- a/balances/src/impl_fungibles.rs +++ b/balances/src/impl_fungibles.rs @@ -71,20 +71,20 @@ impl fungibles::Inspect for Pallet { _provenance: Provenance, ) -> DepositConsequence { if !>::contains_key(asset) { - return DepositConsequence::UnknownAsset + return DepositConsequence::UnknownAsset; }; let total_issuance = Pallet::::total_issuance_entry(asset).principal; let balance_amount = balance_type(amount); if total_issuance.checked_add(balance_amount).is_none() { - return DepositConsequence::Overflow + return DepositConsequence::Overflow; } let balance = Pallet::::balance(asset, who); if balance.checked_add(balance_amount).is_none() { - return DepositConsequence::Overflow + return DepositConsequence::Overflow; } DepositConsequence::Success @@ -98,22 +98,22 @@ impl fungibles::Inspect for Pallet { use WithdrawConsequence::*; if !>::contains_key(asset) { - return UnknownAsset + return UnknownAsset; }; let total_issuance = Pallet::::total_issuance_entry(asset); if fungible(total_issuance.principal).checked_sub(amount).is_none() { - return Underflow + return Underflow; } if amount.is_zero() { - return Success + return Success; } let balance = fungible(Pallet::::balance(asset, who)); if balance.checked_sub(amount).is_none() { - return WithdrawConsequence::BalanceLow + return WithdrawConsequence::BalanceLow; } WithdrawConsequence::Success } diff --git a/balances/src/lib.rs b/balances/src/lib.rs index a83b9ed5..22b05aa9 100644 --- a/balances/src/lib.rs +++ b/balances/src/lib.rs @@ -278,7 +278,7 @@ impl Pallet { // Early exist if no-op. if amount == 0u128 { Self::deposit_event(Event::Transferred(cid, source, dest, amount)); - return Ok(amount) + return Ok(amount); } ensure!(Balance::::contains_key(cid, &source), Error::::NoAccount); @@ -289,7 +289,7 @@ impl Pallet { if source == dest { >::insert(cid, &source, entry_from); - return Ok(amount) + return Ok(amount); } if !Balance::::contains_key(cid, &dest) { @@ -352,7 +352,7 @@ impl Pallet { ensure!(res >= 0, Error::::BalanceTooLow); res } else { - return Err(Error::::BalanceTooLow.into()) + return Err(Error::::BalanceTooLow.into()); }; entry_tot.principal -= amount; //FIXME: delete account if it falls below existential deposit diff --git a/bazaar/Cargo.toml b/bazaar/Cargo.toml index 280ee5be..a5eefcba 100644 --- a/bazaar/Cargo.toml +++ b/bazaar/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-encointer-bazaar" -version = "3.0.2" +version = "3.0.3" authors = ["Encointer Association "] edition = "2021" description = "Bazaar pallet for the Encointer blockchain runtime" @@ -16,7 +16,7 @@ log = { version = "0.4.20", default-features = false } scale-info = { version = "2.10.0", default-features = false } # local deps -encointer-communities = { package = "pallet-encointer-communities", path = "../communities", default-features = false, version = "3.0.2" } +encointer-communities = { package = "pallet-encointer-communities", path = "../communities", default-features = false, version = "3.0.3" } encointer-primitives = { path = "../primitives", default-features = false, features = ["serde_derive"], version = "3.0.2" } # substrate deps diff --git a/bazaar/src/benchmarking.rs b/bazaar/src/benchmarking.rs index 29be3aad..5c749ffa 100644 --- a/bazaar/src/benchmarking.rs +++ b/bazaar/src/benchmarking.rs @@ -23,6 +23,10 @@ fn create_community() -> CommunityIdentifier { let bs = vec![alice.clone(), bob.clone(), charlie.clone()]; let community_meta: CommunityMetadata = CommunityMetadata::default(); + + encointer_communities::Pallet::::set_min_solar_trip_time_s(RawOrigin::Root.into(), 1).ok(); + encointer_communities::Pallet::::set_max_speed_mps(RawOrigin::Root.into(), 83).ok(); + encointer_communities::Pallet::::new_community( RawOrigin::Root.into(), location, diff --git a/ceremonies/Cargo.toml b/ceremonies/Cargo.toml index 3c618dc2..4d505218 100644 --- a/ceremonies/Cargo.toml +++ b/ceremonies/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-encointer-ceremonies" -version = "3.0.2" +version = "3.0.4" authors = ["Encointer Association "] edition = "2021" description = "Ceremonies pallet for the Encointer blockchain runtime" @@ -18,10 +18,10 @@ scale-info = { version = "2.10.0", default-features = false } # local deps encointer-balances = { package = "pallet-encointer-balances", path = "../balances", default-features = false, version = "3.0.2" } encointer-ceremonies-assignment = { path = "assignment", default-features = false, version = "3.0.2" } -encointer-communities = { package = "pallet-encointer-communities", path = "../communities", default-features = false, version = "3.0.2" } +encointer-communities = { package = "pallet-encointer-communities", path = "../communities", default-features = false, version = "3.0.3" } encointer-meetup-validation = { path = "meetup-validation", default-features = false, version = "3.0.2" } encointer-primitives = { path = "../primitives", default-features = false, features = ["serde_derive"], version = "3.0.2" } -encointer-scheduler = { package = "pallet-encointer-scheduler", path = "../scheduler", default-features = false, version = "3.0.2" } +encointer-scheduler = { package = "pallet-encointer-scheduler", path = "../scheduler", default-features = false, version = "3.0.3" } # substrate deps frame-support = { default-features = false, version = "25.0.0" } diff --git a/ceremonies/assignment/src/lib.rs b/ceremonies/assignment/src/lib.rs index 9a580c04..b20e7b8d 100644 --- a/ceremonies/assignment/src/lib.rs +++ b/ceremonies/assignment/src/lib.rs @@ -50,7 +50,7 @@ pub fn generate_assignment_function_params( AssignmentParams { m: m as u64, s1: s1 as u64, s2: s2 as u64 }, num_meetups, ) { - break + break; } else { skip_count += 1; // safe; skip_count <= 200; } @@ -65,7 +65,7 @@ fn validate_equal_mapping( meetup_count: u64, ) -> bool { if num_participants < 2 { - return true + return true; } let mut meetup_index_count: Vec = vec![0; meetup_count as usize]; @@ -80,7 +80,7 @@ fn validate_equal_mapping( meetup_index_count[meetup_index] += 1; // safe; <= num_participants if meetup_index_count[meetup_index] > meetup_index_count_max { - return false + return false; } } true @@ -97,14 +97,14 @@ pub fn assignment_fn_inverse( participant_count: u64, ) -> Option> { if assignment_count == 0 { - return Some(vec![]) + return Some(vec![]); } let mut max_index = assignment_params.m.saturating_sub(meetup_index) / assignment_count; let mut result: Vec = Vec::with_capacity(max_index as usize); // ceil - if (assignment_params.m.saturating_sub(meetup_index) as i64).rem_euclid(assignment_count as i64) != - 0 + if (assignment_params.m.saturating_sub(meetup_index) as i64).rem_euclid(assignment_count as i64) + != 0 { max_index += 1; //safe; m prime below num_participants } @@ -118,7 +118,7 @@ pub fn assignment_fn_inverse( }; if t3 >= participant_count { - continue + continue; } result.push(t3); diff --git a/ceremonies/assignment/src/math.rs b/ceremonies/assignment/src/math.rs index e91e1f62..2aa207a0 100644 --- a/ceremonies/assignment/src/math.rs +++ b/ceremonies/assignment/src/math.rs @@ -40,20 +40,20 @@ pub fn is_coprime(a: u64, b: u64) -> bool { pub fn is_prime(n: u64) -> bool { if n <= 3 { - return n > 1 + return n > 1; } if n % 2 == 0 || n % 3 == 0 { - return false + return false; } if n < 25 { - return true + return true; } let mut i: u64 = 5; let mut j: u64 = 25; while j <= n { let i_plus_two = i.checked_add(2u64).expect("i^2 does not overflow, so i + 2 is safe; qed"); if n % i == 0u64 || n % (i_plus_two) == 0u64 { - return false + return false; } i = i.checked_add(6u64).expect("i^2 does not overflow, so i + 6 is safe; qed"); @@ -61,7 +61,7 @@ pub fn is_prime(n: u64) -> bool { j = i_squared; } else { // if i overflows we can be sure that j <= n does not hold - break + break; } } true @@ -69,15 +69,15 @@ pub fn is_prime(n: u64) -> bool { pub fn get_greatest_common_denominator(a: u64, b: u64) -> u64 { if a == 0 || b == 0 { - return 0 + return 0; } if a == b { - return a + return a; } if a > b { - return get_greatest_common_denominator(a.checked_sub(b).expect("a > b; qed"), b) + return get_greatest_common_denominator(a.checked_sub(b).expect("a > b; qed"), b); } get_greatest_common_denominator(a, b.checked_sub(a).expect("b <= a; qed")) @@ -85,19 +85,19 @@ pub fn get_greatest_common_denominator(a: u64, b: u64) -> u64 { pub fn find_prime_below(mut n: u64) -> u64 { if n <= 2 { - return 2u64 + return 2u64; } if n % 2 == 0 { n = n.checked_sub(1).expect("n > 2; qed"); } while n > 0 { if is_prime(n) { - return n + return n; } if let Some(n_minus_two) = n.checked_sub(2) { n = n_minus_two; } else { - break + break; } } 2u64 @@ -108,11 +108,11 @@ pub fn find_random_coprime_below( random_source: &mut RandomNumberGenerator, ) -> u64 { if upper_bound <= 1 { - return 0 + return 0; } if upper_bound == 2 { - return 1 + return 1; } (1..upper_bound) diff --git a/ceremonies/meetup-validation/src/lib.rs b/ceremonies/meetup-validation/src/lib.rs index 20e2bd23..9437770f 100644 --- a/ceremonies/meetup-validation/src/lib.rs +++ b/ceremonies/meetup-validation/src/lib.rs @@ -83,7 +83,7 @@ fn attestation_graph_is_fully_connected( for (i, mut attestations) in participant_attestations.into_iter().enumerate() { // only consider participants present in the meetup if !legit_participants.contains(&i) { - continue + continue; } attestations.sort(); let mut expected_attestations = legit_participants.clone(); @@ -92,7 +92,7 @@ fn attestation_graph_is_fully_connected( expected_attestations.sort(); if attestations != expected_attestations { - return false + return false; } } true @@ -105,15 +105,15 @@ fn early_rewards_possible( n_confirmed: u32, vote_is_unanimous: bool, ) -> bool { - if vote_is_unanimous && - vote_yields_majority(num_total_participants, n_confirmed) && - num_attestations_matches_vote( + if vote_is_unanimous + && vote_yields_majority(num_total_participants, n_confirmed) + && num_attestations_matches_vote( &legit_participants, &participant_attestations, n_confirmed, ) && attestation_graph_is_fully_connected(legit_participants, participant_attestations) { - return true + return true; } false } @@ -170,7 +170,7 @@ fn get_excluded_participants_num_attestations( for _ in 0..max_iterations { // if all participants were excluded, exit the loop if participants_to_process.is_empty() { - return Ok(excluded_participants) + return Ok(excluded_participants); }; let participants_grouped_by_outgoing_attestations = @@ -217,10 +217,10 @@ fn get_excluded_participants_num_attestations( participants_to_process.retain(|k| !participants_to_exclude.contains(k)); relevant_attestations = filter_attestations(&participants_to_process, relevant_attestations.clone()); - continue + continue; } else { // if all participants are above the threshold and therefore no participants were removed, we exit the loop - break + break; } } Ok(excluded_participants) @@ -240,12 +240,12 @@ fn find_majority_vote( } if n_vote_candidates.is_empty() { - return Err(MeetupValidationError::BallotEmpty) + return Err(MeetupValidationError::BallotEmpty); } // sort by descending vote count n_vote_candidates.sort_by(|a, b| b.1.cmp(&a.1)); if n_vote_candidates.get_or_err(0)?.1 < 3 { - return Err(MeetupValidationError::NoDependableVote) + return Err(MeetupValidationError::NoDependableVote); } let (n_confirmed, vote_count) = n_vote_candidates.get_or_err(0)?; let vote_is_unanimous = n_vote_candidates.len() == 1; @@ -299,7 +299,7 @@ fn group_indices_by_value( ) -> Result, MeetupValidationError> { if let Some(max) = indices.iter().max() { if max >= &values.len() { - return Err(MeetupValidationError::IndexOutOfBounds) + return Err(MeetupValidationError::IndexOutOfBounds); } } diff --git a/ceremonies/meetup-validation/src/tests.rs b/ceremonies/meetup-validation/src/tests.rs index 4fa7fc73..78ff68ed 100644 --- a/ceremonies/meetup-validation/src/tests.rs +++ b/ceremonies/meetup-validation/src/tests.rs @@ -85,11 +85,8 @@ fn get_excluded_participants_num_attestations_works() { (1, ExclusionReason::TooFewOutgoingAttestations), ]; assert_eq!( - get_excluded_participants_num_attestations( - &participants, - participant_attestations, - |n| n - 1 - ) + get_excluded_participants_num_attestations(&participants, participant_attestations, |n| n + - 1) .unwrap(), excluded_participants ); diff --git a/ceremonies/rpc/src/lib.rs b/ceremonies/rpc/src/lib.rs index 0e07270e..7b69d1f0 100644 --- a/ceremonies/rpc/src/lib.rs +++ b/ceremonies/rpc/src/lib.rs @@ -159,7 +159,7 @@ where if !self.offchain_indexing { return Err( Error::OffchainIndexingDisabled("ceremonies_getReputations".to_string()).into() - ) + ); } let cache_key = &reputation_cache_key(&account); @@ -168,12 +168,12 @@ where .map_err(|e| Error::Runtime(e.into()))?; if self.cache_dirty(&reputation_cache_dirty_key(&account)) { - return Ok(self.refresh_reputation_cache(account, ceremony_info, at)?.reputation) + return Ok(self.refresh_reputation_cache(account, ceremony_info, at)?.reputation); } if let Some(reputation_cache_value) = self.get_storage::(cache_key)? { if ceremony_info == reputation_cache_value.ceremony_info { - return Ok(reputation_cache_value.reputation) + return Ok(reputation_cache_value.reputation); } }; diff --git a/ceremonies/src/benchmarking.rs b/ceremonies/src/benchmarking.rs index 6589f6d4..5f2c2aa6 100644 --- a/ceremonies/src/benchmarking.rs +++ b/ceremonies/src/benchmarking.rs @@ -45,7 +45,36 @@ fn test_location() -> Location { fn create_community() -> CommunityIdentifier { let location = test_location(); let bs = bootstrappers::(); - + encointer_scheduler::Pallet::::set_phase_duration( + RawOrigin::Root.into(), + CeremonyPhaseType::Assigning, + 10u32.into(), + ) + .ok(); + encointer_scheduler::Pallet::::set_phase_duration( + RawOrigin::Root.into(), + CeremonyPhaseType::Attesting, + 10u32.into(), + ) + .ok(); + encointer_scheduler::Pallet::::set_phase_duration( + RawOrigin::Root.into(), + CeremonyPhaseType::Registering, + 10u32.into(), + ) + .ok(); + next_phase::(); + next_phase::(); + next_phase::(); + Pallet::::set_inactivity_timeout(RawOrigin::Root.into(), 5).ok(); + Pallet::::set_reputation_lifetime(RawOrigin::Root.into(), 5).ok(); + Pallet::::set_endorsement_tickets_per_bootstrapper(RawOrigin::Root.into(), 1).ok(); + Pallet::::set_endorsement_tickets_per_reputable(RawOrigin::Root.into(), 1).ok(); + Pallet::::set_location_tolerance(RawOrigin::Root.into(), 1000).ok(); + Pallet::::set_time_tolerance(RawOrigin::Root.into(), 1_000_000u32.into()).ok(); + + encointer_communities::Pallet::::set_min_solar_trip_time_s(RawOrigin::Root.into(), 1).ok(); + encointer_communities::Pallet::::set_max_speed_mps(RawOrigin::Root.into(), 83).ok(); encointer_communities::Pallet::::new_community( RawOrigin::Root.into(), location, @@ -125,7 +154,7 @@ where pub fn last_event() -> Option<::RuntimeEvent> { let events = frame_system::Pallet::::events(); if events.len() < 1 { - return None + return None; } let frame_system::EventRecord { event, .. } = &events[events.len() - 1]; Some(event.clone()) diff --git a/ceremonies/src/lib.rs b/ceremonies/src/lib.rs index 80e58b03..c4bbf945 100644 --- a/ceremonies/src/lib.rs +++ b/ceremonies/src/lib.rs @@ -135,7 +135,7 @@ pub mod pallet { }; if Self::is_registered(cid, cindex, &sender) { - return Err(>::ParticipantAlreadyRegistered.into()) + return Err(>::ParticipantAlreadyRegistered.into()); } if let Some(p) = &proof { @@ -154,7 +154,7 @@ pub mod pallet { Error::::AttendanceUnverifiedOrAlreadyUsed ); if Self::verify_attendee_signature(p.clone()).is_err() { - return Err(>::BadProofOfAttendanceSignature.into()) + return Err(>::BadProofOfAttendanceSignature.into()); }; // this reputation must now be burned so it can not be used again @@ -213,7 +213,7 @@ pub mod pallet { Self::remove_participant_from_registry(cid, cindex, &sender)?; Self::register_participant(origin, cid, Some(proof))?; } else { - return Err(>::MustBeNewbieToUpgradeRegistration.into()) + return Err(>::MustBeNewbieToUpgradeRegistration.into()); } Ok(().into()) } @@ -377,8 +377,9 @@ pub mod pallet { match current_phase { CeremonyPhaseType::Registering => cindex -= 1, CeremonyPhaseType::Attesting => (), - CeremonyPhaseType::Assigning => - return Err(>::WrongPhaseForClaimingRewards.into()), + CeremonyPhaseType::Assigning => { + return Err(>::WrongPhaseForClaimingRewards.into()) + }, } let meetup_index = match maybe_meetup_index { @@ -388,7 +389,7 @@ pub mod pallet { }; if >::contains_key((cid, cindex), meetup_index) { - return Err(>::RewardsAlreadyIssued.into()) + return Err(>::RewardsAlreadyIssued.into()); } info!( target: LOG, @@ -464,20 +465,20 @@ pub mod pallet { meetup_index, meetup_result, )); - return Ok(Pays::No.into()) + return Ok(Pays::No.into()); } else { - return error + return error; } }, }; - if current_phase == CeremonyPhaseType::Attesting && - !participant_judgements.early_rewards_possible + if current_phase == CeremonyPhaseType::Attesting + && !participant_judgements.early_rewards_possible { debug!( target: LOG, "early rewards not possible for meetup {:?}, cid: {:?}", meetup_index, cid ); - return Err(>::EarlyRewardsNotPossible.into()) + return Err(>::EarlyRewardsNotPossible.into()); } participants_eligible_for_rewards = participant_judgements.legit; // emit events @@ -573,12 +574,12 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { ::CeremonyMaster::ensure_origin(origin)?; if >::current_phase() != CeremonyPhaseType::Registering { - return Err(>::WrongPhaseForChangingMeetupTimeOffset.into()) + return Err(>::WrongPhaseForChangingMeetupTimeOffset.into()); } // Meetup time offset needs to be in [-8h, 8h] if meetup_time_offset.abs() > 8 * 3600 * 1000 { - return Err(>::InvalidMeetupTimeOffset.into()) + return Err(>::InvalidMeetupTimeOffset.into()); } >::put(meetup_time_offset); @@ -1180,7 +1181,7 @@ impl Pallet { >::insert((cid, cindex), participant_index); ParticipantType::Bootstrapper } else if >::total_issuance(cid) <= 0 { - return Err(Error::::OnlyBootstrappers) + return Err(Error::::OnlyBootstrappers); } else if is_reputable { let participant_index = >::get((cid, cindex)) .checked_add(1) @@ -1217,7 +1218,7 @@ impl Pallet { participant: &T::AccountId, ) -> Result<(), Error> { if >::current_phase() != CeremonyPhaseType::Registering { - return Err(>::WrongPhaseForUnregistering) + return Err(>::WrongPhaseForUnregistering); } let participant_type = Self::get_participant_type((cid, cindex), participant) @@ -1265,10 +1266,10 @@ impl Pallet { cindex: CeremonyIndexType, sender: &T::AccountId, ) -> bool { - >::contains_key((cid, cindex), sender) || - >::contains_key((cid, cindex), sender) || - >::contains_key((cid, cindex), sender) || - >::contains_key((cid, cindex), sender) + >::contains_key((cid, cindex), sender) + || >::contains_key((cid, cindex), sender) + || >::contains_key((cid, cindex), sender) + || >::contains_key((cid, cindex), sender) } /// Will burn the `sender`'s newbie tickets if he has some. @@ -1280,22 +1281,22 @@ impl Pallet { cindex: CeremonyIndexType, sender: &T::AccountId, ) -> Result<(), Error> { - if Self::has_reputation(sender, &cid) && - >::get((cid, cindex), sender) < - Self::endorsement_tickets_per_reputable() + if Self::has_reputation(sender, &cid) + && >::get((cid, cindex), sender) + < Self::endorsement_tickets_per_reputable() { // safe; limited by AMOUNT_NEWBIE_TICKETS >::mutate((cid, cindex), sender, |b| *b += 1); - return Ok(()) + return Ok(()); } - if >::bootstrappers(cid).contains(sender) && - >::get(cid, sender) < - Self::endorsement_tickets_per_bootstrapper() + if >::bootstrappers(cid).contains(sender) + && >::get(cid, sender) + < Self::endorsement_tickets_per_bootstrapper() { // safe; limited by AMOUNT_NEWBIE_TICKETS >::mutate(cid, sender, |b| *b += 1); - return Ok(()) + return Ok(()); } Err(Error::::NoMoreNewbieTickets) @@ -1377,7 +1378,7 @@ impl Pallet { "less than 3 participants available for a meetup. will not assign any meetups for cid {:?}", community_ceremony.0 ); - return Ok(()) + return Ok(()); } info!(target: LOG, "assigning {:} meetups for cid {:?}", num_meetups, community_ceremony.0); @@ -1436,7 +1437,7 @@ impl Pallet { "Number of locations for cid {:?} is {:?}", community_ceremony.0, num_locations ); if num_locations == 0 { - return Err(>::NoLocationsAvailable) + return Err(>::NoLocationsAvailable); } let num_registered_bootstrappers = Self::bootstrapper_count(community_ceremony); @@ -1457,8 +1458,8 @@ impl Pallet { //safe; number of assigned bootstrappers <= max_num_meetups <=num_assigned_bootstrappers + num_reputables let mut seats_left = - max_num_meetups.checked_mul(meetup_multiplier).ok_or(Error::::CheckedMath)? - - num_registered_bootstrappers; + max_num_meetups.checked_mul(meetup_multiplier).ok_or(Error::::CheckedMath)? + - num_registered_bootstrappers; let num_assigned_reputables = min(num_registered_reputables, seats_left); seats_left -= num_assigned_reputables; //safe; given by minimum above @@ -1468,8 +1469,8 @@ impl Pallet { let num_assigned_newbies = min( min(num_registered_newbies, seats_left), - (num_registered_bootstrappers + num_assigned_reputables + num_assigned_endorsees) / - T::MeetupNewbieLimitDivider::get(), //safe; sum equals total + (num_registered_bootstrappers + num_assigned_reputables + num_assigned_endorsees) + / T::MeetupNewbieLimitDivider::get(), //safe; sum equals total ); info!( target: LOG, @@ -1552,16 +1553,16 @@ impl Pallet { participant: &T::AccountId, ) -> Option { if >::contains_key(community_ceremony, participant) { - return Some(ParticipantType::Bootstrapper) + return Some(ParticipantType::Bootstrapper); } if >::contains_key(community_ceremony, participant) { - return Some(ParticipantType::Reputable) + return Some(ParticipantType::Reputable); } if >::contains_key(community_ceremony, participant) { - return Some(ParticipantType::Endorsee) + return Some(ParticipantType::Endorsee); } if >::contains_key(community_ceremony, participant) { - return Some(ParticipantType::Newbie) + return Some(ParticipantType::Newbie); } None } @@ -1584,7 +1585,7 @@ impl Pallet { if participant_index < assignment_count.bootstrappers { (participant_index, assignment.bootstrappers_reputables) } else { - return None + return None; } }, ParticipantType::Reputable => { @@ -1595,7 +1596,7 @@ impl Pallet { assignment.bootstrappers_reputables, ) } else { - return None + return None; } }, @@ -1604,7 +1605,7 @@ impl Pallet { if participant_index < assignment_count.endorsees { (participant_index, assignment.endorsees) } else { - return None + return None; } }, @@ -1613,7 +1614,7 @@ impl Pallet { if participant_index < assignment_count.newbies { (participant_index, assignment.newbies) } else { - return None + return None; } }, }; @@ -1633,7 +1634,7 @@ impl Pallet { target: LOG, "Invalid meetup index {}, meetup_count is {}", meetup_index, meetup_count ); - return Err(>::InvalidMeetupIndex) + return Err(>::InvalidMeetupIndex); } //safe; meetup index conversion from 1 based to 0 based @@ -1732,7 +1733,7 @@ impl Pallet { // this function only works during ATTESTING, so we're keeping it for private use pub(crate) fn get_meetup_time(location: Location) -> Option { if !(>::current_phase() == CeremonyPhaseType::Attesting) { - return None + return None; } let duration = @@ -1854,20 +1855,20 @@ impl Pallet { for attestee in attestations.iter() { if attestee == &participant { warn!(target: LOG, "ignoring attestation for self: {:?}", attestee); - continue + continue; }; if !meetup_participants.contains(attestee) { warn!( target: LOG, "ignoring attestation that isn't a meetup participant: {:?}", attestee ); - continue + continue; }; verified_attestees.insert(0, attestee.clone()) } if verified_attestees.is_empty() { - return Err(>::NoValidAttestations) + return Err(>::NoValidAttestations); } let count = >::get((cid, cindex)); @@ -1905,7 +1906,7 @@ impl Pallet { if Self::participant_reputation((*cid, cindex.saturating_sub(i)), participant) .is_verified() { - return true + return true; } } false @@ -1919,7 +1920,7 @@ impl Pallet { for i in 0..=reputation_lifetime { let cindex = cc.1.saturating_sub(i); if >::contains_key((cc.0, cindex), participant) { - return Some(cindex) + return Some(cindex); } } None @@ -1932,7 +1933,7 @@ impl Pallet { ) -> bool { let current_cindex = >::current_ceremony_index(); if cindex < current_cindex.saturating_sub(Self::reputation_lifetime()) { - return false + return false; } >::get((*cid, cindex), account_id).is_verified() } diff --git a/ceremonies/src/migrations.rs b/ceremonies/src/migrations.rs index de3d385a..1f9e38d2 100644 --- a/ceremonies/src/migrations.rs +++ b/ceremonies/src/migrations.rs @@ -49,7 +49,7 @@ pub mod v1 { "skipping on_runtime_upgrade: executed on wrong storage version.\ Expected version 0" ); - return weight + return weight; } // we do not actually migrate any data, because it seems that the storage representation of Vec and BoundedVec is the same. diff --git a/ceremonies/src/tests.rs b/ceremonies/src/tests.rs index 7170d417..620fdf33 100644 --- a/ceremonies/src/tests.rs +++ b/ceremonies/src/tests.rs @@ -78,12 +78,12 @@ fn correct_meetup_time(cid: &CommunityIdentifier, mindex: MeetupIndexType) -> Mo .lon .lossy_into(); - let t = GENESIS_TIME - GENESIS_TIME.rem(ONE_DAY) + - cindex * EncointerScheduler::phase_durations(CeremonyPhaseType::Registering) + - cindex * EncointerScheduler::phase_durations(CeremonyPhaseType::Assigning) + - (cindex - 1) * EncointerScheduler::phase_durations(CeremonyPhaseType::Attesting) + - ONE_DAY / 2 - - (mlon / 360.0 * ONE_DAY as f64) as u64; + let t = GENESIS_TIME - GENESIS_TIME.rem(ONE_DAY) + + cindex * EncointerScheduler::phase_durations(CeremonyPhaseType::Registering) + + cindex * EncointerScheduler::phase_durations(CeremonyPhaseType::Assigning) + + (cindex - 1) * EncointerScheduler::phase_durations(CeremonyPhaseType::Attesting) + + ONE_DAY / 2 + - (mlon / 360.0 * ONE_DAY as f64) as u64; let time = t as i64 + EncointerCeremonies::meetup_time_offset() as i64; time as u64 @@ -1653,12 +1653,12 @@ fn get_meetup_time_works(lat_micro: i64, lon_micro: i64, meetup_time_offset: i64 assert_eq!(EncointerScheduler::current_phase(), CeremonyPhaseType::Attesting); let mtime = if lon_micro >= 0 { - GENESIS_TIME - GENESIS_TIME.rem(ONE_DAY) + 2 * ONE_DAY + ONE_DAY / 2 - - (lon_micro * ONE_DAY as i64 / 360_000_000) as u64 + GENESIS_TIME - GENESIS_TIME.rem(ONE_DAY) + 2 * ONE_DAY + ONE_DAY / 2 + - (lon_micro * ONE_DAY as i64 / 360_000_000) as u64 } else { - GENESIS_TIME - GENESIS_TIME.rem(ONE_DAY) + - 2 * ONE_DAY + ONE_DAY / 2 + - (lon_micro.abs() * ONE_DAY as i64 / 360_000_000) as u64 + GENESIS_TIME - GENESIS_TIME.rem(ONE_DAY) + + 2 * ONE_DAY + ONE_DAY / 2 + + (lon_micro.abs() * ONE_DAY as i64 / 360_000_000) as u64 }; let adjusted_mtime = mtime as i64 + meetup_time_offset; diff --git a/communities/Cargo.toml b/communities/Cargo.toml index d6827a70..7a4399dd 100644 --- a/communities/Cargo.toml +++ b/communities/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-encointer-communities" -version = "3.0.2" +version = "3.0.3" authors = ["Encointer Association "] edition = "2021" description = "Communities pallet for the Encointer blockchain runtime" @@ -18,7 +18,7 @@ scale-info = { version = "2.10.0", default-features = false } # local deps encointer-balances = { package = "pallet-encointer-balances", path = "../balances", default-features = false, version = "3.0.2" } encointer-primitives = { path = "../primitives", default-features = false, features = ["serde_derive"], version = "3.0.2" } -encointer-scheduler = { package = "pallet-encointer-scheduler", path = "../scheduler", default-features = false, version = "3.0.2" } +encointer-scheduler = { package = "pallet-encointer-scheduler", path = "../scheduler", default-features = false, version = "3.0.3" } # substrate deps frame-benchmarking = { default-features = false, optional = true, version = "25.0.0" } diff --git a/communities/rpc/src/lib.rs b/communities/rpc/src/lib.rs index a340afea..07c730a6 100644 --- a/communities/rpc/src/lib.rs +++ b/communities/rpc/src/lib.rs @@ -149,7 +149,7 @@ where { fn communities_get_all(&self, at: Option<::Hash>) -> RpcResult> { if !self.offchain_indexing { - return Err(Error::OffchainIndexingDisabled("communities_getAll".to_string()).into()) + return Err(Error::OffchainIndexingDisabled("communities_getAll".to_string()).into()); } if self.cache_dirty() { @@ -171,7 +171,7 @@ where at: Option<::Hash>, ) -> RpcResult> { if !self.offchain_indexing { - return Err(Error::OffchainIndexingDisabled("communities_getAll".to_string()).into()) + return Err(Error::OffchainIndexingDisabled("communities_getAll".to_string()).into()); } if self.cache_dirty() { diff --git a/communities/src/benchmarking.rs b/communities/src/benchmarking.rs index 0bf4f3f7..7fa67169 100644 --- a/communities/src/benchmarking.rs +++ b/communities/src/benchmarking.rs @@ -42,6 +42,8 @@ fn setup_test_community() -> ( Option, Option, ) { + MaxSpeedMps::::put(83); + MinSolarTripTimeS::::put(1); let bootstrappers: Vec = (0..10).map(|n| account("dummy name", n, n)).collect(); let mut community_metadata = CommunityMetadataType::default(); community_metadata.name = PalletString::from_str("20charsaaaaaaaaaaaaa").unwrap(); @@ -60,7 +62,7 @@ fn setup_test_community() -> ( )); let cid = CommunityIdentifier::new(get_location(0).clone(), bootstrappers.clone()).unwrap(); - return (cid, bootstrappers, community_metadata, demurrage, nominal_income) + return (cid, bootstrappers, community_metadata, demurrage, nominal_income); } parameter_types! { diff --git a/communities/src/lib.rs b/communities/src/lib.rs index 5185fc44..1ffb515b 100644 --- a/communities/src/lib.rs +++ b/communities/src/lib.rs @@ -556,10 +556,10 @@ impl Pallet { } pub fn is_valid_location(loc: &Location) -> bool { - (loc.lat < MAX_ABS_LATITUDE) & - (loc.lat > -MAX_ABS_LATITUDE) & - (loc.lon < DATELINE_LON) & - (loc.lon > -DATELINE_LON) + (loc.lat < MAX_ABS_LATITUDE) + & (loc.lat > -MAX_ABS_LATITUDE) + & (loc.lon < DATELINE_LON) + & (loc.lon > -DATELINE_LON) } pub fn haversine_distance(a: &Location, b: &Location) -> u32 { @@ -605,15 +605,15 @@ impl Pallet { let bucket_max_lon = bucket_center_lon + bucket_lon_error; //check if northern neighbour bucket needs to be included - if Self::solar_trip_time(&Location { lon: location.lon, lat: bucket_max_lat }, location) < - Self::min_solar_trip_time_s() + if Self::solar_trip_time(&Location { lon: location.lon, lat: bucket_max_lat }, location) + < Self::min_solar_trip_time_s() { relevant_neighbor_buckets.push(neighbors.n) } //check if southern neighbour bucket needs to be included - if Self::solar_trip_time(&Location { lon: location.lon, lat: bucket_min_lat }, location) < - Self::min_solar_trip_time_s() + if Self::solar_trip_time(&Location { lon: location.lon, lat: bucket_min_lat }, location) + < Self::min_solar_trip_time_s() { relevant_neighbor_buckets.push(neighbors.s) } @@ -635,43 +635,43 @@ impl Pallet { // traverse 1 bucket horizontally //check if north eastern neighbour bucket needs to be included - if Self::solar_trip_time(&Location { lon: bucket_max_lon, lat: bucket_max_lat }, location) < - Self::min_solar_trip_time_s() + if Self::solar_trip_time(&Location { lon: bucket_max_lon, lat: bucket_max_lat }, location) + < Self::min_solar_trip_time_s() { relevant_neighbor_buckets.push(neighbors.ne) } //check if eastern neighbour bucket needs to be included - if Self::solar_trip_time(&Location { lon: bucket_max_lon, lat: location.lat }, location) < - Self::min_solar_trip_time_s() + if Self::solar_trip_time(&Location { lon: bucket_max_lon, lat: location.lat }, location) + < Self::min_solar_trip_time_s() { relevant_neighbor_buckets.push(neighbors.e) } //check if south eastern neighbour bucket needs to be included - if Self::solar_trip_time(&Location { lon: bucket_max_lon, lat: bucket_min_lat }, location) < - Self::min_solar_trip_time_s() + if Self::solar_trip_time(&Location { lon: bucket_max_lon, lat: bucket_min_lat }, location) + < Self::min_solar_trip_time_s() { relevant_neighbor_buckets.push(neighbors.se) } //check if north western neighbour bucket needs to be included - if Self::solar_trip_time(&Location { lon: bucket_min_lon, lat: bucket_max_lat }, location) < - Self::min_solar_trip_time_s() + if Self::solar_trip_time(&Location { lon: bucket_min_lon, lat: bucket_max_lat }, location) + < Self::min_solar_trip_time_s() { relevant_neighbor_buckets.push(neighbors.nw) } //check if western neighbour bucket needs to be included - if Self::solar_trip_time(&Location { lon: bucket_min_lon, lat: location.lat }, location) < - Self::min_solar_trip_time_s() + if Self::solar_trip_time(&Location { lon: bucket_min_lon, lat: location.lat }, location) + < Self::min_solar_trip_time_s() { relevant_neighbor_buckets.push(neighbors.w) } //check if south western neighbour bucket needs to be included - if Self::solar_trip_time(&Location { lon: bucket_min_lon, lat: bucket_min_lat }, location) < - Self::min_solar_trip_time_s() + if Self::solar_trip_time(&Location { lon: bucket_min_lon, lat: bucket_min_lat }, location) + < Self::min_solar_trip_time_s() { relevant_neighbor_buckets.push(neighbors.sw) } @@ -700,7 +700,7 @@ impl Pallet { let dateline_proxy = Location { lat: location.lat, lon: DATELINE_LON }; if Self::haversine_distance(location, &dateline_proxy) < DATELINE_DISTANCE_M { warn!(target: LOG, "location too close to dateline: {:?}", location); - return Err(>::MinimumDistanceViolationToDateLine)? + return Err(>::MinimumDistanceViolationToDateLine)?; } let nearby_locations = Self::get_nearby_locations(location)?; diff --git a/communities/src/migrations.rs b/communities/src/migrations.rs index bb9a8ad2..4d3b01b7 100644 --- a/communities/src/migrations.rs +++ b/communities/src/migrations.rs @@ -261,7 +261,7 @@ pub mod v2 { target: TARGET, "skipping on_runtime_upgrade: executed on wrong storage version." ); - return T::DbWeight::get().reads(1) + return T::DbWeight::get().reads(1); } if onchain_version == StorageVersion::new(0) { CommunityMetadata::::translate::( diff --git a/communities/src/tests.rs b/communities/src/tests.rs index 8afb258a..a0d52c51 100644 --- a/communities/src/tests.rs +++ b/communities/src/tests.rs @@ -121,8 +121,8 @@ fn haversine_distance_works() { // pole to pole assert_abs_diff_eq!( - f64::from(EncointerCommunities::haversine_distance(&NORTH_POLE, &SOUTH_POLE) as i32) * - 0.001, + f64::from(EncointerCommunities::haversine_distance(&NORTH_POLE, &SOUTH_POLE) as i32) + * 0.001, 12742.0, epsilon = 0.1 ); diff --git a/democracy/src/lib.rs b/democracy/src/lib.rs index 21f76409..7da2150a 100644 --- a/democracy/src/lib.rs +++ b/democracy/src/lib.rs @@ -160,7 +160,7 @@ pub mod pallet { proposal_action: ProposalAction, ) -> DispatchResultWithPostInfo { if Self::enactment_queue(proposal_action.get_identifier()).is_some() { - return Err(Error::::ProposalWaitingForEnactment.into()) + return Err(Error::::ProposalWaitingForEnactment.into()); } let _sender = ensure_signed(origin)?; let cindex = >::current_ceremony_index(); @@ -244,8 +244,8 @@ pub mod pallet { Ok(((proposal .start_cindex .saturating_sub(reputation_lifetime) - .saturating_add(T::ProposalLifetimeCycles::get()))..= - (proposal.start_cindex.saturating_sub(2))) + .saturating_add(T::ProposalLifetimeCycles::get())) + ..=(proposal.start_cindex.saturating_sub(2))) .collect::>()) } /// Returns the reputations that @@ -271,16 +271,16 @@ pub mod pallet { for community_ceremony in reputations { if !Self::relevant_cindexes(proposal_id)?.contains(&community_ceremony.1) { - continue + continue; } if let Some(cid) = maybe_cid { if community_ceremony.0 != cid { - continue + continue; } } if >::contains_key(proposal_id, (account_id, community_ceremony)) { - continue + continue; } if >::validate_reputation( account_id, @@ -379,8 +379,8 @@ pub mod pallet { sqrt::(U64F64::from_num(t)).map_err(|_| >::AQBError)?; let one = U64F64::from_num(1); - Ok(U64F64::from_num(a) > - sqrt_e + Ok(U64F64::from_num(a) + > sqrt_e .checked_mul(sqrt_t) .ok_or(>::AQBError)? .checked_div( @@ -399,13 +399,13 @@ pub mod pallet { let turnout_permill = (tally.turnout * 1000).checked_div(electorate).unwrap_or(0); if turnout_permill < T::MinTurnout::get() { - return Ok(false) + return Ok(false); } let positive_turnout_bias = Self::positive_turnout_bias(electorate, tally.turnout, tally.ayes); if let Ok(passing) = positive_turnout_bias { if passing { - return Ok(true) + return Ok(true); } } Ok(false) diff --git a/democracy/src/tests.rs b/democracy/src/tests.rs index d0df6760..b7a5c1a2 100644 --- a/democracy/src/tests.rs +++ b/democracy/src/tests.rs @@ -36,7 +36,7 @@ use test_utils::{ }; fn create_cid() -> CommunityIdentifier { - return register_test_community::(None, 0.0, 0.0) + return register_test_community::(None, 0.0, 0.0); } fn alice() -> AccountId { diff --git a/faucet/Cargo.toml b/faucet/Cargo.toml index 09776b20..a271e73d 100644 --- a/faucet/Cargo.toml +++ b/faucet/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-encointer-faucet" -version = "3.0.2" +version = "3.0.3" authors = ["Encointer Association "] edition = "2021" description = "Faucet pallet for the Encointer blockchain runtime" @@ -17,7 +17,7 @@ log = { version = "0.4.20", default-features = false } scale-info = { version = "2.10.0", default-features = false } # local deps -encointer-communities = { package = "pallet-encointer-communities", path = "../communities", default-features = false, version = "3.0.2" } +encointer-communities = { package = "pallet-encointer-communities", path = "../communities", default-features = false, version = "3.0.3" } encointer-primitives = { path = "../primitives", default-features = false, features = ["serde_derive"], version = "3.0.2" } encointer-reputation-commitments = { package = "pallet-encointer-reputation-commitments", path = "../reputation-commitments", default-features = false, version = "3.0.2" } diff --git a/faucet/src/benchmarking.rs b/faucet/src/benchmarking.rs index 5b119788..e33569a0 100644 --- a/faucet/src/benchmarking.rs +++ b/faucet/src/benchmarking.rs @@ -32,6 +32,8 @@ fn test_location() -> Location { fn create_community() -> CommunityIdentifier { let location = test_location(); let bs = bootstrappers::(); + encointer_communities::Pallet::::set_min_solar_trip_time_s(RawOrigin::Root.into(), 1).ok(); + encointer_communities::Pallet::::set_max_speed_mps(RawOrigin::Root.into(), 83).ok(); encointer_communities::Pallet::::new_community( RawOrigin::Root.into(), diff --git a/faucet/src/lib.rs b/faucet/src/lib.rs index 325f3d90..3771391a 100644 --- a/faucet/src/lib.rs +++ b/faucet/src/lib.rs @@ -103,7 +103,7 @@ pub mod pallet { if let Some(wl) = whitelist.clone() { for cid in &wl { if !all_communities.contains(cid) { - return Err(>::InvalidCommunityIdentifierInWhitelist.into()) + return Err(>::InvalidCommunityIdentifierInWhitelist.into()); } } } @@ -122,7 +122,7 @@ pub mod pallet { .expect("32 bytes can always construct an AccountId32"); if >::contains_key(&faucet_account) { - return Err(>::FaucetAlreadyExists.into()) + return Err(>::FaucetAlreadyExists.into()); } ::Currency::reserve_named( @@ -163,7 +163,7 @@ pub mod pallet { if let Some(wl) = faucet.whitelist { if !wl.contains(&cid) { - return Err(>::CommunityNotInWhitelist.into()) + return Err(>::CommunityNotInWhitelist.into()); } } @@ -232,8 +232,8 @@ pub mod pallet { ensure!(from == faucet.creator, >::NotCreator); ensure!( - ::Currency::free_balance(&faucet_account) < - faucet.drip_amount.saturating_mul(2u32.saturated_into()), + ::Currency::free_balance(&faucet_account) + < faucet.drip_amount.saturating_mul(2u32.saturated_into()), >::FaucetNotEmpty ); diff --git a/faucet/src/mock.rs b/faucet/src/mock.rs index 5e8b8466..8ce0423f 100644 --- a/faucet/src/mock.rs +++ b/faucet/src/mock.rs @@ -93,7 +93,7 @@ pub struct MulBy(PhantomData); impl> ConversionFromAssetBalance for MulBy { type Error = (); fn from_asset_balance(balance: u64, _asset_id: u32) -> Result { - return balance.checked_mul(N::get()).ok_or(()) + return balance.checked_mul(N::get()).ok_or(()); } #[cfg(feature = "runtime-benchmarks")] fn ensure_successful(_: u32) {} diff --git a/faucet/src/tests.rs b/faucet/src/tests.rs index 8e0e7344..7cf696cd 100644 --- a/faucet/src/tests.rs +++ b/faucet/src/tests.rs @@ -45,7 +45,7 @@ fn new_faucet( if let mock::RuntimeEvent::EncointerFaucet(Event::FaucetCreated(faucet_account, _)) = last_event::().unwrap() { - return faucet_account + return faucet_account; } else { panic!("Faucet not found"); } diff --git a/primitives/core/src/bs58_verify.rs b/primitives/core/src/bs58_verify.rs index 9c61cc10..315d345b 100644 --- a/primitives/core/src/bs58_verify.rs +++ b/primitives/core/src/bs58_verify.rs @@ -56,11 +56,11 @@ impl Bs58verify { pub fn verify(bytes: &[u8]) -> Result<(), Bs58Error> { for (i, c) in bytes.iter().enumerate() { if *c > 127 { - return Err(Bs58Error::NonAsciiCharacter(i as u8)) + return Err(Bs58Error::NonAsciiCharacter(i as u8)); } if Self::BITCOIN_DECODE_MAP[*c as usize] as usize == 0xFF { - return Err(Bs58Error::NonBs58Character(i as u8)) + return Err(Bs58Error::NonBs58Character(i as u8)); } } Ok(()) diff --git a/primitives/core/src/random_number_generator.rs b/primitives/core/src/random_number_generator.rs index 494ef4d5..cd83f986 100644 --- a/primitives/core/src/random_number_generator.rs +++ b/primitives/core/src/random_number_generator.rs @@ -76,7 +76,7 @@ impl RandomNumberGenerator { self.offset += needed as u32; let raw = u32::decode(&mut TrailingZeroInput::new(data)).unwrap_or(0); if raw <= top { - break if max < u32::MAX { raw % (max + 1) } else { raw } + break if max < u32::MAX { raw % (max + 1) } else { raw }; } } } diff --git a/primitives/src/balances.rs b/primitives/src/balances.rs index a71cb8d2..ce006e75 100644 --- a/primitives/src/balances.rs +++ b/primitives/src/balances.rs @@ -87,11 +87,11 @@ where ) -> BalanceEntry { if self.last_update == current_block_number { // Nothing to be done, as no time elapsed. - return self + return self; } if self.principal.eq(&0i16) { - return Self { principal: self.principal, last_update: current_block_number } + return Self { principal: self.principal, last_update: current_block_number }; } let elapsed_blocks = @@ -207,7 +207,7 @@ impl Convert for EncointerBalanceConverter { #[allow(non_snake_case)] pub fn to_U64F64(source: I64F64) -> Option { if source.is_negative() { - return None + return None; } // Safe conversion because we made sure that it is not negative above. diff --git a/primitives/src/common.rs b/primitives/src/common.rs index 0fe71575..93c6973b 100644 --- a/primitives/src/common.rs +++ b/primitives/src/common.rs @@ -58,7 +58,7 @@ pub type BoundedIpfsCid = PalletString; pub fn validate_ascii(bytes: &[u8]) -> Result<(), u8> { for (i, c) in bytes.iter().enumerate() { if *c > 127 { - return Err(i as u8) + return Err(i as u8); } } Ok(()) @@ -70,7 +70,7 @@ pub const MAX_HASH_SIZE: usize = 46; pub fn validate_ipfs_cid(cid: &BoundedIpfsCid) -> Result<(), IpfsValidationError> { if cid.len() != MAX_HASH_SIZE { - return Err(IpfsValidationError::InvalidLength(cid.len() as u8)) + return Err(IpfsValidationError::InvalidLength(cid.len() as u8)); } Bs58verify::verify(cid.as_bytes_or_noop()).map_err(IpfsValidationError::InvalidBase58) } diff --git a/primitives/src/communities.rs b/primitives/src/communities.rs index a5455dc5..058b27f5 100644 --- a/primitives/src/communities.rs +++ b/primitives/src/communities.rs @@ -77,7 +77,7 @@ pub enum RangeError { /// zero is legit as it effectively disables demurrage pub fn validate_demurrage(demurrage: &Demurrage) -> Result<(), RangeError> { if demurrage < &Demurrage::from_num(0) { - return Err(RangeError::LessThanZero) + return Err(RangeError::LessThanZero); } // Just some safeguarding against overflows, but 1 is already a very high value: @@ -86,7 +86,7 @@ pub fn validate_demurrage(demurrage: &Demurrage) -> Result<(), RangeError> { // // So the community does still have the choice of a huge demurrage. if demurrage > &Demurrage::from_num(1) { - return Err(RangeError::TooHigh { limit: 1 }) + return Err(RangeError::TooHigh { limit: 1 }); } Ok(()) } @@ -185,8 +185,9 @@ impl FromStr for CommunityIdentifier { fn decorate_bs58_err(err: bs58::decode::Error) -> bs58::decode::Error { use bs58::decode::Error as Bs58Err; match err { - Bs58Err::InvalidCharacter { character, index } => - Bs58Err::InvalidCharacter { character, index: index + 5 }, + Bs58Err::InvalidCharacter { character, index } => { + Bs58Err::InvalidCharacter { character, index: index + 5 } + }, err => err, } } @@ -319,19 +320,19 @@ impl CommunityMetadata { validate_ipfs_cid(&self.assets).map_err(CommunityMetadataError::InvalidIpfsCid)?; if self.name.len() > 20 { - return Err(CommunityMetadataError::TooManyCharactersInName(self.name.len() as u8)) + return Err(CommunityMetadataError::TooManyCharactersInName(self.name.len() as u8)); } if self.symbol.len() != 3 { return Err(CommunityMetadataError::InvalidAmountCharactersInSymbol( self.symbol.len() as u8 - )) + )); } if let Some(u) = &self.url { validate_ascii(u.as_bytes_or_noop()).map_err(CommunityMetadataError::InvalidAscii)?; if u.len() >= 20 { - return Err(CommunityMetadataError::TooManyCharactersInUrl(u.len() as u8)) + return Err(CommunityMetadataError::TooManyCharactersInUrl(u.len() as u8)); } } @@ -423,8 +424,8 @@ mod tests { Degree, Demurrage, Location, PalletString, RangeError, }, }; + use frame_support::assert_err; use sp_std::str::FromStr; - use std::assert_matches::assert_matches; #[test] fn demurrage_smaller_0_fails() { @@ -508,8 +509,8 @@ mod tests { #[test] fn invalid_cid_from_str_errs() { - assert_matches!( - CommunityIdentifier::from_str("gbsuv7YXq9l").unwrap_err(), + assert_err!( + CommunityIdentifier::from_str("gbsuv7YXq9l"), bs58::decode::Error::InvalidCharacter { character: 'l', index: 10 } ) } diff --git a/primitives/src/democracy.rs b/primitives/src/democracy.rs index 9fe88183..ad833edc 100644 --- a/primitives/src/democracy.rs +++ b/primitives/src/democracy.rs @@ -68,10 +68,12 @@ impl ProposalAction { pub fn get_identifier(self) -> ProposalActionIdentifier { match self { - ProposalAction::UpdateNominalIncome(cid, _) => - ProposalActionIdentifier::UpdateNominalIncome(cid), - ProposalAction::SetInactivityTimeout(_) => - ProposalActionIdentifier::SetInactivityTimeout, + ProposalAction::UpdateNominalIncome(cid, _) => { + ProposalActionIdentifier::UpdateNominalIncome(cid) + }, + ProposalAction::SetInactivityTimeout(_) => { + ProposalActionIdentifier::SetInactivityTimeout + }, } } } diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 6984cf25..687c38c9 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -15,7 +15,6 @@ // along with Encointer. If not, see . #![cfg_attr(not(feature = "std"), no_std)] -#![cfg_attr(test, feature(assert_matches))] pub mod balances; pub mod bazaar; diff --git a/reputation-commitments/src/lib.rs b/reputation-commitments/src/lib.rs index 0724cffe..4afb80ef 100644 --- a/reputation-commitments/src/lib.rs +++ b/reputation-commitments/src/lib.rs @@ -105,17 +105,17 @@ pub mod pallet { commitment_hash: Option, ) -> Result<(), Error> { if !>::contains_key(purpose) { - return Err(>::InexistentPurpose) + return Err(>::InexistentPurpose); } if !>::participant_reputation((cid, cindex), account) .is_verified() { - return Err(>::NoReputation) + return Err(>::NoReputation); } if >::contains_key((cid, cindex), (purpose, &account)) { - return Err(>::AlreadyCommited) + return Err(>::AlreadyCommited); } >::insert((cid, cindex), (purpose, &account), commitment_hash); diff --git a/rust-toolchain.toml b/rust-toolchain.toml index c9719f47..8dca45a8 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "nightly-2023-07-18" +channel = "stable" profile = "default" # include rustfmt, clippy targets = ["wasm32-unknown-unknown"] diff --git a/scheduler/Cargo.toml b/scheduler/Cargo.toml index f707cb3a..6e490918 100644 --- a/scheduler/Cargo.toml +++ b/scheduler/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-encointer-scheduler" -version = "3.0.2" +version = "3.0.3" authors = ["Encointer Association "] edition = "2021" description = "Scheduler pallet for the Encointer blockchain runtime" diff --git a/scheduler/src/benchmarking.rs b/scheduler/src/benchmarking.rs index c12a44f2..1b6ac1a9 100644 --- a/scheduler/src/benchmarking.rs +++ b/scheduler/src/benchmarking.rs @@ -6,8 +6,29 @@ use crate::Pallet as Scheduler; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite}; use frame_system::RawOrigin; +fn default_phase_durations() { + Pallet::::set_phase_duration( + RawOrigin::Root.into(), + CeremonyPhaseType::Assigning, + 10u32.into(), + ) + .ok(); + Pallet::::set_phase_duration( + RawOrigin::Root.into(), + CeremonyPhaseType::Attesting, + 10u32.into(), + ) + .ok(); + Pallet::::set_phase_duration( + RawOrigin::Root.into(), + CeremonyPhaseType::Registering, + 10u32.into(), + ) + .ok(); +} benchmarks! { next_phase { + default_phase_durations::(); crate::CurrentPhase::::put(CeremonyPhaseType::Attesting); }: _(RawOrigin::Root) verify { @@ -15,6 +36,7 @@ benchmarks! { } push_by_one_day { + default_phase_durations::(); let current_timestamp = crate::NextPhaseTimestamp::::get(); }: _(RawOrigin::Root) verify { diff --git a/scheduler/src/lib.rs b/scheduler/src/lib.rs index 5f426956..732bb003 100644 --- a/scheduler/src/lib.rs +++ b/scheduler/src/lib.rs @@ -227,9 +227,9 @@ impl Pallet { // 1. when the chain bootstraps and cycle duration is smaller than 24h, phases would cycle with every block until catched up // 2. when next_phase() is used, we would introduce long idle phases because next_phase_timestamp would be pushed furhter and further into the future fn resync_and_set_next_phase_timestamp(tnext: T::Moment) -> DispatchResult { - let cycle_duration = >::get(CeremonyPhaseType::Registering) + - >::get(CeremonyPhaseType::Assigning) + - >::get(CeremonyPhaseType::Attesting); + let cycle_duration = >::get(CeremonyPhaseType::Registering) + + >::get(CeremonyPhaseType::Assigning) + + >::get(CeremonyPhaseType::Attesting); let now = >::now(); let tnext = if tnext < now { @@ -237,14 +237,14 @@ impl Pallet { if let Some(n) = gap.checked_div(&cycle_duration) { tnext.saturating_add((cycle_duration).saturating_mul(n + T::Moment::one())) } else { - return Err(>::DivisionByZero.into()) + return Err(>::DivisionByZero.into()); } } else { let gap = tnext - now; if let Some(n) = gap.checked_div(&cycle_duration) { tnext.saturating_sub(cycle_duration.saturating_mul(n)) } else { - return Err(>::DivisionByZero.into()) + return Err(>::DivisionByZero.into()); } }; >::put(tnext); diff --git a/test-utils/src/helpers.rs b/test-utils/src/helpers.rs index 217538c3..7c7d02fe 100644 --- a/test-utils/src/helpers.rs +++ b/test-utils/src/helpers.rs @@ -38,7 +38,7 @@ pub fn bootstrappers() -> Vec { ] .iter() .map(|k| k.pair()) - .collect() + .collect(); } /// register a simple test community with a specified location and defined bootstrappers @@ -88,7 +88,7 @@ pub fn last_event() -> Option { pub fn event_at_index(index: usize) -> Option { let events = frame_system::Pallet::::events(); if events.len() < index { - return None + return None; } let frame_system::EventRecord { event, .. } = &events[index]; Some(event.clone()) @@ -99,7 +99,7 @@ pub fn event_deposited(desired_event: T::RuntimeEvent) for eventrec in events.iter() { let frame_system::EventRecord { event, .. } = eventrec; if *event == desired_event { - return true + return true; } } false