Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+35 -57
View File
@@ -91,18 +91,16 @@ mod mock;
mod tests;
use codec::FullCodec;
use sp_std::{
fmt::Debug,
prelude::*,
};
use frame_support::{
ensure,
traits::{ChangeMembers, InitializeMembers, Currency, Get, ReservableCurrency},
traits::{ChangeMembers, Currency, Get, InitializeMembers, ReservableCurrency},
};
use sp_runtime::traits::{AtLeast32Bit, Zero, StaticLookup};
pub use pallet::*;
use sp_runtime::traits::{AtLeast32Bit, StaticLookup, Zero};
use sp_std::{fmt::Debug, prelude::*};
type BalanceOf<T, I> = <<T as Config<I>>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type BalanceOf<T, I> =
<<T as Config<I>>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type PoolT<T, I> = Vec<(<T as frame_system::Config>::AccountId, Option<<T as Config<I>>::Score>)>;
/// The enum is supplied when refreshing the members set.
@@ -117,10 +115,10 @@ enum ChangeReceiver {
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::{pallet_prelude::*, traits::EnsureOrigin, weights::Weight};
use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};
use sp_runtime::traits::MaybeSerializeDeserialize;
use super::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
@@ -132,8 +130,13 @@ pub mod pallet {
type Currency: Currency<Self::AccountId> + ReservableCurrency<Self::AccountId>;
/// The score attributed to a member or candidate.
type Score:
AtLeast32Bit + Clone + Copy + Default + FullCodec + MaybeSerializeDeserialize + Debug;
type Score: AtLeast32Bit
+ Clone
+ Copy
+ Default
+ FullCodec
+ MaybeSerializeDeserialize
+ Debug;
/// The overarching event type.
type Event: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::Event>;
@@ -209,22 +212,19 @@ pub mod pallet {
/// `T::AccountId`, but by `T::Score` instead).
#[pallet::storage]
#[pallet::getter(fn candidate_exists)]
pub(crate) type CandidateExists<T: Config<I>, I: 'static = ()> = StorageMap<
_,
Twox64Concat, T::AccountId,
bool,
ValueQuery,
>;
pub(crate) type CandidateExists<T: Config<I>, I: 'static = ()> =
StorageMap<_, Twox64Concat, T::AccountId, bool, ValueQuery>;
/// The current membership, stored as an ordered Vec.
#[pallet::storage]
#[pallet::getter(fn members)]
pub(crate) type Members<T: Config<I>, I: 'static = ()> = StorageValue<_, Vec<T::AccountId>, ValueQuery>;
pub(crate) type Members<T: Config<I>, I: 'static = ()> =
StorageValue<_, Vec<T::AccountId>, ValueQuery>;
/// Size of the `Members` set.
#[pallet::storage]
#[pallet::getter(fn member_count)]
pub(crate) type MemberCount<T, I=()> = StorageValue<_, u32, ValueQuery>;
pub(crate) type MemberCount<T, I = ()> = StorageValue<_, u32, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
@@ -235,10 +235,7 @@ pub mod pallet {
#[cfg(feature = "std")]
impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
fn default() -> Self {
Self {
pool: Default::default(),
member_count: Default::default(),
}
Self { pool: Default::default(), member_count: Default::default() }
}
}
@@ -249,19 +246,15 @@ pub mod pallet {
// reserve balance for each candidate in the pool.
// panicking here is ok, since this just happens one time, pre-genesis.
pool
.iter()
.for_each(|(who, _)| {
T::Currency::reserve(&who, T::CandidateDeposit::get())
.expect("balance too low to create candidacy");
<CandidateExists<T, I>>::insert(who, true);
});
pool.iter().for_each(|(who, _)| {
T::Currency::reserve(&who, T::CandidateDeposit::get())
.expect("balance too low to create candidacy");
<CandidateExists<T, I>>::insert(who, true);
});
// Sorts the `Pool` by score in a descending order. Entities which
// have a score of `None` are sorted to the beginning of the vec.
pool.sort_by_key(|(_, maybe_score)|
Reverse(maybe_score.unwrap_or_default())
);
pool.sort_by_key(|(_, maybe_score)| Reverse(maybe_score.unwrap_or_default()));
<MemberCount<T, I>>::put(self.member_count);
<Pool<T, I>>::put(&pool);
@@ -324,10 +317,7 @@ pub mod pallet {
/// The `index` parameter of this function must be set to
/// the index of the transactor in the `Pool`.
#[pallet::weight(0)]
pub fn withdraw_candidacy(
origin: OriginFor<T>,
index: u32
) -> DispatchResult {
pub fn withdraw_candidacy(origin: OriginFor<T>, index: u32) -> DispatchResult {
let who = ensure_signed(origin)?;
let pool = <Pool<T, I>>::get();
@@ -348,7 +338,7 @@ pub mod pallet {
pub fn kick(
origin: OriginFor<T>,
dest: <T::Lookup as StaticLookup>::Source,
index: u32
index: u32,
) -> DispatchResult {
T::KickOrigin::ensure_origin(origin)?;
@@ -373,7 +363,7 @@ pub mod pallet {
origin: OriginFor<T>,
dest: <T::Lookup as StaticLookup>::Source,
index: u32,
score: T::Score
score: T::Score,
) -> DispatchResult {
T::ScoreOrigin::ensure_origin(origin)?;
@@ -390,10 +380,9 @@ pub mod pallet {
// where we can insert while maintaining order.
let item = (who, Some(score.clone()));
let location = pool
.binary_search_by_key(
&Reverse(score),
|(_, maybe_score)| Reverse(maybe_score.unwrap_or_default())
)
.binary_search_by_key(&Reverse(score), |(_, maybe_score)| {
Reverse(maybe_score.unwrap_or_default())
})
.unwrap_or_else(|l| l);
pool.insert(location, item);
@@ -418,16 +407,12 @@ pub mod pallet {
}
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Fetches the `MemberCount` highest scoring members from
/// `Pool` and puts them into `Members`.
///
/// The `notify` parameter is used to deduct which associated
/// type function to invoke at the end of the method.
fn refresh_members(
pool: PoolT<T, I>,
notify: ChangeReceiver
) {
fn refresh_members(pool: PoolT<T, I>, notify: ChangeReceiver) {
let count = MemberCount::<T, I>::get();
let mut new_members: Vec<T::AccountId> = pool
@@ -445,10 +430,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
ChangeReceiver::MembershipInitialized =>
T::MembershipInitialized::initialize_members(&new_members),
ChangeReceiver::MembershipChanged =>
T::MembershipChanged::set_members_sorted(
&new_members[..],
&old_members[..],
),
T::MembershipChanged::set_members_sorted(&new_members[..], &old_members[..]),
}
}
@@ -459,7 +441,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
fn remove_member(
mut pool: PoolT<T, I>,
remove: T::AccountId,
index: u32
index: u32,
) -> Result<(), Error<T, I>> {
// all callers of this function in this pallet also check
// the index for validity before calling this function.
@@ -486,11 +468,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Checks if `index` is a valid number and if the element found
/// at `index` in `Pool` is equal to `who`.
fn ensure_index(
pool: &PoolT<T, I>,
who: &T::AccountId,
index: u32
) -> Result<(), Error<T, I>> {
fn ensure_index(pool: &PoolT<T, I>, who: &T::AccountId, index: u32) -> Result<(), Error<T, I>> {
ensure!(index < pool.len() as u32, Error::<T, I>::InvalidIndex);
let (index_who, _index_score) = &pool[index as usize];
+16 -21
View File
@@ -20,13 +20,14 @@
use super::*;
use crate as pallet_scored_pool;
use std::cell::RefCell;
use frame_support::{parameter_types, ord_parameter_types, traits::GenesisBuild};
use frame_support::{ord_parameter_types, parameter_types, traits::GenesisBuild};
use frame_system::EnsureSignedBy;
use sp_core::H256;
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup}, testing::Header,
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
};
use frame_system::EnsureSignedBy;
use std::cell::RefCell;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -145,32 +146,26 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
(40, 500_000),
(99, 1),
],
}.assimilate_storage(&mut t).unwrap();
pallet_scored_pool::GenesisConfig::<Test>{
pool: vec![
(5, None),
(10, Some(1)),
(20, Some(2)),
(31, Some(2)),
(40, Some(3)),
],
}
.assimilate_storage(&mut t)
.unwrap();
pallet_scored_pool::GenesisConfig::<Test> {
pool: vec![(5, None), (10, Some(1)), (20, Some(2)), (31, Some(2)), (40, Some(3))],
member_count: 2,
.. Default::default()
}.assimilate_storage(&mut t).unwrap();
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
t.into()
}
/// Fetch an entity from the pool, if existent.
pub fn fetch_from_pool(who: u64) -> Option<(u64, Option<u64>)> {
<Pallet<Test>>::pool()
.into_iter()
.find(|item| item.0 == who)
<Pallet<Test>>::pool().into_iter().find(|item| item.0 == who)
}
/// Find an entity in the pool.
/// Returns its position in the `Pool` vec, if existent.
pub fn find_in_pool(who: u64) -> Option<usize> {
<Pallet<Test>>::pool()
.into_iter()
.position(|item| item.0 == who)
<Pallet<Test>>::pool().into_iter().position(|item| item.0 == who)
}
+35 -16
View File
@@ -20,7 +20,7 @@
use super::*;
use mock::*;
use frame_support::{assert_ok, assert_noop, traits::OnInitialize};
use frame_support::{assert_noop, assert_ok, traits::OnInitialize};
use sp_runtime::traits::BadOrigin;
type ScoredPool = Pallet<Test>;
@@ -142,14 +142,12 @@ fn unscored_entities_must_not_be_used_for_filling_members() {
// when
// we remove every scored member
ScoredPool::pool()
.into_iter()
.for_each(|(who, score)| {
if let Some(_) = score {
let index = find_in_pool(who).expect("entity must be in pool") as u32;
assert_ok!(ScoredPool::kick(Origin::signed(KickOrigin::get()), who, index));
}
});
ScoredPool::pool().into_iter().for_each(|(who, score)| {
if let Some(_) = score {
let index = find_in_pool(who).expect("entity must be in pool") as u32;
assert_ok!(ScoredPool::kick(Origin::signed(KickOrigin::get()), who, index));
}
});
// then
// the `None` candidates should not have been filled in
@@ -201,7 +199,10 @@ fn withdraw_candidacy_must_only_work_for_members() {
new_test_ext().execute_with(|| {
let who = 77;
let index = 0;
assert_noop!( ScoredPool::withdraw_candidacy(Origin::signed(who), index), Error::<Test, _>::WrongAccountIndex);
assert_noop!(
ScoredPool::withdraw_candidacy(Origin::signed(who), index),
Error::<Test, _>::WrongAccountIndex
);
});
}
@@ -210,9 +211,18 @@ fn oob_index_should_abort() {
new_test_ext().execute_with(|| {
let who = 40;
let oob_index = ScoredPool::pool().len() as u32;
assert_noop!(ScoredPool::withdraw_candidacy(Origin::signed(who), oob_index), Error::<Test, _>::InvalidIndex);
assert_noop!(ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, oob_index, 99), Error::<Test, _>::InvalidIndex);
assert_noop!(ScoredPool::kick(Origin::signed(KickOrigin::get()), who, oob_index), Error::<Test, _>::InvalidIndex);
assert_noop!(
ScoredPool::withdraw_candidacy(Origin::signed(who), oob_index),
Error::<Test, _>::InvalidIndex
);
assert_noop!(
ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, oob_index, 99),
Error::<Test, _>::InvalidIndex
);
assert_noop!(
ScoredPool::kick(Origin::signed(KickOrigin::get()), who, oob_index),
Error::<Test, _>::InvalidIndex
);
});
}
@@ -221,9 +231,18 @@ fn index_mismatches_should_abort() {
new_test_ext().execute_with(|| {
let who = 40;
let index = 3;
assert_noop!(ScoredPool::withdraw_candidacy(Origin::signed(who), index), Error::<Test, _>::WrongAccountIndex);
assert_noop!(ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, index, 99), Error::<Test, _>::WrongAccountIndex);
assert_noop!(ScoredPool::kick(Origin::signed(KickOrigin::get()), who, index), Error::<Test, _>::WrongAccountIndex);
assert_noop!(
ScoredPool::withdraw_candidacy(Origin::signed(who), index),
Error::<Test, _>::WrongAccountIndex
);
assert_noop!(
ScoredPool::score(Origin::signed(ScoreOrigin::get()), who, index, 99),
Error::<Test, _>::WrongAccountIndex
);
assert_noop!(
ScoredPool::kick(Origin::signed(KickOrigin::get()), who, index),
Error::<Test, _>::WrongAccountIndex
);
});
}