diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c832b2b4..a25471c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: os: [ ubuntu-latest ] check: [ cargo build --release, cargo test --all --features runtime-benchmarks --features try-runtime, - cargo +nightly fmt --all -- --check, + cargo +nightly-2024-04-14 fmt --all -- --check, cargo clippy --all-features -- -D warnings ] steps: @@ -36,7 +36,8 @@ jobs: run: sudo apt-get install protobuf-compiler - name: Install nightly toolchain - run: rustup toolchain install nightly --profile minimal --component rustfmt + # align nightly version with https://github.com/polkadot-fellows/runtimes/blob/7157d41176bebf128aa2e29e72ed184844446b19/.github/env#L2C22-L2C32 + run: rustup toolchain install nightly-2024-04-14 --profile minimal --component rustfmt - name: Setup Rust toolchain run: rustup show diff --git a/rustfmt.toml b/.rustfmt.toml similarity index 69% rename from rustfmt.toml rename to .rustfmt.toml index 6005fb82..54fac309 100644 --- a/rustfmt.toml +++ b/.rustfmt.toml @@ -1,4 +1,6 @@ +# align with https://github.com/polkadot-fellows/runtimes/blob/main/.rustfmt.toml # Basic +edition = "2021" hard_tabs = true max_width = 100 use_small_heuristics = "Max" @@ -17,4 +19,7 @@ match_arm_blocks = false match_block_trailing_comma = true trailing_comma = "Vertical" trailing_semicolon = false -use_field_init_shorthand = true \ No newline at end of file +use_field_init_shorthand = true +# Format comments +comment_width = 100 +wrap_comments = true \ No newline at end of file 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..9e087734 100644 --- a/balances/src/lib.rs +++ b/balances/src/lib.rs @@ -42,7 +42,8 @@ const LOG: &str = "encointer"; /// ``` /// This needs to be negated in the formula! // FIXME: how to define negative hex literal? -//pub const DemurrageRate: BalanceType = BalanceType::from_bits(0x0000000000000000000001E3F0A8A973_i128); +//pub const DemurrageRate: BalanceType = +// BalanceType::from_bits(0x0000000000000000000001E3F0A8A973_i128); pub use pallet::*; mod impl_fungibles; @@ -133,8 +134,8 @@ pub mod pallet { /// /// [CC]: 1 Unit of Community Currency /// NI: Nominal Income. Unit = [CC] - /// FCF: Fee Conversion Factor. Unit = [1/ KKSM] <- Kilo-KSM to be able to adjust fee factor in both ways. - /// CB: Balance in Community Currency [CC] + /// FCF: Fee Conversion Factor. Unit = [1/ KKSM] <- Kilo-KSM to be able to adjust fee factor + /// in both ways. CB: Balance in Community Currency [CC] /// /// The following equation should hold for fee design: /// KSM * FCF * NI = CB -> FCF = CB / (NI * KSM) @@ -278,7 +279,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 +290,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 +353,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/balances/src/weights.rs b/balances/src/weights.rs index 4997cf25..162a8027 100644 --- a/balances/src/weights.rs +++ b/balances/src/weights.rs @@ -36,7 +36,8 @@ limitations under the License. // --wasm-execution=compiled // --heap-pages=4096 // --output=runtime/src/weights/pallet_encointer_balances.rs -// --template=/Users/pigu/Dropbox/DATA/Documents/solidbit/kunden/encointer/code/repos/encointer-node/scripts/frame-weight-template-full-info.hbs +// --template=/Users/pigu/Dropbox/DATA/Documents/solidbit/kunden/encointer/code/repos/ +// encointer-node/scripts/frame-weight-template-full-info.hbs #![allow(unused_parens)] #![allow(unused_imports)] @@ -54,7 +55,8 @@ pub trait WeightInfo { fn set_fee_conversion_factor() -> Weight; } -/// Weights for pallet_encointer_balances using the Encointer solo chain node and recommended hardware. +/// Weights for pallet_encointer_balances using the Encointer solo chain node and recommended +/// hardware. pub struct EncointerWeight(PhantomData); impl WeightInfo for EncointerWeight { fn transfer() -> Weight { diff --git a/bazaar/src/lib.rs b/bazaar/src/lib.rs index 34591df8..13634715 100644 --- a/bazaar/src/lib.rs +++ b/bazaar/src/lib.rs @@ -19,7 +19,6 @@ //! provides functionality for //! - creating new bazaar entries (shop and articles) //! - removing existing entries (shop and articles) -//! #![cfg_attr(not(feature = "std"), no_std)] diff --git a/bazaar/src/weights.rs b/bazaar/src/weights.rs index 069c512d..4d381e9b 100644 --- a/bazaar/src/weights.rs +++ b/bazaar/src/weights.rs @@ -57,7 +57,8 @@ pub trait WeightInfo { fn delete_offering() -> Weight; } -/// Weights for pallet_encointer_bazaar using the Encointer solo chain node and recommended hardware. +/// Weights for pallet_encointer_bazaar using the Encointer solo chain node and recommended +/// hardware. pub struct EncointerWeight(PhantomData); impl WeightInfo for EncointerWeight { fn create_business() -> Weight { diff --git a/ceremonies/assignment/src/lib.rs b/ceremonies/assignment/src/lib.rs index 9a580c04..e129e975 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,7 +97,7 @@ 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; @@ -118,7 +118,7 @@ pub fn assignment_fn_inverse( }; if t3 >= participant_count { - continue + continue; } result.push(t3); @@ -264,7 +264,8 @@ mod tests { assignment_params = AssignmentParams { m, s1, s2 }; check_assignment(num_participants, assignment_params, n); - // in the case where there is only one participant, m will be 2 because it is the smallest prime number + // in the case where there is only one participant, m will be 2 because it is the smallest + // prime number s1 = 1u64; s2 = 1u64; n = 1u64; 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 d8f83353..34a61a7b 100644 --- a/ceremonies/meetup-validation/src/lib.rs +++ b/ceremonies/meetup-validation/src/lib.rs @@ -4,10 +4,10 @@ use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use sp_std::{vec, vec::Vec}; -/// This module is about finding which participants get their rewards based on their votes and attestations. -/// The participant vecs are always vecs of participant ids -/// The partitipant_vote and partcipant_attestations vecs (and their derived vecs) are indexed by the participant index -/// ie. participant_votes[i] holds the vote of participant i +/// This module is about finding which participants get their rewards based on their votes and +/// attestations. The participant vecs are always vecs of participant ids +/// The partitipant_vote and partcipant_attestations vecs (and their derived vecs) are indexed by +/// the participant index ie. participant_votes[i] holds the vote of participant i type ParticipantIndex = usize; type Participants = Vec; @@ -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 @@ -113,7 +113,7 @@ fn early_rewards_possible( n_confirmed, ) && attestation_graph_is_fully_connected(legit_participants, participant_attestations) { - return true + return true; } false } @@ -122,9 +122,10 @@ fn get_excluded_participants_no_vote( participants: &Vec, participant_votes: &Vec, ) -> Result, MeetupValidationError> { - // We want to get rid of all participants that did not vote (ie. have a vote of 0 (default storage value) because they did not receive any attestations). - // This needs to happen before we compute the majority vote, because otherwise it would be possible to receive a majority vote of 0 - // in the case where more than half of the participants did not show up. + // We want to get rid of all participants that did not vote (ie. have a vote of 0 (default + // storage value) because they did not receive any attestations). This needs to happen before we + // compute the majority vote, because otherwise it would be possible to receive a majority vote + // of 0 in the case where more than half of the participants did not show up. let mut excluded_participants: Vec<(ParticipantIndex, ExclusionReason)> = vec![]; for i in participants { @@ -170,7 +171,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 +218,11 @@ 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 + // if all participants are above the threshold and therefore no participants were + // removed, we exit the loop + break; } } Ok(excluded_participants) @@ -240,12 +242,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; @@ -256,7 +258,8 @@ fn filter_attestations( participants: &Participants, participant_attestations: Attestations, ) -> Attestations { - // filter out participants from the attestation vectors that are not in the participants vector anymore. + // filter out participants from the attestation vectors that are not in the participants vector + // anymore. participant_attestations .into_iter() .map(|mut a| { @@ -299,7 +302,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/rpc/src/lib.rs b/ceremonies/rpc/src/lib.rs index cbd761a4..43b89441 100644 --- a/ceremonies/rpc/src/lib.rs +++ b/ceremonies/rpc/src/lib.rs @@ -158,7 +158,7 @@ where if !self.offchain_indexing { return Err( Error::OffchainIndexingDisabled("ceremonies_getReputations".to_string()).into() - ) + ); } let cache_key = &reputation_cache_key(&account); @@ -167,12 +167,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 ae6fbb14..0534bea2 100644 --- a/ceremonies/src/benchmarking.rs +++ b/ceremonies/src/benchmarking.rs @@ -153,7 +153,7 @@ where pub fn last_event() -> Option<::RuntimeEvent> { let events = frame_system::Pallet::::events(); if events.is_empty() { - 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 70e96f18..267baf98 100644 --- a/ceremonies/src/lib.rs +++ b/ceremonies/src/lib.rs @@ -21,7 +21,6 @@ //! - meetup assignment //! - attestation registry //! - issuance of basic income -//! #![cfg_attr(not(feature = "std"), no_std)] @@ -135,7 +134,7 @@ pub mod pallet { }; if Self::is_registered(cid, cindex, &sender) { - return Err(>::ParticipantAlreadyRegistered.into()) + return Err(>::ParticipantAlreadyRegistered.into()); } if let Some(p) = &proof { @@ -220,7 +219,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()) } @@ -260,14 +259,15 @@ pub mod pallet { || { // no reputation provided to refund if participant_type == ParticipantType::Bootstrapper { - // bootstrappers can always register without proving previous attendance. - // Therefore, we don't care if they provide reputation to be refunded or not. - // Client apps must take care not to provide invalid reputation proofs - // for bootstrappers + // bootstrappers can always register without proving previous + // attendance. Therefore, we don't care if they provide reputation to be + // refunded or not. Client apps must take care not to provide invalid + // reputation proofs for bootstrappers Ok::<(), Error>(()) } else { - // we don't want reputables to unregister without refunding their reputation because - // they then couldn't re-register again in the same cycle as reputables. + // we don't want reputables to unregister without refunding their + // reputation because they then couldn't re-register again in the same + // cycle as reputables. Err(>::ReputationCommunityCeremonyRequired) } }, @@ -427,7 +427,7 @@ pub mod pallet { }; if >::contains_key((cid, cindex), meetup_index) { - return Err(>::RewardsAlreadyIssued.into()) + return Err(>::RewardsAlreadyIssued.into()); } info!( target: LOG, @@ -503,9 +503,9 @@ pub mod pallet { meetup_index, meetup_result, )); - return Ok(Pays::No.into()) + return Ok(Pays::No.into()); } else { - return error + return error; } }, }; @@ -516,7 +516,7 @@ pub mod pallet { 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 @@ -614,12 +614,12 @@ pub mod pallet { 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); @@ -672,21 +672,26 @@ pub mod pallet { pub enum Event { /// Participant registered for next ceremony [community, participant type, who] ParticipantRegistered(CommunityIdentifier, ParticipantType, T::AccountId), - /// A bootstrapper (first accountid) has endorsed a participant (second accountid) who can now register as endorsee for this ceremony + /// A bootstrapper (first accountid) has endorsed a participant (second accountid) who can + /// now register as endorsee for this ceremony EndorsedParticipant(CommunityIdentifier, T::AccountId, T::AccountId), /// A participant has registered N attestations for fellow meetup participants AttestationsRegistered(CommunityIdentifier, MeetupIndexType, u32, T::AccountId), - /// rewards have been claimed and issued successfully for N participants for their meetup at the previous ceremony + /// rewards have been claimed and issued successfully for N participants for their meetup + /// at the previous ceremony RewardsIssued(CommunityIdentifier, MeetupIndexType, MeetupParticipantIndexType), - /// inactivity timeout has changed. affects how many ceremony cycles a community can be idle before getting purged + /// inactivity timeout has changed. affects how many ceremony cycles a community can be + /// idle before getting purged InactivityTimeoutUpdated(InactivityTimeoutType), /// The number of endorsement tickets which bootstrappers can give out has changed EndorsementTicketsPerBootstrapperUpdated(EndorsementTicketsType), /// The number of endorsement tickets which bootstrappers can give out has changed EndorsementTicketsPerReputableUpdated(EndorsementTicketsType), - /// reputation lifetime has changed. After this many ceremony cycles, reputations is outdated + /// reputation lifetime has changed. After this many ceremony cycles, reputations is + /// outdated ReputationLifetimeUpdated(ReputationLifetimeType), - /// meetup time offset has changed. affects the exact time the upcoming ceremony meetups will take place + /// meetup time offset has changed. affects the exact time the upcoming ceremony meetups + /// will take place MeetupTimeOffsetUpdated(MeetupTimeOffsetType), /// meetup time tolerance has changed TimeToleranceUpdated(T::Moment), @@ -778,7 +783,8 @@ pub mod pallet { EarlyRewardsNotPossible, /// Only newbies can upgrade their registration MustBeNewbieToUpgradeRegistration, - /// To unregister as a reputable you need to provide a provide a community ceremony where you have a linked reputation + /// To unregister as a reputable you need to provide a provide a community ceremony where + /// you have a linked reputation ReputationCommunityCeremonyRequired, /// In order to unregister a reputable, the provided reputation must be linked ReputationMustBeLinked, @@ -1223,7 +1229,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) @@ -1262,7 +1268,7 @@ impl Pallet { if >::current_phase() != CeremonyPhaseType::Registering { - return Err(>::WrongPhaseForUnregistering) + return Err(>::WrongPhaseForUnregistering); } let participant_type = Self::get_participant_type((cid, cindex), participant) @@ -1331,7 +1337,7 @@ impl Pallet { { // safe; limited by AMOUNT_NEWBIE_TICKETS >::mutate((cid, cindex), sender, |b| *b += 1); - return Ok(()) + return Ok(()); } if >::bootstrappers(cid).contains(sender) && @@ -1340,7 +1346,7 @@ impl Pallet { { // safe; limited by AMOUNT_NEWBIE_TICKETS >::mutate(cid, sender, |b| *b += 1); - return Ok(()) + return Ok(()); } Err(Error::::NoMoreNewbieTickets) @@ -1422,7 +1428,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); @@ -1483,7 +1489,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); @@ -1502,7 +1508,8 @@ impl Pallet { find_prime_below(num_registered_bootstrappers + num_registered_reputables), ); - //safe; number of assigned bootstrappers <= max_num_meetups <=num_assigned_bootstrappers + num_reputables + //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; @@ -1599,16 +1606,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 } @@ -1631,7 +1638,7 @@ impl Pallet { if participant_index < assignment_count.bootstrappers { (participant_index, assignment.bootstrappers_reputables) } else { - return None + return None; } }, ParticipantType::Reputable => { @@ -1642,7 +1649,7 @@ impl Pallet { assignment.bootstrappers_reputables, ) } else { - return None + return None; } }, @@ -1651,7 +1658,7 @@ impl Pallet { if participant_index < assignment_count.endorsees { (participant_index, assignment.endorsees) } else { - return None + return None; } }, @@ -1660,7 +1667,7 @@ impl Pallet { if participant_index < assignment_count.newbies { (participant_index, assignment.newbies) } else { - return None + return None; } }, }; @@ -1680,7 +1687,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 @@ -1769,7 +1776,7 @@ impl Pallet { if !(>::current_phase() == CeremonyPhaseType::Attesting) { - return None + return None; } let duration = @@ -1889,20 +1896,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)); @@ -1940,7 +1947,7 @@ impl Pallet { if Self::participant_reputation((*cid, cindex.saturating_sub(i)), participant) .is_verified() { - return true + return true; } } false @@ -1954,7 +1961,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 @@ -1967,7 +1974,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() } @@ -2000,7 +2007,8 @@ impl OnCeremonyPhaseChange for Pallet { CeremonyPhaseType::Attesting => {}, CeremonyPhaseType::Registering => { let cindex = >::current_ceremony_index(); - // Clean up with a time delay, such that participants can claim their UBI in the following cycle. + // Clean up with a time delay, such that participants can claim their UBI in the + // following cycle. if cindex > Self::reputation_lifetime() { Self::purge_registry( cindex.saturating_sub(Self::reputation_lifetime()).saturating_sub(1), diff --git a/ceremonies/src/migrations.rs b/ceremonies/src/migrations.rs index 15911e7b..11fdd82e 100644 --- a/ceremonies/src/migrations.rs +++ b/ceremonies/src/migrations.rs @@ -92,11 +92,12 @@ 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. - // as long as we check the bounds in pre_upgrade, we should be fine. + // we do not actually migrate any data, because it seems that the storage representation + // of Vec and BoundedVec is the same. as long as we check the bounds in pre_upgrade, we + // should be fine. StorageVersion::new(1).put::>(); weight.saturating_add(T::DbWeight::get().reads_writes(1, 2)) @@ -148,7 +149,7 @@ pub mod v2 { "skipping on_runtime_upgrade: executed on wrong storage version.\ Expected version 1" ); - return weight + return weight; } let cindex = pallet_encointer_scheduler::Pallet::::current_ceremony_index(); let phase = pallet_encointer_scheduler::Pallet::::current_phase(); diff --git a/ceremonies/src/tests.rs b/ceremonies/src/tests.rs index 7fecae17..463ecd6f 100644 --- a/ceremonies/src/tests.rs +++ b/ceremonies/src/tests.rs @@ -154,7 +154,8 @@ fn register_alice_bob_ferdie(cid: CommunityIdentifier) { assert_ok!(register(account_id(&AccountKeyring::Ferdie.pair()), cid, None)); } -/// shortcut to register well-known keys for current ceremony +/// shortcut to register well-known keys for +/// current ceremony fn register_charlie_dave_eve(cid: CommunityIdentifier) { assert_ok!(register(account_id(&AccountKeyring::Charlie.pair()), cid, None)); assert_ok!(register(account_id(&AccountKeyring::Dave.pair()), cid, None)); @@ -176,7 +177,8 @@ fn attest_all( )); } -/// Fully attest all attendees with the new `attest_attendees` extrinsic. +/// Fully attest all attendees with the new +/// `attest_attendees` extrinsic. fn fully_attest_attendees( attendees: &Vec, cid: CommunityIdentifier, @@ -199,7 +201,8 @@ fn fully_attest_attendees( } } -/// Perform full attestation of all participants for a given meetup. +/// Perform full attestation of all participants +/// for a given meetup. fn fully_attest_meetup(cid: CommunityIdentifier, mindex: MeetupIndexType) { let cindex = EncointerScheduler::current_ceremony_index(); let meetup_participants = @@ -217,7 +220,9 @@ fn create_locations(n_locations: u32) -> Vec { .collect() } -/// perform bootstrapping ceremony for test community with either the supplied bootstrappers or the default bootstrappers +/// perform bootstrapping ceremony for test +/// community with either the supplied +/// bootstrappers or the default bootstrappers fn perform_bootstrapping_ceremony( custom_bootstrappers: Option>, n_locations: u32, @@ -253,7 +258,8 @@ fn perform_bootstrapping_ceremony( cid } -// unit tests //////////////////////////////////////// +// unit tests +// //////////////////////////////////////// #[test] fn registering_participant_works() { @@ -1274,7 +1280,8 @@ fn register_with_reputation_works() { ); // tolerate no shows - // no meetup will succeed in this cycle, still we want reputation to be valid for the next cycle + // no meetup will succeed in this cycle, still we want reputation to be valid for the next + // cycle run_to_next_phase(); run_to_next_phase(); run_to_next_phase(); @@ -1700,26 +1707,27 @@ fn registering_endorsee_removes_endorsement() { }); } -// integration tests //////////////////////////////// +// integration tests +// //////////////////////////////// #[rstest(lat_micro, lon_micro, meetup_time_offset, -case(0, 0, 0), -case(1_000_000, 1_000_000, 0), -case(0, 2_234_567, 0), -case(2_000_000, 155_000_000, 0), -case(1_000_000, -2_000_000, 0), -case(-31_000_000, -155_000_000, 0), -case(0, 0, 100_000), -case(1_000_000, 1_000_000, 100_000), -case(0, 2_234_567, 100_000), -case(2_000_000, 155_000_000, 100_000), -case(1_000_000, -2_000_000, 100_000), -case(-31_000_000, -155_000_000, 100_000), -case(1_000_000, 1_000_000, -100_000), -case(0, 2_234_567, -100_000), -case(2_000_000, 155_000_000, -100_000), -case(1_000_000, -2_000_000, -100_000), -case(-31_000_000, -155_000_000, -100_000), + case(0, 0, 0), + case(1_000_000, 1_000_000, 0), + case(0, 2_234_567, 0), + case(2_000_000, 155_000_000, 0), + case(1_000_000, -2_000_000, 0), + case(-31_000_000, -155_000_000, 0), + case(0, 0, 100_000), + case(1_000_000, 1_000_000, 100_000), + case(0, 2_234_567, 100_000), + case(2_000_000, 155_000_000, 100_000), + case(1_000_000, -2_000_000, 100_000), + case(-31_000_000, -155_000_000, 100_000), + case(1_000_000, 1_000_000, -100_000), + case(0, 2_234_567, -100_000), + case(2_000_000, 155_000_000, -100_000), + case(1_000_000, -2_000_000, -100_000), + case(-31_000_000, -155_000_000, -100_000), )] fn get_meetup_time_works(lat_micro: i64, lon_micro: i64, meetup_time_offset: i64) { new_test_ext().execute_with(|| { @@ -2189,7 +2197,8 @@ fn purge_inactive_communities_works() { assert!(>::community_identifiers() .contains(&cid)); - // now the inactivity counter is 3 == inactivity_timeout, so in the next cycle the community will be purged + // now the inactivity counter is 3 == inactivity_timeout, so in the next cycle the community + // will be purged assert_eq!(EncointerCeremonies::inactivity_counters(cid).unwrap(), 3); run_to_next_phase(); diff --git a/ceremonies/src/weights.rs b/ceremonies/src/weights.rs index d3842483..605a8957 100644 --- a/ceremonies/src/weights.rs +++ b/ceremonies/src/weights.rs @@ -37,7 +37,8 @@ limitations under the License. // --wasm-execution=compiled // --heap-pages=4096 // --output=runtime/src/weights/pallet_encointer_ceremonies.rs -// --template=/Users/pigu/Dropbox/DATA/Documents/solidbit/kunden/encointer/code/repos/encointer-node/scripts/frame-weight-template-full-info.hbs +// --template=/Users/pigu/Dropbox/DATA/Documents/solidbit/kunden/encointer/code/repos/ +// encointer-node/scripts/frame-weight-template-full-info.hbs #![allow(unused_parens)] #![allow(unused_imports)] @@ -66,7 +67,8 @@ pub trait WeightInfo { fn purge_community_ceremony() -> Weight; } -/// Weights for pallet_encointer_ceremonies using the Encointer solo chain node and recommended hardware. +/// Weights for pallet_encointer_ceremonies using the Encointer solo chain node and recommended +/// hardware. pub struct EncointerWeight(PhantomData); impl WeightInfo for EncointerWeight { fn register_participant() -> Weight { diff --git a/communities/rpc/src/lib.rs b/communities/rpc/src/lib.rs index fd13a700..ddc61362 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/lib.rs b/communities/src/lib.rs index 2d700761..412cdba6 100644 --- a/communities/src/lib.rs +++ b/communities/src/lib.rs @@ -19,7 +19,6 @@ //! provides functionality for //! - registering new communities //! - modifying community characteristics -//! #![cfg_attr(not(feature = "std"), no_std)] @@ -93,7 +92,8 @@ pub mod pallet { /// /// May only be called from `T::TrustableForNonDestructiveAction`. #[pallet::call_index(0)] - #[pallet::weight((::WeightInfo::new_community(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::new_community(), DispatchClass::Normal, Pays::Yes) + )] pub fn new_community( origin: OriginFor, location: Location, @@ -168,7 +168,8 @@ pub mod pallet { /// /// Todo: Replace `T::CommunityMaster` with community governance: #137. #[pallet::call_index(1)] - #[pallet::weight((::WeightInfo::add_location(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::add_location(), DispatchClass::Normal, Pays::Yes) + )] pub fn add_location( origin: OriginFor, cid: CommunityIdentifier, @@ -189,7 +190,8 @@ pub mod pallet { /// /// Todo: Replace `T::CommunityMaster` with community governance: #137. #[pallet::call_index(2)] - #[pallet::weight((::WeightInfo::remove_location(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::remove_location(), DispatchClass::Normal, Pays::Yes) + )] pub fn remove_location( origin: OriginFor, cid: CommunityIdentifier, @@ -208,7 +210,8 @@ pub mod pallet { /// /// May only be called from `T::CommunityMaster`. #[pallet::call_index(3)] - #[pallet::weight((::WeightInfo::update_community_metadata(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::update_community_metadata(), DispatchClass::Normal, Pays::Yes) + )] pub fn update_community_metadata( origin: OriginFor, cid: CommunityIdentifier, @@ -219,7 +222,8 @@ pub mod pallet { } #[pallet::call_index(4)] - #[pallet::weight((::WeightInfo::update_demurrage(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::update_demurrage(), DispatchClass::Normal, Pays::Yes) + )] pub fn update_demurrage( origin: OriginFor, cid: CommunityIdentifier, @@ -230,7 +234,8 @@ pub mod pallet { } #[pallet::call_index(5)] - #[pallet::weight((::WeightInfo::update_nominal_income(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::update_nominal_income(), DispatchClass::Normal, Pays::Yes) + )] pub fn update_nominal_income( origin: OriginFor, cid: CommunityIdentifier, @@ -241,7 +246,8 @@ pub mod pallet { } #[pallet::call_index(6)] - #[pallet::weight((::WeightInfo::set_min_solar_trip_time_s(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::set_min_solar_trip_time_s(), DispatchClass::Normal, Pays::Yes) + )] pub fn set_min_solar_trip_time_s( origin: OriginFor, min_solar_trip_time_s: MinSolarTripTimeType, @@ -254,7 +260,8 @@ pub mod pallet { } #[pallet::call_index(7)] - #[pallet::weight((::WeightInfo::set_max_speed_mps(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::set_max_speed_mps(), DispatchClass::Normal, Pays::Yes) + )] pub fn set_max_speed_mps( origin: OriginFor, max_speed_mps: MaxSpeedMpsType, @@ -267,7 +274,8 @@ pub mod pallet { } #[pallet::call_index(8)] - #[pallet::weight((::WeightInfo::purge_community(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::purge_community(), DispatchClass::Normal, Pays::Yes) + )] pub fn purge_community( origin: OriginFor, cid: CommunityIdentifier, @@ -726,7 +734,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)?; @@ -765,7 +773,7 @@ impl Pallet { if pallet_encointer_balances::Balance::::contains_key(cid, account.clone()) { balances.push(( cid, - >::balance_entry(cid, &account.clone()), + >::balance_entry(cid, account.clone()), )); } } diff --git a/communities/src/migrations.rs b/communities/src/migrations.rs index a78cdb33..d0aeda3b 100644 --- a/communities/src/migrations.rs +++ b/communities/src/migrations.rs @@ -18,8 +18,6 @@ mod v0 { pub type IpfsCid = UnboundedPalletString; #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] - #[cfg_attr(feature = "serde_derive", derive(Serialize, Deserialize))] - #[cfg_attr(feature = "serde_derive", serde(rename_all = "camelCase"))] pub struct UnboundedCommunityMetadata { /// utf8 encoded name pub name: UnboundedPalletString, @@ -105,8 +103,6 @@ pub mod v1 { #[derive( Encode, Decode, Default, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen, )] - #[cfg_attr(feature = "serde_derive", derive(Serialize, Deserialize))] - #[cfg_attr(feature = "serde_derive", serde(rename_all = "camelCase"))] pub struct CommunityMetadataV1 { /// utf8 encoded name pub name: PalletString, @@ -213,7 +209,8 @@ pub mod v2 { } log::info!(target: TARGET, "{} bootstrappers will be migrated.", bootstrappers_count,); - // For community metadata, we do not need any checks, because the data is bounded already due to the CommmunityMetadata validate() function. + // For community metadata, we do not need any checks, because the data is bounded + // already due to the CommmunityMetadata validate() function. Ok(( cid_count, @@ -245,7 +242,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::( @@ -434,13 +431,13 @@ mod test { // Check that all values got migrated. assert_eq!( - crate::CommunityIdentifiers::::get(), - BoundedVec::< - CommunityIdentifier, - ::MaxCommunityIdentifiers, - >::try_from(cids) - .unwrap() - ); + crate::CommunityIdentifiers::::get(), + BoundedVec::< + CommunityIdentifier, + ::MaxCommunityIdentifiers, + >::try_from(cids) + .unwrap() + ); assert_eq!( crate::CommunityIdentifiersByGeohash::::get( diff --git a/communities/src/tests.rs b/communities/src/tests.rs index d8b0a082..09e3ee8e 100644 --- a/communities/src/tests.rs +++ b/communities/src/tests.rs @@ -609,7 +609,6 @@ fn new_community_near_dateline_fails() { /// lat max: 0.0439453125 /// lon min: 39.990234375 /// lon max: 40.0341796875 -/// #[test] fn get_relevant_neighbor_buckets_works() { new_test_ext().execute_with(|| { @@ -720,8 +719,6 @@ fn get_relevant_neighbor_buckets_works() { /// lat max: 0.0439453125 /// lon min: 39.990234375 /// lon max: 40.0341796875 -/// -/// #[test] fn get_nearby_locations_works() { new_test_ext().execute_with(|| { diff --git a/communities/src/weights.rs b/communities/src/weights.rs index ef3cf4ae..074d3908 100644 --- a/communities/src/weights.rs +++ b/communities/src/weights.rs @@ -60,7 +60,8 @@ pub trait WeightInfo { fn purge_community() -> Weight; } -/// Weights for pallet_encointer_communities using the Encointer solo chain node and recommended hardware. +/// Weights for pallet_encointer_communities using the Encointer solo chain node and recommended +/// hardware. pub struct EncointerWeight(PhantomData); impl WeightInfo for EncointerWeight { fn new_community() -> Weight { diff --git a/democracy/src/benchmarking.rs b/democracy/src/benchmarking.rs index 39eabb82..e51a9a2b 100644 --- a/democracy/src/benchmarking.rs +++ b/democracy/src/benchmarking.rs @@ -29,7 +29,12 @@ benchmarks! { submit_proposal { let zoran = account("zoran", 1, 1); - let proposal_action = ProposalAction::SetInactivityTimeout(8); + let cid = CommunityIdentifier::default(); + // worst case is petition + let proposal_action = ProposalAction::Petition(Some(cid), PalletString::try_from("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\ + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\ + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\ + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".as_bytes().to_vec()).unwrap()); assert!(>::iter().next().is_none()); }: _(RawOrigin::Signed(zoran), proposal_action) verify { diff --git a/democracy/src/lib.rs b/democracy/src/lib.rs index 2eac2483..81599b49 100644 --- a/democracy/src/lib.rs +++ b/democracy/src/lib.rs @@ -15,12 +15,12 @@ // along with Encointer. If not, see . //! # Encointer Democracy Module -//! #![cfg_attr(not(feature = "std"), no_std)] use encointer_primitives::{ ceremonies::ReputationCountType, + common::PalletString, democracy::{Proposal, ProposalAction, ProposalIdType, ReputationVec}, fixed::{transcendental::sqrt, types::U64F64}, scheduler::{CeremonyIndexType, CeremonyPhaseType}, @@ -144,6 +144,10 @@ pub mod pallet { proposal_id: ProposalIdType, reason: DispatchErrorWithPostInfo, }, + PetitionApproved { + cid: Option, + text: PalletString, + }, } #[pallet::error] @@ -227,13 +231,14 @@ pub mod pallet { #[pallet::call] impl Pallet { #[pallet::call_index(0)] - #[pallet::weight((::WeightInfo::submit_proposal(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::submit_proposal(), DispatchClass::Normal, Pays::Yes) + )] pub fn submit_proposal( origin: OriginFor, proposal_action: ProposalAction, ) -> DispatchResultWithPostInfo { if Self::enactment_queue(proposal_action.clone().get_identifier()).is_some() { - return Err(Error::::ProposalWaitingForEnactment.into()) + return Err(Error::::ProposalWaitingForEnactment.into()); } let _sender = ensure_signed(origin)?; let cindex = >::current_ceremony_index(); @@ -313,7 +318,8 @@ pub mod pallet { } #[pallet::call_index(2)] - #[pallet::weight((::WeightInfo::update_proposal_state(), DispatchClass::Normal, Pays::Yes))] + #[pallet::weight((::WeightInfo::update_proposal_state(), DispatchClass::Normal, Pays::Yes) + )] pub fn update_proposal_state( origin: OriginFor, proposal_id: ProposalIdType, @@ -332,7 +338,7 @@ pub mod pallet { /// /// These boundaries ensure that we have a constant electorate to determine the /// approval threshold. - /// * The lower bound ensures that the oldest reputation still exist at the end of the + /// * The lower bound ensures that the oldest reputation still exist at the end of the /// proposal lifetime. /// * The upper bound ensures that the still dynamic reputation count of the /// cindex at submission time is not included. @@ -361,11 +367,13 @@ pub mod pallet { .ok_or(Error::::MathError) } - /// Validates the reputations based on the following criteria and commits the reputations. Returns count of valid reputations. + /// Validates the reputations based on the following criteria and commits the reputations. + /// Returns count of valid reputations. /// 1. are valid /// 2. have not been used to vote for proposal_id /// 3. originate in the correct community (for Community AccessPolicy) - /// 4. are within proposal.start_cindex - reputation_lifetime + proposal_lifetime and proposal.start_cindex - 2 + /// 4. are within proposal.start_cindex - reputation_lifetime + proposal_lifetime and + /// proposal.start_cindex - 2 pub fn validate_and_commit_reputations( proposal_id: ProposalIdType, account_id: &T::AccountId, @@ -383,12 +391,12 @@ pub mod pallet { for community_ceremony in reputations { if !Self::voting_cindexes(proposal.start_cindex)?.contains(&community_ceremony.1) { - continue + continue; } if let Some(cid) = maybe_cid { if community_ceremony.0 != cid { - continue + continue; } } @@ -401,7 +409,7 @@ pub mod pallet { ) .is_err() { - continue + continue; } eligible_reputation_count += 1; @@ -423,7 +431,8 @@ pub mod pallet { let proposal_action_identifier = proposal.action.clone().get_identifier(); let last_approved_proposal_for_action = Self::last_approved_proposal_for_action(proposal_action_identifier); - let proposal_cancelled_by_other = last_approved_proposal_for_action.is_some() && + let proposal_cancelled_by_other = proposal.action.supersedes_same_action() && + last_approved_proposal_for_action.is_some() && proposal.start < last_approved_proposal_for_action.unwrap().0; let proposal_too_old = now - proposal.start > T::ProposalLifetime::get(); if proposal_cancelled_by_other { @@ -531,7 +540,7 @@ 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); } Self::positive_turnout_bias(electorate, tally.turnout, tally.ayes) @@ -541,15 +550,18 @@ pub mod pallet { let mut proposal = Self::proposals(proposal_id).ok_or(Error::::InexistentProposal)?; - match proposal.action.clone() { + match proposal.action { ProposalAction::AddLocation(cid, location) => { CommunitiesPallet::::do_add_location(cid, location)?; }, ProposalAction::RemoveLocation(cid, location) => { CommunitiesPallet::::do_remove_location(cid, location)?; }, - ProposalAction::UpdateCommunityMetadata(cid, community_metadata) => { - CommunitiesPallet::::do_update_community_metadata(cid, community_metadata)?; + ProposalAction::UpdateCommunityMetadata(cid, ref community_metadata) => { + CommunitiesPallet::::do_update_community_metadata( + cid, + community_metadata.clone(), + )?; }, ProposalAction::UpdateDemurrage(cid, demurrage) => { CommunitiesPallet::::do_update_demurrage(cid, demurrage)?; @@ -560,6 +572,12 @@ pub mod pallet { ProposalAction::SetInactivityTimeout(inactivity_timeout) => { CeremoniesPallet::::do_set_inactivity_timeout(inactivity_timeout)?; }, + ProposalAction::Petition(maybe_cid, ref petition) => { + Self::deposit_event(Event::PetitionApproved { + cid: maybe_cid, + text: petition.clone(), + }); + }, }; proposal.state = ProposalState::Enacted; diff --git a/democracy/src/migrations.rs b/democracy/src/migrations.rs index 1b42fbf4..8e362b35 100644 --- a/democracy/src/migrations.rs +++ b/democracy/src/migrations.rs @@ -42,7 +42,7 @@ pub mod v1 { target: TARGET, "skipping on_runtime_upgrade: executed on wrong storage version." ); - return T::DbWeight::get().reads(1) + return T::DbWeight::get().reads(1); } let mut purged_keys = 0u64; diff --git a/democracy/src/tests.rs b/democracy/src/tests.rs index b29d8f7a..89078c5d 100644 --- a/democracy/src/tests.rs +++ b/democracy/src/tests.rs @@ -46,7 +46,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 { @@ -481,6 +481,35 @@ fn do_update_proposal_state_cancels_superseded_proposal() { }); } +#[test] +fn do_update_proposal_state_does_not_cancel_no_supersession_actions() { + new_test_ext().execute_with(|| { + let cid = create_cid(); + let petition1_text = PalletString::try_from("freedom for all".as_bytes().to_vec()).unwrap(); + let proposal1_action = ProposalAction::Petition(Some(cid), petition1_text.clone()); + + assert_ok!(EncointerDemocracy::submit_proposal( + RuntimeOrigin::signed(alice()), + proposal1_action + )); + + //another proposal of same action has been scheduled for enactment + LastApprovedProposalForAction::::insert( + ProposalActionIdentifier::Petition(Some(cid)), + (3 * BLOCKTIME, 2), + ); + + assert_eq!(EncointerDemocracy::proposals(1).unwrap().state, ProposalState::Ongoing); + + advance_n_blocks(5); + + assert_ok!(EncointerDemocracy::do_update_proposal_state(1)); + + // we do not want petitions to cancel others + assert_eq!(EncointerDemocracy::proposals(1).unwrap().state, ProposalState::Ongoing); + }); +} + #[test] fn do_update_proposal_state_works_with_too_old_proposal() { new_test_ext().execute_with(|| { @@ -959,6 +988,42 @@ fn enact_set_inactivity_timeout_works() { }); } +#[test] +fn enact_petition_works() { + new_test_ext().execute_with(|| { + System::set_block_number(System::block_number() + 1); // this is needed to assert events + + let cid = create_cid(); + let alice = alice(); + let petition_text = PalletString::try_from("freedom for all".as_bytes().to_vec()).unwrap(); + let proposal_action = ProposalAction::Petition(Some(cid), petition_text.clone()); + assert_ok!(EncointerDemocracy::submit_proposal( + RuntimeOrigin::signed(alice.clone()), + proposal_action.clone() + )); + + // directly inject the proposal into the enactment queue + EnactmentQueue::::insert(proposal_action.clone().get_identifier(), 1); + + run_to_next_phase(); + // first assigning phase after proposal lifetime ended + + assert_eq!(EncointerDemocracy::proposals(1).unwrap().state, ProposalState::Enacted); + assert_eq!(EncointerDemocracy::enactment_queue(proposal_action.get_identifier()), None); + + match event_at_index::(get_num_events::() - 3).unwrap() { + mock::RuntimeEvent::EncointerDemocracy(Event::PetitionApproved { + cid: maybe_cid, + text, + }) => { + assert_eq!(maybe_cid, Some(cid)); + assert_eq!(text, petition_text); + }, + _ => panic!("Wrong event"), + }; + }); +} + #[test] fn enactment_error_fires_event() { new_test_ext().execute_with(|| { diff --git a/democracy/src/weights.rs b/democracy/src/weights.rs index 69846a0e..f749376c 100644 --- a/democracy/src/weights.rs +++ b/democracy/src/weights.rs @@ -36,7 +36,8 @@ limitations under the License. // --wasm-execution=compiled // --heap-pages=4096 // --output=runtime/src/weights/pallet_encointer_democracy.rs -// --template=/Users/pigu/Documents/code/encointer/encointer-node/scripts/frame-weight-template-full-info.hbs +// --template=/Users/pigu/Documents/code/encointer/encointer-node/scripts/ +// frame-weight-template-full-info.hbs #![allow(unused_parens)] #![allow(unused_imports)] @@ -54,7 +55,8 @@ pub trait WeightInfo { fn update_proposal_state() -> Weight; } -/// Weights for pallet_encointer_democracy using the Encointer solo chain node and recommended hardware. +/// Weights for pallet_encointer_democracy using the Encointer solo chain node and recommended +/// hardware. pub struct EncointerWeight(PhantomData); impl WeightInfo for EncointerWeight { fn submit_proposal() -> Weight { diff --git a/faucet/src/lib.rs b/faucet/src/lib.rs index b02bdb55..48c7fd5a 100644 --- a/faucet/src/lib.rs +++ b/faucet/src/lib.rs @@ -109,7 +109,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()); } } } @@ -128,7 +128,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( @@ -170,7 +170,7 @@ pub mod pallet { if let Some(wl) = faucet.whitelist { if !wl.contains(&cid) { - return Err(>::CommunityNotInWhitelist.into()) + return Err(>::CommunityNotInWhitelist.into()); } } diff --git a/faucet/src/tests.rs b/faucet/src/tests.rs index ce30c6cd..246473c7 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"); } @@ -392,7 +392,7 @@ fn dripping_fails_when_cid_not_whitelisted() { ext.execute_with(|| { System::set_block_number(System::block_number() + 1); // this is needed to assert events - // re-register because of different ext + // re-register because of different ext let cid = register_test_community::(None, 0.0, 0.0); let cid2 = register_test_community::(None, 10.0, 10.0); let whitelist_input: WhiteListType = bounded_vec![cid]; @@ -458,7 +458,7 @@ fn dripping_works_with_whitelist_bypass() { ext.execute_with(|| { System::set_block_number(System::block_number() + 1); // this is needed to assert events - // re-register because of different ext + // re-register because of different ext let cid = register_test_community::(None, 0.0, 0.0); let cid2 = register_test_community::(None, 10.0, 10.0); Balances::make_free_balance_be(&bob, 1000); diff --git a/faucet/src/weights.rs b/faucet/src/weights.rs index 0289aceb..2e9d06b9 100644 --- a/faucet/src/weights.rs +++ b/faucet/src/weights.rs @@ -37,7 +37,8 @@ limitations under the License. // --wasm-execution=compiled // --heap-pages=4096 // --output=runtime/src/weights/pallet_encointer_faucet.rs -// --template=/Users/pigu/Documents/code/encointer/encointer-node/scripts/frame-weight-template-full-info.hbs +// --template=/Users/pigu/Documents/code/encointer/encointer-node/scripts/ +// frame-weight-template-full-info.hbs #![allow(unused_parens)] #![allow(unused_imports)] @@ -57,7 +58,8 @@ pub trait WeightInfo { fn set_reserve_amount() -> Weight; } -/// Weights for pallet_encointer_faucet using the Encointer solo chain node and recommended hardware. +/// Weights for pallet_encointer_faucet using the Encointer solo chain node and recommended +/// hardware. pub struct EncointerWeight(PhantomData); impl WeightInfo for EncointerWeight { fn create_faucet() -> Weight { diff --git a/primitives/core/src/bs58_verify.rs b/primitives/core/src/bs58_verify.rs index f8b4b4e3..d011f2fd 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 c4724b1f..dea17e0e 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/core/src/serde.rs b/primitives/core/src/serde.rs index 3e283dfd..6d46d8b2 100644 --- a/primitives/core/src/serde.rs +++ b/primitives/core/src/serde.rs @@ -26,7 +26,8 @@ pub mod serialize_array { } } -/// Serialization shim for fixed point numbers that is consistent with `polkadot-js`'s implementation. +/// Serialization shim for fixed point numbers that is consistent with `polkadot-js`'s +/// implementation. /// /// This is needed in particular for fixed point types that map to a i-/u128, as serde has problems /// with it: https://github.com/paritytech/substrate/issues/4641 diff --git a/primitives/src/balances.rs b/primitives/src/balances.rs index 1d2075aa..eb3556cd 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/ceremonies.rs b/primitives/src/ceremonies.rs index 0effcefc..f941c612 100644 --- a/primitives/src/ceremonies.rs +++ b/primitives/src/ceremonies.rs @@ -38,7 +38,8 @@ pub type CommunityCeremony = (CommunityIdentifier, CeremonyIndexType); pub type InactivityTimeoutType = u32; pub type EndorsementTicketsType = u8; -/// reputation lifetime may not be longer than CeremonyIndexShort::MAX, otherwise double-using reputation is possible. therefore, we restrict the type to u8 +/// reputation lifetime may not be longer than CeremonyIndexShort::MAX, otherwise double-using +/// reputation is possible. therefore, we restrict the type to u8 pub type ReputationLifetimeType = u32; pub type MeetupTimeOffsetType = i32; pub type MeetupData = @@ -302,16 +303,19 @@ pub struct Assignment { pub locations: AssignmentParams, } -// Todo: abstract AssignmentParams trait and use two different structs: AssignmentParams, LocationAssignmentParams +// Todo: abstract AssignmentParams trait and use two different structs: AssignmentParams, +// LocationAssignmentParams #[derive( Encode, Decode, Default, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen, )] #[cfg_attr(feature = "serde_derive", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde_derive", serde(rename_all = "camelCase"))] pub struct AssignmentParams { - /// Random prime below number of meetup participants. For locations this is the amount of locations. + /// Random prime below number of meetup participants. For locations this is the amount of + /// locations. pub m: u64, - /// First random group element in the interval (0, m). For locations this is a random coprime < m. + /// First random group element in the interval (0, m). For locations this is a random coprime < + /// m. pub s1: u64, /// Second random group element in the interval (0, m). For locations the closest prime to m, /// with s2 < m. diff --git a/primitives/src/common.rs b/primitives/src/common.rs index 1c58da23..92270c50 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 6b2eee44..cb3f1a6d 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(()) } @@ -180,8 +180,6 @@ impl FromStr for CommunityIdentifier { /// If we just returned the error as is, it would be confusing, as the index size is not the actual /// index of the &str passed to the `CommunityIdentifier::from_str` method. Hence, we increase the /// index by the geohash size. -/// -/// fn decorate_bs58_err(err: bs58::decode::Error) -> bs58::decode::Error { use bs58::decode::Error as Bs58Err; match err { @@ -319,19 +317,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)); } } diff --git a/primitives/src/democracy.rs b/primitives/src/democracy.rs index 8b6234d1..f0a697b9 100644 --- a/primitives/src/democracy.rs +++ b/primitives/src/democracy.rs @@ -9,11 +9,12 @@ use crate::{ use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -use crate::{ceremonies::ReputationCountType, scheduler::CeremonyIndexType}; +use crate::{ceremonies::ReputationCountType, common::PalletString, scheduler::CeremonyIndexType}; #[cfg(feature = "serde_derive")] use serde::{Deserialize, Serialize}; use sp_core::RuntimeDebug; use sp_runtime::BoundedVec; + pub type ProposalIdType = u128; pub type VoteCountType = u128; pub type VoteEntry = (AccountId, CommunityCeremony); @@ -55,6 +56,7 @@ pub enum ProposalAction { UpdateDemurrage(CommunityIdentifier, Demurrage), UpdateNominalIncome(CommunityIdentifier, NominalIncomeType), SetInactivityTimeout(InactivityTimeoutType), + Petition(Option, PalletString), } #[derive(Encode, Decode, RuntimeDebug, Clone, Copy, PartialEq, Eq, TypeInfo, MaxEncodedLen)] @@ -67,32 +69,52 @@ pub enum ProposalActionIdentifier { UpdateDemurrage(CommunityIdentifier), UpdateNominalIncome(CommunityIdentifier), SetInactivityTimeout, + Petition(Option), } impl ProposalAction { - pub fn get_access_policy(self) -> ProposalAccessPolicy { + pub fn get_access_policy(&self) -> ProposalAccessPolicy { match self { - ProposalAction::AddLocation(cid, _) => ProposalAccessPolicy::Community(cid), - ProposalAction::RemoveLocation(cid, _) => ProposalAccessPolicy::Community(cid), - ProposalAction::UpdateCommunityMetadata(cid, _) => ProposalAccessPolicy::Community(cid), - ProposalAction::UpdateDemurrage(cid, _) => ProposalAccessPolicy::Community(cid), - ProposalAction::UpdateNominalIncome(cid, _) => ProposalAccessPolicy::Community(cid), + ProposalAction::AddLocation(cid, _) => ProposalAccessPolicy::Community(*cid), + ProposalAction::RemoveLocation(cid, _) => ProposalAccessPolicy::Community(*cid), + ProposalAction::UpdateCommunityMetadata(cid, _) => + ProposalAccessPolicy::Community(*cid), + ProposalAction::UpdateDemurrage(cid, _) => ProposalAccessPolicy::Community(*cid), + ProposalAction::UpdateNominalIncome(cid, _) => ProposalAccessPolicy::Community(*cid), ProposalAction::SetInactivityTimeout(_) => ProposalAccessPolicy::Global, + ProposalAction::Petition(Some(cid), _) => ProposalAccessPolicy::Community(*cid), + ProposalAction::Petition(None, _) => ProposalAccessPolicy::Global, } } - pub fn get_identifier(self) -> ProposalActionIdentifier { + pub fn get_identifier(&self) -> ProposalActionIdentifier { match self { - ProposalAction::AddLocation(cid, _) => ProposalActionIdentifier::AddLocation(cid), - ProposalAction::RemoveLocation(cid, _) => ProposalActionIdentifier::RemoveLocation(cid), + ProposalAction::AddLocation(cid, _) => ProposalActionIdentifier::AddLocation(*cid), + ProposalAction::RemoveLocation(cid, _) => + ProposalActionIdentifier::RemoveLocation(*cid), ProposalAction::UpdateCommunityMetadata(cid, _) => - ProposalActionIdentifier::UpdateCommunityMetadata(cid), + ProposalActionIdentifier::UpdateCommunityMetadata(*cid), ProposalAction::UpdateDemurrage(cid, _) => - ProposalActionIdentifier::UpdateDemurrage(cid), + ProposalActionIdentifier::UpdateDemurrage(*cid), ProposalAction::UpdateNominalIncome(cid, _) => - ProposalActionIdentifier::UpdateNominalIncome(cid), + ProposalActionIdentifier::UpdateNominalIncome(*cid), ProposalAction::SetInactivityTimeout(_) => ProposalActionIdentifier::SetInactivityTimeout, + ProposalAction::Petition(maybe_cid, _) => + ProposalActionIdentifier::Petition(*maybe_cid), + } + } + + /// Returns true if the action supersedes other proposals of the same action type when approved. + pub fn supersedes_same_action(&self) -> bool { + match self { + ProposalAction::AddLocation(_, _) => true, + ProposalAction::RemoveLocation(_, _) => true, + ProposalAction::UpdateCommunityMetadata(_, _) => true, + ProposalAction::UpdateDemurrage(_, _) => true, + ProposalAction::UpdateNominalIncome(_, _) => true, + ProposalAction::SetInactivityTimeout(_) => true, + ProposalAction::Petition(_, _) => false, } } } diff --git a/primitives/src/vouches.rs b/primitives/src/vouches.rs index 645cc1df..8b5d5224 100644 --- a/primitives/src/vouches.rs +++ b/primitives/src/vouches.rs @@ -33,9 +33,10 @@ pub enum PresenceType { /// could be "I have visited that place in the metaverse" /// could be "I have met this person on an video call and they presented this account to me" LiveVirtual, - /// could be "I met the human I vouch for in-person and scanned the account they presented at the occasion of this physical encounter" - /// could be "I was standing in front of this monument and scanned the QR code on its plate" - /// could be "I ate at this restaurant and scanned the QR code presented at their entrance in order to submit a rating" + /// could be "I met the human I vouch for in-person and scanned the account they presented at + /// the occasion of this physical encounter" could be "I was standing in front of this monument + /// and scanned the QR code on its plate" could be "I ate at this restaurant and scanned the QR + /// code presented at their entrance in order to submit a rating" LivePhysical, } @@ -50,7 +51,8 @@ pub enum VouchKind { Unspecified, /// This person is know to me and I have verified their account with specified presence type KnownHuman(PresenceType), - /// I do not claim to know this person, but I encountered a human being providing me with the account I vouch for + /// I do not claim to know this person, but I encountered a human being providing me with the + /// account I vouch for EncounteredHuman(PresenceType), /// I encountered an object showing the account I vouch for EncounteredObject(PresenceType), @@ -80,7 +82,8 @@ pub enum VouchQuality { #[derive(Default, Encode, Decode, PartialEq, Eq, RuntimeDebug, Clone, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "serde_derive", derive(Serialize, Deserialize))] pub struct Vouch { - /// protected vouches can't be purged. unprotected ones can be lazily purged after a time-to-live. (future feature) + /// protected vouches can't be purged. unprotected ones can be lazily purged after a + /// time-to-live. (future feature) pub protected: bool, /// the timestamp of the block which registers this Vouch pub timestamp: Moment, diff --git a/reputation-commitments/src/lib.rs b/reputation-commitments/src/lib.rs index 841072a6..2f3fb509 100644 --- a/reputation-commitments/src/lib.rs +++ b/reputation-commitments/src/lib.rs @@ -107,7 +107,7 @@ pub mod pallet { commitment_hash: Option, ) -> Result<(), Error> { if !>::contains_key(purpose) { - return Err(>::InexistentPurpose) + return Err(>::InexistentPurpose); } if !>::participant_reputation( @@ -116,11 +116,11 @@ pub mod pallet { ) .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); @@ -214,7 +214,8 @@ impl OnCeremonyPhaseChange for Pallet { let reputation_lifetime = >::reputation_lifetime(); let cindex = >::current_ceremony_index(); - // Clean up with a time delay, such that participants can claim their UBI in the following cycle. + // Clean up with a time delay, such that participants can claim their UBI in the + // following cycle. if cindex > reputation_lifetime { Self::purge_registry( cindex.saturating_sub(reputation_lifetime).saturating_sub(1), diff --git a/reputation-commitments/src/tests.rs b/reputation-commitments/src/tests.rs index 22e14d2a..d13e40f7 100644 --- a/reputation-commitments/src/tests.rs +++ b/reputation-commitments/src/tests.rs @@ -269,7 +269,7 @@ fn purging_works() { ext.execute_with(|| { System::set_block_number(System::block_number() + 1); // this is needed to assert events - // re-register because of different ext + // re-register because of different ext let cid = register_test_community::(None, 0.0, 0.0); let cid2 = register_test_community::(None, 10.0, 10.0); diff --git a/reputation-commitments/src/weights.rs b/reputation-commitments/src/weights.rs index 68a39d9c..656ceb54 100644 --- a/reputation-commitments/src/weights.rs +++ b/reputation-commitments/src/weights.rs @@ -37,7 +37,8 @@ limitations under the License. // --wasm-execution=compiled // --heap-pages=4096 // --output=runtime/src/weights/pallet_encointer_reputation_commitments.rs -// --template=/Users/pigu/Documents/code/encointer/encointer-node/scripts/frame-weight-template-full-info.hbs +// --template=/Users/pigu/Documents/code/encointer/encointer-node/scripts/ +// frame-weight-template-full-info.hbs #![allow(unused_parens)] #![allow(unused_imports)] @@ -54,7 +55,8 @@ pub trait WeightInfo { fn commit_reputation() -> Weight; } -/// Weights for pallet_encointer_reputation_commitments using the Encointer solo chain node and recommended hardware. +/// Weights for pallet_encointer_reputation_commitments using the Encointer solo chain node and +/// recommended hardware. pub struct EncointerWeight(PhantomData); impl WeightInfo for EncointerWeight { fn register_purpose() -> Weight { diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 8dca45a8..69d82979 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "stable" +channel = "1.77.0" # align with https://github.com/polkadot-fellows/runtimes/blob/7157d41176bebf128aa2e29e72ed184844446b19/.github/env#L1 profile = "default" # include rustfmt, clippy targets = ["wasm32-unknown-unknown"] diff --git a/scheduler/src/lib.rs b/scheduler/src/lib.rs index b4da4b4e..87700a63 100644 --- a/scheduler/src/lib.rs +++ b/scheduler/src/lib.rs @@ -19,7 +19,6 @@ //! provides functionality for //! - scheduling ceremonies with their different phases //! - dispatch transition functions upon phase change -//! #![cfg_attr(not(feature = "std"), no_std)] @@ -230,8 +229,10 @@ impl Pallet { } // we need to resync in two situations: - // 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 + // 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 = Self::get_cycle_duration(); let now = pallet_timestamp::Now::::get(); @@ -241,14 +242,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/scheduler/src/tests.rs b/scheduler/src/tests.rs index d3a2edf5..f54f14f6 100644 --- a/scheduler/src/tests.rs +++ b/scheduler/src/tests.rs @@ -257,7 +257,8 @@ fn resync_after_next_phase_works() { EncointerScheduler::next_phase_timestamp(), (genesis_time - genesis_time.rem(ONE_DAY)) + 2 * ONE_DAY ); - // this means that we merely anticipated the ASSIGNING_PHASE. NExt ATTESTING will still start as if next_phase() had not been called + // this means that we merely anticipated the ASSIGNING_PHASE. NExt ATTESTING will still + // start as if next_phase() had not been called run_to_block(2); set_timestamp(genesis_time + 2 * TEN_MIN); @@ -270,7 +271,8 @@ fn resync_after_next_phase_works() { EncointerScheduler::next_phase_timestamp(), (genesis_time - genesis_time.rem(ONE_DAY)) + 3 * ONE_DAY ); - // this means that we merely anticipated the ATTESTING phase. NExt REGISTERING will still start as if next_phase() had not been called + // this means that we merely anticipated the ATTESTING phase. NExt REGISTERING will still + // start as if next_phase() had not been called run_to_block(3); set_timestamp(genesis_time + 3 * TEN_MIN); @@ -285,8 +287,8 @@ fn resync_after_next_phase_works() { EncointerScheduler::next_phase_timestamp(), (genesis_time - genesis_time.rem(ONE_DAY)) + ONE_DAY ); - // now the next ASSIGNING phase starts exactly at the time it would have startet if next_phase had not been called. - // But the ceremony index increased by one + // now the next ASSIGNING phase starts exactly at the time it would have startet if + // next_phase had not been called. But the ceremony index increased by one }); } diff --git a/scheduler/src/weights.rs b/scheduler/src/weights.rs index adea9eef..af12fff6 100644 --- a/scheduler/src/weights.rs +++ b/scheduler/src/weights.rs @@ -55,7 +55,8 @@ pub trait WeightInfo { fn set_next_phase_timestamp() -> Weight; } -/// Weights for pallet_encointer_scheduler using the Encointer solo chain node and recommended hardware. +/// Weights for pallet_encointer_scheduler using the Encointer solo chain node and recommended +/// hardware. pub struct EncointerWeight(PhantomData); impl WeightInfo for EncointerWeight { fn next_phase() -> Weight { diff --git a/test-utils/src/helpers.rs b/test-utils/src/helpers.rs index 6c6da146..f56adbbf 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 diff --git a/vouches/src/weights.rs b/vouches/src/weights.rs index 5c7406af..b21df647 100644 --- a/vouches/src/weights.rs +++ b/vouches/src/weights.rs @@ -37,7 +37,8 @@ limitations under the License. // --wasm-execution=compiled // --heap-pages=4096 // --output=runtime/src/weights/pallet_encointer_reputation_commitments.rs -// --template=/Users/pigu/Documents/code/encointer/encointer-node/scripts/frame-weight-template-full-info.hbs +// --template=/Users/pigu/Documents/code/encointer/encointer-node/scripts/ +// frame-weight-template-full-info.hbs #![allow(unused_parens)] #![allow(unused_imports)] @@ -53,7 +54,8 @@ pub trait WeightInfo { fn vouch_for() -> Weight; } -/// Weights for pallet_encointer_reputation_commitments using the Encointer solo chain node and recommended hardware. +/// Weights for pallet_encointer_reputation_commitments using the Encointer solo chain node and +/// recommended hardware. pub struct EncointerWeight(PhantomData); impl WeightInfo for EncointerWeight { fn vouch_for() -> Weight {