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
+3 -7
View File
@@ -21,9 +21,9 @@
use super::*;
use frame_system::RawOrigin;
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller};
use frame_support::traits::{EnsureOrigin, OnInitialize, UnfilteredDispatchable};
use frame_benchmarking::{benchmarks, account, whitelisted_caller, impl_benchmark_test_suite};
use frame_system::RawOrigin;
use sp_runtime::traits::{Bounded, Zero};
use crate::Pallet as Lottery;
@@ -170,8 +170,4 @@ benchmarks! {
}
}
impl_benchmark_test_suite!(
Lottery,
crate::mock::new_test_ext(),
crate::mock::Test,
);
impl_benchmark_test_suite!(Lottery, crate::mock::new_test_ext(), crate::mock::Test,);
+71 -60
View File
@@ -47,30 +47,30 @@
#![cfg_attr(not(feature = "std"), no_std)]
mod benchmarking;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod benchmarking;
pub mod weights;
use sp_std::prelude::*;
use sp_runtime::{
DispatchError, ArithmeticError,
traits::{AccountIdConversion, Saturating, Zero},
};
use codec::{Decode, Encode};
use frame_support::{
ensure, PalletId, RuntimeDebug,
dispatch::{Dispatchable, DispatchResult, GetDispatchInfo},
traits::{
Currency, ReservableCurrency, Get, ExistenceRequirement::KeepAlive, Randomness,
},
dispatch::{DispatchResult, Dispatchable, GetDispatchInfo},
ensure,
traits::{Currency, ExistenceRequirement::KeepAlive, Get, Randomness, ReservableCurrency},
PalletId, RuntimeDebug,
};
use codec::{Encode, Decode};
pub use weights::WeightInfo;
pub use pallet::*;
use sp_runtime::{
traits::{AccountIdConversion, Saturating, Zero},
ArithmeticError, DispatchError,
};
use sp_std::prelude::*;
pub use weights::WeightInfo;
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
// Any runtime call can be encoded into two bytes which represent the pallet and call index.
// We use this to uniquely match someone's incoming call with the calls configured for the lottery.
@@ -96,7 +96,9 @@ pub trait ValidateCall<T: Config> {
}
impl<T: Config> ValidateCall<T> for () {
fn validate_call(_: &<T as Config>::Call) -> bool { false }
fn validate_call(_: &<T as Config>::Call) -> bool {
false
}
}
impl<T: Config> ValidateCall<T> for Pallet<T> {
@@ -112,9 +114,9 @@ impl<T: Config> ValidateCall<T> for Pallet<T> {
#[frame_support::pallet]
pub mod pallet {
use frame_support::{Parameter, pallet_prelude::*, traits::EnsureOrigin, weights::Weight};
use frame_system::{ensure_signed, pallet_prelude::*};
use super::*;
use frame_support::{pallet_prelude::*, traits::EnsureOrigin, weights::Weight, Parameter};
use frame_system::{ensure_signed, pallet_prelude::*};
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
@@ -128,7 +130,10 @@ pub mod pallet {
type PalletId: Get<PalletId>;
/// A dispatchable call.
type Call: Parameter + Dispatchable<Origin=Self::Origin> + GetDispatchInfo + From<frame_system::Call<Self>>;
type Call: Parameter
+ Dispatchable<Origin = Self::Origin>
+ GetDispatchInfo
+ From<frame_system::Call<Self>>;
/// The currency trait.
type Currency: ReservableCurrency<Self::AccountId>;
@@ -200,16 +205,13 @@ pub mod pallet {
/// The configuration for the current lottery.
#[pallet::storage]
pub(crate) type Lottery<T: Config> = StorageValue<_, LotteryConfig<T::BlockNumber, BalanceOf<T>>>;
pub(crate) type Lottery<T: Config> =
StorageValue<_, LotteryConfig<T::BlockNumber, BalanceOf<T>>>;
/// Users who have purchased a ticket. (Lottery Index, Tickets Purchased)
#[pallet::storage]
pub(crate) type Participants<T: Config> = StorageMap<
_,
Twox64Concat, T::AccountId,
(u32, Vec<CallIndex>),
ValueQuery,
>;
pub(crate) type Participants<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, (u32, Vec<CallIndex>), ValueQuery>;
/// Total number of tickets sold.
#[pallet::storage]
@@ -232,9 +234,8 @@ pub mod pallet {
fn on_initialize(n: T::BlockNumber) -> Weight {
Lottery::<T>::mutate(|mut lottery| -> Weight {
if let Some(config) = &mut lottery {
let payout_block = config.start
.saturating_add(config.length)
.saturating_add(config.delay);
let payout_block =
config.start.saturating_add(config.length).saturating_add(config.delay);
if payout_block <= n {
let (lottery_account, lottery_balance) = Self::pot();
let ticket_count = TicketsCount::<T>::get();
@@ -242,7 +243,12 @@ pub mod pallet {
let winning_number = Self::choose_winner(ticket_count);
let winner = Tickets::<T>::get(winning_number).unwrap_or(lottery_account);
// Not much we can do if this fails...
let res = T::Currency::transfer(&Self::account_id(), &winner, lottery_balance, KeepAlive);
let res = T::Currency::transfer(
&Self::account_id(),
&winner,
lottery_balance,
KeepAlive,
);
debug_assert!(res.is_ok());
Self::deposit_event(Event::<T>::Winner(winner, lottery_balance));
@@ -340,13 +346,7 @@ pub mod pallet {
let new_index = index.checked_add(1).ok_or(ArithmeticError::Overflow)?;
let start = frame_system::Pallet::<T>::block_number();
// Use new_index to more easily track everything with the current state.
*lottery = Some(LotteryConfig {
price,
start,
length,
delay,
repeat,
});
*lottery = Some(LotteryConfig { price, start, length, delay, repeat });
LotteryIndex::<T>::put(new_index);
Ok(())
})?;
@@ -389,8 +389,8 @@ impl<T: Config> Pallet<T> {
// The existential deposit is not part of the pot so lottery account never gets deleted.
fn pot() -> (T::AccountId, BalanceOf<T>) {
let account_id = Self::account_id();
let balance = T::Currency::free_balance(&account_id)
.saturating_sub(T::Currency::minimum_balance());
let balance =
T::Currency::free_balance(&account_id).saturating_sub(T::Currency::minimum_balance());
(account_id, balance)
}
@@ -408,7 +408,9 @@ impl<T: Config> Pallet<T> {
// Convert a call to it's call index by encoding the call and taking the first two bytes.
fn call_to_index(call: &<T as Config>::Call) -> Result<CallIndex, DispatchError> {
let encoded_call = call.encode();
if encoded_call.len() < 2 { Err(Error::<T>::EncodingFailed)? }
if encoded_call.len() < 2 {
Err(Error::<T>::EncodingFailed)?
}
return Ok((encoded_call[0], encoded_call[1]))
}
@@ -417,30 +419,39 @@ impl<T: Config> Pallet<T> {
// Check the call is valid lottery
let config = Lottery::<T>::get().ok_or(Error::<T>::NotConfigured)?;
let block_number = frame_system::Pallet::<T>::block_number();
ensure!(block_number < config.start.saturating_add(config.length), Error::<T>::AlreadyEnded);
ensure!(
block_number < config.start.saturating_add(config.length),
Error::<T>::AlreadyEnded
);
ensure!(T::ValidateCall::validate_call(call), Error::<T>::InvalidCall);
let call_index = Self::call_to_index(call)?;
let ticket_count = TicketsCount::<T>::get();
let new_ticket_count = ticket_count.checked_add(1).ok_or(ArithmeticError::Overflow)?;
// Try to update the participant status
Participants::<T>::try_mutate(&caller, |(lottery_index, participating_calls)| -> DispatchResult {
let index = LotteryIndex::<T>::get();
// If lottery index doesn't match, then reset participating calls and index.
if *lottery_index != index {
*participating_calls = Vec::new();
*lottery_index = index;
} else {
// Check that user is not already participating under this call.
ensure!(!participating_calls.iter().any(|c| call_index == *c), Error::<T>::AlreadyParticipating);
}
// Check user has enough funds and send it to the Lottery account.
T::Currency::transfer(caller, &Self::account_id(), config.price, KeepAlive)?;
// Create a new ticket.
TicketsCount::<T>::put(new_ticket_count);
Tickets::<T>::insert(ticket_count, caller.clone());
participating_calls.push(call_index);
Ok(())
})?;
Participants::<T>::try_mutate(
&caller,
|(lottery_index, participating_calls)| -> DispatchResult {
let index = LotteryIndex::<T>::get();
// If lottery index doesn't match, then reset participating calls and index.
if *lottery_index != index {
*participating_calls = Vec::new();
*lottery_index = index;
} else {
// Check that user is not already participating under this call.
ensure!(
!participating_calls.iter().any(|c| call_index == *c),
Error::<T>::AlreadyParticipating
);
}
// Check user has enough funds and send it to the Lottery account.
T::Currency::transfer(caller, &Self::account_id(), config.price, KeepAlive)?;
// Create a new ticket.
TicketsCount::<T>::put(new_ticket_count);
Tickets::<T>::insert(ticket_count, caller.clone());
participating_calls.push(call_index);
Ok(())
},
)?;
Self::deposit_event(Event::<T>::TicketBought(caller.clone(), call_index));
@@ -452,9 +463,9 @@ impl<T: Config> Pallet<T> {
let mut random_number = Self::generate_random_number(0);
// Best effort attempt to remove bias from modulus operator.
for i in 1 .. T::MaxGenerateRandom::get() {
for i in 1..T::MaxGenerateRandom::get() {
if random_number < u32::MAX - u32::MAX % total {
break;
break
}
random_number = Self::generate_random_number(i);
+5 -3
View File
@@ -25,13 +25,13 @@ use frame_support::{
traits::{OnFinalize, OnInitialize},
};
use frame_support_test::TestRandomness;
use frame_system::EnsureRoot;
use sp_core::H256;
use sp_runtime::{
Perbill,
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
Perbill,
};
use frame_system::EnsureRoot;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -123,7 +123,9 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)],
}.assimilate_storage(&mut t).unwrap();
}
.assimilate_storage(&mut t)
.unwrap();
t.into()
}
+6 -17
View File
@@ -18,13 +18,12 @@
//! Tests for the module.
use super::*;
use mock::{
Lottery, Balances, Test, Origin, Call, SystemCall, BalancesCall,
new_test_ext, run_to_block
};
use sp_runtime::traits::{BadOrigin};
use frame_support::{assert_noop, assert_ok};
use mock::{
new_test_ext, run_to_block, Balances, BalancesCall, Call, Lottery, Origin, SystemCall, Test,
};
use pallet_balances::Error as BalancesError;
use sp_runtime::traits::BadOrigin;
#[test]
fn initial_state() {
@@ -86,13 +85,7 @@ fn basic_end_to_end_works() {
assert_eq!(LotteryIndex::<Test>::get(), 2);
assert_eq!(
crate::Lottery::<Test>::get().unwrap(),
LotteryConfig {
price,
start: 25,
length,
delay,
repeat: true,
}
LotteryConfig { price, start: 25, length, delay, repeat: true }
);
});
}
@@ -184,10 +177,7 @@ fn buy_ticket_works_as_simple_passthrough() {
);
let bad_origin_call = Box::new(Call::Balances(BalancesCall::force_transfer(0, 0, 0)));
assert_noop!(
Lottery::buy_ticket(Origin::signed(1), bad_origin_call),
BadOrigin,
);
assert_noop!(Lottery::buy_ticket(Origin::signed(1), bad_origin_call), BadOrigin,);
// User can call other txs, but doesn't get a ticket
let remark_call = Box::new(Call::System(SystemCall::remark(b"hello, world!".to_vec())));
@@ -210,7 +200,6 @@ fn buy_ticket_works() {
];
assert_ok!(Lottery::set_calls(Origin::root(), calls));
// Can't buy ticket before start
let call = Box::new(Call::Balances(BalancesCall::transfer(2, 1)));
assert_ok!(Lottery::buy_ticket(Origin::signed(1), call.clone()));
+1
View File
@@ -36,6 +36,7 @@
// --template=./.maintain/frame-weight-template.hbs
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]