From d32c5c2e698866834ff51cea163ba67db883f277 Mon Sep 17 00:00:00 2001 From: david Date: Wed, 6 Oct 2021 18:30:07 +0100 Subject: [PATCH 01/11] convert pallet-assets events to struct types --- frame/assets/src/benchmarking.rs | 56 +++++++++---------- frame/assets/src/functions.rs | 12 ++--- frame/assets/src/lib.rs | 92 +++++++++++++++----------------- frame/assets/src/tests.rs | 2 +- 4 files changed, 79 insertions(+), 83 deletions(-) diff --git a/frame/assets/src/benchmarking.rs b/frame/assets/src/benchmarking.rs index d9de9ed3dedd4..080e068a49bdb 100644 --- a/frame/assets/src/benchmarking.rs +++ b/frame/assets/src/benchmarking.rs @@ -155,7 +155,7 @@ benchmarks_instance_pallet! { T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup, 1u32.into()) verify { - assert_last_event::(Event::Created(Default::default(), caller.clone(), caller).into()); + assert_last_event::(Event::Created{asset:id: Default::default(), creator: caller.clone(), owner: caller}.into()); } force_create { @@ -163,7 +163,7 @@ benchmarks_instance_pallet! { let caller_lookup = T::Lookup::unlookup(caller.clone()); }: _(SystemOrigin::Root, Default::default(), caller_lookup, true, 1u32.into()) verify { - assert_last_event::(Event::ForceCreated(Default::default(), caller).into()); + assert_last_event::(Event::ForceCreated{asset_id: Default::default(), caller}.into()); } destroy { @@ -177,7 +177,7 @@ benchmarks_instance_pallet! { let witness = Asset::::get(T::AssetId::default()).unwrap().destroy_witness(); }: _(SystemOrigin::Signed(caller), Default::default(), witness) verify { - assert_last_event::(Event::Destroyed(Default::default()).into()); + assert_last_event::(Event::Destroyed{asset_id: Default::default()}.into()); } mint { @@ -185,7 +185,7 @@ benchmarks_instance_pallet! { let amount = T::Balance::from(100u32); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup, amount) verify { - assert_last_event::(Event::Issued(Default::default(), caller, amount).into()); + assert_last_event::(Event::Issued{asset_id: Default::default(), owner: caller, total_supply: amount}.into()); } burn { @@ -193,7 +193,7 @@ benchmarks_instance_pallet! { let (caller, caller_lookup) = create_default_minted_asset::(true, amount); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup, amount) verify { - assert_last_event::(Event::Burned(Default::default(), caller, amount).into()); + assert_last_event::(Event::Burned{asset_id: Default::default(), owner: caller, balance: amount}.into()); } transfer { @@ -203,7 +203,7 @@ benchmarks_instance_pallet! { let target_lookup = T::Lookup::unlookup(target.clone()); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), target_lookup, amount) verify { - assert_last_event::(Event::Transferred(Default::default(), caller, target, amount).into()); + assert_last_event::(Event::Transferred{asset_id: Default::default(), from: caller, to: target, amount}.into()); } transfer_keep_alive { @@ -215,7 +215,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Signed(caller.clone()), Default::default(), target_lookup, amount) verify { assert!(frame_system::Pallet::::account_exists(&caller)); - assert_last_event::(Event::Transferred(Default::default(), caller, target, amount).into()); + assert_last_event::(Event::Transferred{asset_id: Default::default(), from: caller, to: target, amount}.into()); } force_transfer { @@ -226,7 +226,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup, target_lookup, amount) verify { assert_last_event::( - Event::Transferred(Default::default(), caller, target, amount).into() + Event::Transferred{asset_id: Default::default(), from: caller, to: target, amount}.into() ); } @@ -234,7 +234,7 @@ benchmarks_instance_pallet! { let (caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup) verify { - assert_last_event::(Event::Frozen(Default::default(), caller).into()); + assert_last_event::(Event::Frozen{asset_id: Default::default(), who: caller}.into()); } thaw { @@ -246,14 +246,14 @@ benchmarks_instance_pallet! { )?; }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup) verify { - assert_last_event::(Event::Thawed(Default::default(), caller).into()); + assert_last_event::(Event::Thawed{asset_id: Default::default(), who: caller}.into()); } freeze_asset { let (caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); }: _(SystemOrigin::Signed(caller.clone()), Default::default()) verify { - assert_last_event::(Event::AssetFrozen(Default::default()).into()); + assert_last_event::(Event::AssetFrozen{asset_id: Default::default()}.into()); } thaw_asset { @@ -264,7 +264,7 @@ benchmarks_instance_pallet! { )?; }: _(SystemOrigin::Signed(caller.clone()), Default::default()) verify { - assert_last_event::(Event::AssetThawed(Default::default()).into()); + assert_last_event::(Event::AssetThawed{asset_id: Default::default()}.into()); } transfer_ownership { @@ -273,7 +273,7 @@ benchmarks_instance_pallet! { let target_lookup = T::Lookup::unlookup(target.clone()); }: _(SystemOrigin::Signed(caller), Default::default(), target_lookup) verify { - assert_last_event::(Event::OwnerChanged(Default::default(), target).into()); + assert_last_event::(Event::OwnerChanged{asset_id: Default::default(), owner: target}.into()); } set_team { @@ -283,12 +283,12 @@ benchmarks_instance_pallet! { let target2 = T::Lookup::unlookup(account("target", 2, SEED)); }: _(SystemOrigin::Signed(caller), Default::default(), target0.clone(), target1.clone(), target2.clone()) verify { - assert_last_event::(Event::TeamChanged( - Default::default(), - account("target", 0, SEED), - account("target", 1, SEED), - account("target", 2, SEED), - ).into()); + assert_last_event::(Event::TeamChanged{ + asset_id: Default::default(), + issuer: account("target", 0, SEED), + admin: account("target", 1, SEED), + freezer: account("target", 2, SEED), + }.into()); } set_metadata { @@ -304,7 +304,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Signed(caller), Default::default(), name.clone(), symbol.clone(), decimals) verify { let id = Default::default(); - assert_last_event::(Event::MetadataSet(id, name, symbol, decimals, false).into()); + assert_last_event::(Event::MetadataSet{asset_id: id, name, symbol, decimals, is_frozen: false}.into()); } clear_metadata { @@ -315,7 +315,7 @@ benchmarks_instance_pallet! { Assets::::set_metadata(origin, Default::default(), dummy.clone(), dummy, 12)?; }: _(SystemOrigin::Signed(caller), Default::default()) verify { - assert_last_event::(Event::MetadataCleared(Default::default()).into()); + assert_last_event::(Event::MetadataCleared{asset_id: Default::default()}.into()); } force_set_metadata { @@ -339,7 +339,7 @@ benchmarks_instance_pallet! { }: { call.dispatch_bypass_filter(origin)? } verify { let id = Default::default(); - assert_last_event::(Event::MetadataSet(id, name, symbol, decimals, false).into()); + assert_last_event::(Event::MetadataSet{asset_id: id, name, symbol, decimals, is_frozen: false}.into()); } force_clear_metadata { @@ -353,7 +353,7 @@ benchmarks_instance_pallet! { let call = Call::::force_clear_metadata { id: Default::default() }; }: { call.dispatch_bypass_filter(origin)? } verify { - assert_last_event::(Event::MetadataCleared(Default::default()).into()); + assert_last_event::(Event::MetadataCleared{asset_id: Default::default()}.into()); } force_asset_status { @@ -372,7 +372,7 @@ benchmarks_instance_pallet! { }; }: { call.dispatch_bypass_filter(origin)? } verify { - assert_last_event::(Event::AssetStatusChanged(Default::default()).into()); + assert_last_event::(Event::AssetStatusChanged{asset_id: Default::default()}.into()); } approve_transfer { @@ -385,7 +385,7 @@ benchmarks_instance_pallet! { let amount = 100u32.into(); }: _(SystemOrigin::Signed(caller.clone()), id, delegate_lookup, amount) verify { - assert_last_event::(Event::ApprovedTransfer(id, caller, delegate, amount).into()); + assert_last_event::(Event::ApprovedTransfer{asset_id: id, source: caller, delegate, amount}.into()); } transfer_approved { @@ -405,7 +405,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Signed(delegate.clone()), id, owner_lookup, dest_lookup, amount) verify { assert!(T::Currency::reserved_balance(&owner).is_zero()); - assert_event::(Event::Transferred(id, owner, dest, amount).into()); + assert_event::(Event::Transferred{asset_id: id, from: owner, to: dest, amount}.into()); } cancel_approval { @@ -420,7 +420,7 @@ benchmarks_instance_pallet! { Assets::::approve_transfer(origin, id, delegate_lookup.clone(), amount)?; }: _(SystemOrigin::Signed(caller.clone()), id, delegate_lookup) verify { - assert_last_event::(Event::ApprovalCancelled(id, caller, delegate).into()); + assert_last_event::(Event::ApprovalCancelled{asset_id: id, owner: caller, delegate}.into()); } force_cancel_approval { @@ -435,7 +435,7 @@ benchmarks_instance_pallet! { Assets::::approve_transfer(origin, id, delegate_lookup.clone(), amount)?; }: _(SystemOrigin::Signed(caller.clone()), id, caller_lookup, delegate_lookup) verify { - assert_last_event::(Event::ApprovalCancelled(id, caller, delegate).into()); + assert_last_event::(Event::ApprovalCancelled{asset_id: id, owner: caller, delegate}.into()); } impl_benchmark_test_suite!(Assets, crate::mock::new_test_ext(), crate::mock::Test) diff --git a/frame/assets/src/functions.rs b/frame/assets/src/functions.rs index a4685d88d0497..f50f671d95a4b 100644 --- a/frame/assets/src/functions.rs +++ b/frame/assets/src/functions.rs @@ -275,7 +275,7 @@ impl, I: 'static> Pallet { details.supply = details.supply.saturating_add(amount); Ok(()) })?; - Self::deposit_event(Event::Issued(id, beneficiary.clone(), amount)); + Self::deposit_event(Event::Issued{asset_id: id, owner: beneficiary.clone(), total_supply: amount}); Ok(()) } @@ -342,7 +342,7 @@ impl, I: 'static> Pallet { Ok(()) })?; - Self::deposit_event(Event::Burned(id, target.clone(), actual)); + Self::deposit_event(Event::Burned{asset_id: id, owner: target.clone(), balance: actual}); Ok(actual) } @@ -415,7 +415,7 @@ impl, I: 'static> Pallet { ) -> Result { // Early exist if no-op. if amount.is_zero() { - Self::deposit_event(Event::Transferred(id, source.clone(), dest.clone(), amount)); + Self::deposit_event(Event::Transferred{asset_id: id, from: source.clone(), to: dest.clone(), amount}); return Ok(amount) } @@ -476,7 +476,7 @@ impl, I: 'static> Pallet { Ok(()) })?; - Self::deposit_event(Event::Transferred(id, source.clone(), dest.clone(), credit)); + Self::deposit_event(Event::Transferred{asset_id: id, from: source.clone(), to: dest.clone(), amount: credit}); Ok(credit) } @@ -514,7 +514,7 @@ impl, I: 'static> Pallet { is_frozen: false, }, ); - Self::deposit_event(Event::ForceCreated(id, owner)); + Self::deposit_event(Event::ForceCreated{asset_id: id, owner}); Ok(()) } @@ -554,7 +554,7 @@ impl, I: 'static> Pallet { for ((owner, _), approval) in Approvals::::drain_prefix((&id,)) { T::Currency::unreserve(&owner, approval.deposit); } - Self::deposit_event(Event::Destroyed(id)); + Self::deposit_event(Event::Destroyed{asset_id: id}); Ok(DestroyWitness { accounts: details.accounts, diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 4176242c8394a..94e3877ed10e9 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -380,47 +380,43 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { - /// Some asset class was created. \[asset_id, creator, owner\] - Created(T::AssetId, T::AccountId, T::AccountId), - /// Some assets were issued. \[asset_id, owner, total_supply\] - Issued(T::AssetId, T::AccountId, T::Balance), - /// Some assets were transferred. \[asset_id, from, to, amount\] - Transferred(T::AssetId, T::AccountId, T::AccountId, T::Balance), - /// Some assets were destroyed. \[asset_id, owner, balance\] - Burned(T::AssetId, T::AccountId, T::Balance), - /// The management team changed \[asset_id, issuer, admin, freezer\] - TeamChanged(T::AssetId, T::AccountId, T::AccountId, T::AccountId), - /// The owner changed \[asset_id, owner\] - OwnerChanged(T::AssetId, T::AccountId), - /// Some account `who` was frozen. \[asset_id, who\] - Frozen(T::AssetId, T::AccountId), - /// Some account `who` was thawed. \[asset_id, who\] - Thawed(T::AssetId, T::AccountId), - /// Some asset `asset_id` was frozen. \[asset_id\] - AssetFrozen(T::AssetId), - /// Some asset `asset_id` was thawed. \[asset_id\] - AssetThawed(T::AssetId), + /// Some asset class was created. + Created{asset_id: T::AssetId, creator: T::AccountId, owner: T::AccountId}, + /// Some assets were issued. + Issued{asset_id: T::AssetId, owner: T::AccountId, total_supply: T::Balance}, + /// Some assets were transferred. + Transferred{asset_id: T::AssetId, from: T::AccountId, to: T::AccountId, amount: T::Balance}, + /// Some assets were destroyed. + Burned{asset_id: T::AssetId, owner: T::AccountId, balance: T::Balance}, + /// The management team changed. + TeamChanged{asset_id: T::AssetId, issuer: T::AccountId, admin: T::AccountId, freezer: T::AccountId}, + /// The owner changed. + OwnerChanged{asset_id: T::AssetId, owner: T::AccountId}, + /// Some account `who` was frozen. + Frozen{asset_id: T::AssetId, who: T::AccountId}, + /// Some account `who` was thawed. + Thawed{asset_id: T::AssetId, who: T::AccountId}, + /// Some asset `asset_id` was frozen. + AssetFrozen{asset_id: T::AssetId}, + /// Some asset `asset_id` was thawed. + AssetThawed{asset_id: T::AssetId}, /// An asset class was destroyed. - Destroyed(T::AssetId), - /// Some asset class was force-created. \[asset_id, owner\] - ForceCreated(T::AssetId, T::AccountId), - /// New metadata has been set for an asset. \[asset_id, name, symbol, decimals, is_frozen\] - MetadataSet(T::AssetId, Vec, Vec, u8, bool), - /// Metadata has been cleared for an asset. \[asset_id\] - MetadataCleared(T::AssetId), + Destroyed{asset_id: T::AssetId}, + /// Some asset class was force-created. + ForceCreated{asset_id: T::AssetId, owner: T::AccountId}, + /// New metadata has been set for an asset. + MetadataSet{asset_id: T::AssetId, name: Vec, symbol: Vec, decimals: u8, is_frozen: bool}, + /// Metadata has been cleared for an asset. + MetadataCleared{asset_id: T::AssetId}, /// (Additional) funds have been approved for transfer to a destination account. - /// \[asset_id, source, delegate, amount\] - ApprovedTransfer(T::AssetId, T::AccountId, T::AccountId, T::Balance), + ApprovedTransfer{asset_id: T::AssetId, source: T::AccountId, delegate: T::AccountId, amount: T::Balance}, /// An approval for account `delegate` was cancelled by `owner`. - /// \[id, owner, delegate\] - ApprovalCancelled(T::AssetId, T::AccountId, T::AccountId), + ApprovalCancelled{asset_id: T::AssetId, owner: T::AccountId, delegate: T::AccountId}, /// An `amount` was transferred in its entirety from `owner` to `destination` by /// the approved `delegate`. - /// \[id, owner, delegate, destination\] - TransferredApproved(T::AssetId, T::AccountId, T::AccountId, T::AccountId, T::Balance), + TransferredApproved{asset_id: T::AssetId, owner: T::AccountId, delegate: T::AccountId, destination: T::AccountId, amount: T::Balance}, /// An asset has had its attributes changed by the `Force` origin. - /// \[id\] - AssetStatusChanged(T::AssetId), + AssetStatusChanged{asset_id: T::AssetId}, } #[pallet::error] @@ -506,7 +502,7 @@ pub mod pallet { is_frozen: false, }, ); - Self::deposit_event(Event::Created(id, owner, admin)); + Self::deposit_event(Event::Created{asset_id: id, creator: owner, owner: admin}); Ok(()) } @@ -762,7 +758,7 @@ pub mod pallet { Account::::mutate(id, &who, |a| a.is_frozen = true); - Self::deposit_event(Event::::Frozen(id, who)); + Self::deposit_event(Event::::Frozen{asset_id: id, who}); Ok(()) } @@ -791,7 +787,7 @@ pub mod pallet { Account::::mutate(id, &who, |a| a.is_frozen = false); - Self::deposit_event(Event::::Thawed(id, who)); + Self::deposit_event(Event::::Thawed{asset_id: id, who}); Ok(()) } @@ -817,7 +813,7 @@ pub mod pallet { d.is_frozen = true; - Self::deposit_event(Event::::AssetFrozen(id)); + Self::deposit_event(Event::::AssetFrozen{asset_id: id}); Ok(()) }) } @@ -844,7 +840,7 @@ pub mod pallet { d.is_frozen = false; - Self::deposit_event(Event::::AssetThawed(id)); + Self::deposit_event(Event::::AssetThawed{asset_id: id}); Ok(()) }) } @@ -883,7 +879,7 @@ pub mod pallet { details.owner = owner.clone(); - Self::deposit_event(Event::OwnerChanged(id, owner)); + Self::deposit_event(Event::OwnerChanged{asset_id: id, owner}); Ok(()) }) } @@ -921,7 +917,7 @@ pub mod pallet { details.admin = admin.clone(); details.freezer = freezer.clone(); - Self::deposit_event(Event::TeamChanged(id, issuer, admin, freezer)); + Self::deposit_event(Event::TeamChanged{asset_id: id, issuer, admin, freezer}); Ok(()) }) } @@ -978,7 +974,7 @@ pub mod pallet { Metadata::::try_mutate_exists(id, |metadata| { let deposit = metadata.take().ok_or(Error::::Unknown)?.deposit; T::Currency::unreserve(&d.owner, deposit); - Self::deposit_event(Event::MetadataCleared(id)); + Self::deposit_event(Event::MetadataCleared{asset_id: id}); Ok(()) }) } @@ -1025,7 +1021,7 @@ pub mod pallet { is_frozen, }); - Self::deposit_event(Event::MetadataSet(id, name, symbol, decimals, is_frozen)); + Self::deposit_event(Event::MetadataSet{asset_id: id, name, symbol, decimals, is_frozen}); Ok(()) }) } @@ -1052,7 +1048,7 @@ pub mod pallet { Metadata::::try_mutate_exists(id, |metadata| { let deposit = metadata.take().ok_or(Error::::Unknown)?.deposit; T::Currency::unreserve(&d.owner, deposit); - Self::deposit_event(Event::MetadataCleared(id)); + Self::deposit_event(Event::MetadataCleared{asset_id: id}); Ok(()) }) } @@ -1104,7 +1100,7 @@ pub mod pallet { asset.is_frozen = is_frozen; *maybe_asset = Some(asset); - Self::deposit_event(Event::AssetStatusChanged(id)); + Self::deposit_event(Event::AssetStatusChanged{asset_id: id}); Ok(()) }) } @@ -1170,7 +1166,7 @@ pub mod pallet { d.approvals.saturating_dec(); Asset::::insert(id, d); - Self::deposit_event(Event::ApprovalCancelled(id, owner, delegate)); + Self::deposit_event(Event::ApprovalCancelled{asset_id: id, owner, delegate}); Ok(()) } @@ -1212,7 +1208,7 @@ pub mod pallet { d.approvals.saturating_dec(); Asset::::insert(id, d); - Self::deposit_event(Event::ApprovalCancelled(id, owner, delegate)); + Self::deposit_event(Event::ApprovalCancelled{asset_id: id, owner, delegate}); Ok(()) } diff --git a/frame/assets/src/tests.rs b/frame/assets/src/tests.rs index 5250fafaa8f9a..b43833a543f36 100644 --- a/frame/assets/src/tests.rs +++ b/frame/assets/src/tests.rs @@ -500,7 +500,7 @@ fn transferring_less_than_one_unit_is_fine() { assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 0)); - System::assert_last_event(mock::Event::Assets(crate::Event::Transferred(0, 1, 2, 0))); + System::assert_last_event(mock::Event::Assets(crate::Event::Transferred{asset_id: 0, from: 1, to: 2, amount: 0})); }); } From d9ec48f7b56c7f61238b76f3d5afe5b5222e4224 Mon Sep 17 00:00:00 2001 From: david Date: Sat, 9 Oct 2021 14:22:21 +0100 Subject: [PATCH 02/11] updated events of a couple pallets --- frame/atomic-swap/src/lib.rs | 17 +++--- frame/bags-list/src/lib.rs | 6 +- frame/balances/src/lib.rs | 80 +++++++++++++------------- frame/balances/src/tests.rs | 26 ++++----- frame/balances/src/tests_local.rs | 10 ++-- frame/balances/src/tests_reentrancy.rs | 29 +++++----- 6 files changed, 83 insertions(+), 85 deletions(-) diff --git a/frame/atomic-swap/src/lib.rs b/frame/atomic-swap/src/lib.rs index 9cf92c3bd2337..1cd3774433373 100644 --- a/frame/atomic-swap/src/lib.rs +++ b/frame/atomic-swap/src/lib.rs @@ -218,13 +218,12 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// Swap created. \[account, proof, swap\] - NewSwap(T::AccountId, HashedProof, PendingSwap), + /// Swap created. + NewSwap{account: T::AccountId, proof: HashedProof, swap: PendingSwap}, /// Swap claimed. The last parameter indicates whether the execution succeeds. - /// \[account, proof, success\] - SwapClaimed(T::AccountId, HashedProof, bool), - /// Swap cancelled. \[account, proof\] - SwapCancelled(T::AccountId, HashedProof), + SwapClaimed{account: T::AccountId, proof: HashedProof, success: bool}, + /// Swap cancelled. + SwapCancelled{account: T::AccountId, proof: HashedProof}, } /// Old name generated by `decl_event`. @@ -268,7 +267,7 @@ pub mod pallet { }; PendingSwaps::::insert(target.clone(), hashed_proof.clone(), swap.clone()); - Self::deposit_event(Event::NewSwap(target, hashed_proof, swap)); + Self::deposit_event(Event::NewSwap{account: target, proof: hashed_proof, swap}); Ok(()) } @@ -304,7 +303,7 @@ pub mod pallet { PendingSwaps::::remove(target.clone(), hashed_proof.clone()); - Self::deposit_event(Event::SwapClaimed(target, hashed_proof, succeeded)); + Self::deposit_event(Event::SwapClaimed{account: target, proof: hashed_proof, success: succeeded}); Ok(()) } @@ -333,7 +332,7 @@ pub mod pallet { swap.action.cancel(&swap.source); PendingSwaps::::remove(&target, hashed_proof.clone()); - Self::deposit_event(Event::SwapCancelled(target, hashed_proof)); + Self::deposit_event(Event::SwapCancelled{account: target, proof: hashed_proof}); Ok(()) } diff --git a/frame/bags-list/src/lib.rs b/frame/bags-list/src/lib.rs index 4202a4d499895..77a52ede7d8c1 100644 --- a/frame/bags-list/src/lib.rs +++ b/frame/bags-list/src/lib.rs @@ -174,8 +174,8 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { - /// Moved an account from one bag to another. \[who, from, to\]. - Rebagged(T::AccountId, VoteWeight, VoteWeight), + /// Moved an account from one bag to another. + Rebagged{who: T::AccountId, from: VoteWeight, to: VoteWeight}, } #[pallet::call] @@ -222,7 +222,7 @@ impl Pallet { let maybe_movement = list::Node::::get(&account) .and_then(|node| List::update_position_for(node, new_weight)); if let Some((from, to)) = maybe_movement { - Self::deposit_event(Event::::Rebagged(account.clone(), from, to)); + Self::deposit_event(Event::::Rebagged{who: account.clone(), from, to}); }; maybe_movement } diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index da8019583c3be..8dfc1f17155ba 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -346,7 +346,7 @@ pub mod pallet { (account.free, account.reserved) })?; - Self::deposit_event(Event::BalanceSet(who, free, reserved)); + Self::deposit_event(Event::BalanceSet{who, free, reserved}); Ok(().into()) } @@ -454,31 +454,29 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { - /// An account was created with some free balance. \[account, free_balance\] - Endowed(T::AccountId, T::Balance), + /// An account was created with some free balance. + Endowed{account: T::AccountId, free_balance: T::Balance}, /// An account was removed whose balance was non-zero but below ExistentialDeposit, - /// resulting in an outright loss. \[account, balance\] - DustLost(T::AccountId, T::Balance), - /// Transfer succeeded. \[from, to, value\] - Transfer(T::AccountId, T::AccountId, T::Balance), - /// A balance was set by root. \[who, free, reserved\] - BalanceSet(T::AccountId, T::Balance, T::Balance), - /// Some balance was reserved (moved from free to reserved). \[who, value\] - Reserved(T::AccountId, T::Balance), - /// Some balance was unreserved (moved from reserved to free). \[who, value\] - Unreserved(T::AccountId, T::Balance), + /// resulting in an outright loss. + DustLost{account: T::AccountId, balance: T::Balance}, + /// Transfer succeeded. + Transfer{from: T::AccountId, to: T::AccountId, value: T::Balance}, + /// A balance was set by root. + BalanceSet{who: T::AccountId, free: T::Balance, reserved: T::Balance}, + /// Some amount was deposited (e.g. for transaction fees). + Deposit{who: T::AccountId, deposit: T::Balance}, + /// Some amount was withdrawn from the account (e.g. for transaction fees). \[who, value\] + Withdraw{who: T::AccountId, amount: T::Balance}, + /// Some balance was reserved (moved from free to reserved). + Reserved{who: T::AccountId, value: T::Balance}, + /// Some balance was unreserved (moved from reserved to free). + Unreserved{who: T::AccountId, value: T::Balance}, /// Some balance was moved from the reserve of the first account to the second account. /// Final argument indicates the destination balance type. - /// \[from, to, balance, destination_status\] - ReserveRepatriated(T::AccountId, T::AccountId, T::Balance, Status), - /// Some amount was deposited into the account (e.g. for transaction fees). \[who, - /// deposit\] - Deposit(T::AccountId, T::Balance), - /// Some amount was withdrawn from the account (e.g. for transaction fees). \[who, value\] - Withdraw(T::AccountId, T::Balance), + ReserveRepatriated{from: T::AccountId, to: T::AccountId, balance: T::Balance, destination_status: Status}, /// Some amount was removed from the account (e.g. for misbehavior). \[who, /// amount_slashed\] - Slashed(T::AccountId, T::Balance), + Slashed{who: T::AccountId, amount_slashed: T::Balance}, } /// Old name generated by `decl_event`. @@ -742,7 +740,7 @@ pub struct DustCleaner, I: 'static = ()>( impl, I: 'static> Drop for DustCleaner { fn drop(&mut self) { if let Some((who, dust)) = self.0.take() { - Pallet::::deposit_event(Event::DustLost(who, dust.peek())); + Pallet::::deposit_event(Event::DustLost{account: who, balance: dust.peek()}); T::DustRemoval::on_unbalanced(dust); } } @@ -939,7 +937,7 @@ impl, I: 'static> Pallet { }); result.map(|(maybe_endowed, maybe_dust, result)| { if let Some(endowed) = maybe_endowed { - Self::deposit_event(Event::Endowed(who.clone(), endowed)); + Self::deposit_event(Event::Endowed{account: who.clone(), free_balance: endowed}); } let dust_cleaner = DustCleaner(maybe_dust.map(|dust| (who.clone(), dust))); (result, dust_cleaner) @@ -1051,12 +1049,12 @@ impl, I: 'static> Pallet { }, )?; - Self::deposit_event(Event::ReserveRepatriated( - slashed.clone(), - beneficiary.clone(), - actual, - status, - )); + Self::deposit_event(Event::ReserveRepatriated{ + from: slashed.clone(), + to: beneficiary.clone(), + balance: actual, + destination_status: status, + }); Ok(actual) } } @@ -1531,7 +1529,7 @@ where )?; // Emit transfer event. - Self::deposit_event(Event::Transfer(transactor.clone(), dest.clone(), value)); + Self::deposit_event(Event::Transfer{from: transactor.clone(), to: dest.clone(), value}); Ok(()) } @@ -1595,10 +1593,10 @@ where }, ) { Ok((imbalance, not_slashed)) => { - Self::deposit_event(Event::Slashed( - who.clone(), - value.saturating_sub(not_slashed), - )); + Self::deposit_event(Event::Slashed{ + who: who.clone(), + amount_slashed: value.saturating_sub(not_slashed), + }); return (imbalance, not_slashed) }, Err(_) => (), @@ -1773,7 +1771,7 @@ where Self::ensure_can_withdraw(&who, value.clone(), WithdrawReasons::RESERVE, account.free) })?; - Self::deposit_event(Event::Reserved(who.clone(), value)); + Self::deposit_event(Event::Reserved{who: who.clone(), value}); Ok(()) } @@ -1805,7 +1803,7 @@ where }, }; - Self::deposit_event(Event::Unreserved(who.clone(), actual.clone())); + Self::deposit_event(Event::Unreserved{who: who.clone(), value: actual.clone()}); value - actual } @@ -1846,10 +1844,10 @@ where (NegativeImbalance::new(actual), value - actual) }) { Ok((imbalance, not_slashed)) => { - Self::deposit_event(Event::Slashed( - who.clone(), - value.saturating_sub(not_slashed), - )); + Self::deposit_event(Event::Slashed{ + who: who.clone(), + amount_slashed: value.saturating_sub(not_slashed), + }); return (imbalance, not_slashed) }, Err(_) => (), @@ -1992,7 +1990,7 @@ where // `actual <= to_change` and `to_change <= amount`; qed; reserves[index].amount -= actual; - Self::deposit_event(Event::Slashed(who.clone(), actual)); + Self::deposit_event(Event::Slashed{who: who.clone(), amount_slashed: actual}); (imb, value - actual) }, Err(_) => (NegativeImbalance::zero(), value), diff --git a/frame/balances/src/tests.rs b/frame/balances/src/tests.rs index 6a6ebc692c34a..d02be25dd169f 100644 --- a/frame/balances/src/tests.rs +++ b/frame/balances/src/tests.rs @@ -444,7 +444,7 @@ macro_rules! decl_tests { let _ = Balances::withdraw( &2, 11, WithdrawReasons::TRANSFER, ExistenceRequirement::KeepAlive ); - System::assert_last_event(Event::Balances(crate::Event::Withdraw(2, 11))); + System::assert_last_event(Event::Balances(crate::Event::Withdraw{who: 2, amount: 11})); assert_eq!(Balances::free_balance(2), 100); assert_eq!(>::get(), 100); }); @@ -505,7 +505,7 @@ macro_rules! decl_tests { assert_ok!(Balances::reserve(&1, 110)); assert_ok!(Balances::repatriate_reserved(&1, &2, 41, Status::Free), 0); System::assert_last_event( - Event::Balances(crate::Event::ReserveRepatriated(1, 2, 41, Status::Free)) + Event::Balances(crate::Event::ReserveRepatriated{from: 1, to: 2, balance: 41, destination_status: Status::Free}) ); assert_eq!(Balances::reserved_balance(1), 69); assert_eq!(Balances::free_balance(1), 0); @@ -724,18 +724,18 @@ macro_rules! decl_tests { System::set_block_number(2); assert_ok!(Balances::reserve(&1, 10)); - System::assert_last_event(Event::Balances(crate::Event::Reserved(1, 10))); + System::assert_last_event(Event::Balances(crate::Event::Reserved{who: 1, value: 10})); System::set_block_number(3); assert!(Balances::unreserve(&1, 5).is_zero()); - System::assert_last_event(Event::Balances(crate::Event::Unreserved(1, 5))); + System::assert_last_event(Event::Balances(crate::Event::Unreserved{who: 1, value: 5})); System::set_block_number(4); assert_eq!(Balances::unreserve(&1, 6), 1); // should only unreserve 5 - System::assert_last_event(Event::Balances(crate::Event::Unreserved(1, 5))); + System::assert_last_event(Event::Balances(crate::Event::Unreserved{who: 1, value: 5})); }); } @@ -751,8 +751,8 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::NewAccount(1)), - Event::Balances(crate::Event::Endowed(1, 100)), - Event::Balances(crate::Event::BalanceSet(1, 100, 0)), + Event::Balances(crate::Event::Endowed{account: 1, free_balance: 100}), + Event::Balances(crate::Event::BalanceSet{who: 1, free: 100, reserved: 0}), ] ); @@ -763,8 +763,8 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::KilledAccount(1)), - Event::Balances(crate::Event::DustLost(1, 99)), - Event::Balances(crate::Event::Slashed(1, 1)), + Event::Balances(crate::Event::DustLost{account: 1, balance: 99}), + Event::Balances(crate::Event::Slashed{who: 1, amount_slashed: 1}), ] ); }); @@ -782,8 +782,8 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::NewAccount(1)), - Event::Balances(crate::Event::Endowed(1, 100)), - Event::Balances(crate::Event::BalanceSet(1, 100, 0)), + Event::Balances(crate::Event::Endowed{account: 1, free_balance: 100}), + Event::Balances(crate::Event::BalanceSet{who: 1, free: 100, reserved: 0}), ] ); @@ -794,7 +794,7 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::KilledAccount(1)), - Event::Balances(crate::Event::Slashed(1, 100)), + Event::Balances(crate::Event::Slashed{who: 1, amount_slashed: 100}), ] ); }); @@ -814,7 +814,7 @@ macro_rules! decl_tests { assert_eq!(Balances::slash(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive assert!(System::account_exists(&1)); - System::assert_last_event(Event::Balances(crate::Event::Slashed(1, 900))); + System::assert_last_event(Event::Balances(crate::Event::Slashed{who: 1, amount_slashed: 900})); // SCENARIO: Slash will kill account because not enough balance left. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index b2113a916caa5..9913b5940496e 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -164,8 +164,8 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { events(), [ Event::System(system::Event::NewAccount(1)), - Event::Balances(crate::Event::Endowed(1, 100)), - Event::Balances(crate::Event::BalanceSet(1, 100, 0)), + Event::Balances(crate::Event::Endowed{account: 1, free_balance: 100}), + Event::Balances(crate::Event::BalanceSet{who: 1, free: 100, reserved: 0}), ] ); @@ -173,7 +173,7 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { assert_eq!(res, (NegativeImbalance::new(98), 0)); // no events - assert_eq!(events(), [Event::Balances(crate::Event::Slashed(1, 98))]); + assert_eq!(events(), [Event::Balances(crate::Event::Slashed{who :1, amount_slashed: 98})]); let res = Balances::slash(&1, 1); assert_eq!(res, (NegativeImbalance::new(1), 0)); @@ -182,8 +182,8 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { events(), [ Event::System(system::Event::KilledAccount(1)), - Event::Balances(crate::Event::DustLost(1, 1)), - Event::Balances(crate::Event::Slashed(1, 1)), + Event::Balances(crate::Event::DustLost{account: 1, balance: 1}), + Event::Balances(crate::Event::Slashed{who: 1, amount_slashed: 1}) ] ); }); diff --git a/frame/balances/src/tests_reentrancy.rs b/frame/balances/src/tests_reentrancy.rs index 9a5ebb003af2c..e1d8cfe5a15c7 100644 --- a/frame/balances/src/tests_reentrancy.rs +++ b/frame/balances/src/tests_reentrancy.rs @@ -169,9 +169,9 @@ fn transfer_dust_removal_tst1_should_work() { // Verify the events assert_eq!(System::events().len(), 12); - System::assert_has_event(Event::Balances(crate::Event::Transfer(2, 3, 450))); - System::assert_has_event(Event::Balances(crate::Event::DustLost(2, 50))); - System::assert_has_event(Event::Balances(crate::Event::Deposit(1, 50))); + System::assert_has_event(Event::Balances(crate::Event::Transfer{from: 2, to: 3, value: 450})); + System::assert_has_event(Event::Balances(crate::Event::DustLost{account: 2, balance: 50})); + System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 50})); }); } @@ -197,9 +197,9 @@ fn transfer_dust_removal_tst2_should_work() { // Verify the events assert_eq!(System::events().len(), 10); - System::assert_has_event(Event::Balances(crate::Event::Transfer(2, 1, 450))); - System::assert_has_event(Event::Balances(crate::Event::DustLost(2, 50))); - System::assert_has_event(Event::Balances(crate::Event::Deposit(1, 50))); + System::assert_has_event(Event::Balances(crate::Event::Transfer{from: 2, to: 1, value: 450})); + System::assert_has_event(Event::Balances(crate::Event::DustLost{account: 2, balance: 50})); + System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 50})); }); } @@ -234,13 +234,14 @@ fn repatriating_reserved_balance_dust_removal_should_work() { // Verify the events assert_eq!(System::events().len(), 11); - System::assert_has_event(Event::Balances(crate::Event::ReserveRepatriated( - 2, - 1, - 450, - Status::Free, - ))); - System::assert_has_event(Event::Balances(crate::Event::DustLost(2, 50))); - System::assert_last_event(Event::Balances(crate::Event::Deposit(1, 50))); + System::assert_has_event(Event::Balances(crate::Event::ReserveRepatriated{ + from: 2, + to: 1, + balance: 450, + destination_status: Status::Free, + })); + + System::assert_last_event(Event::Balances(crate::Event::DustLost{account: 2, balance: 50})); + System::assert_last_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 50})); }); } From 39ad82501024c02b3365645a4abccb31e795c96c Mon Sep 17 00:00:00 2001 From: david Date: Mon, 11 Oct 2021 05:08:04 +0100 Subject: [PATCH 03/11] updated pallet event field names --- frame/bounties/src/benchmarking.rs | 6 +- frame/bounties/src/lib.rs | 42 +++--- frame/bounties/src/tests.rs | 10 +- frame/collective/src/benchmarking.rs | 16 +- frame/collective/src/lib.rs | 55 +++---- frame/collective/src/tests.rs | 140 +++++++++--------- frame/democracy/src/benchmarking.rs | 2 +- frame/democracy/src/lib.rs | 95 ++++++------ .../election-provider-multi-phase/src/lib.rs | 42 +++--- frame/elections-phragmen/src/lib.rs | 44 +++--- frame/elections/src/lib.rs | 23 ++- frame/example-offchain-worker/src/lib.rs | 5 +- frame/example/src/lib.rs | 10 +- frame/gilt/src/lib.rs | 20 +-- frame/grandpa/src/lib.rs | 10 +- frame/grandpa/src/tests.rs | 4 +- frame/identity/src/benchmarking.rs | 8 +- frame/identity/src/lib.rs | 59 ++++---- frame/im-online/src/lib.rs | 12 +- frame/indices/src/lib.rs | 22 +-- frame/lottery/src/lib.rs | 8 +- frame/membership/src/lib.rs | 2 +- frame/multisig/src/lib.rs | 36 ++--- frame/multisig/src/tests.rs | 2 +- frame/nicks/src/lib.rs | 30 ++-- frame/node-authorization/src/lib.rs | 36 ++--- 26 files changed, 360 insertions(+), 379 deletions(-) diff --git a/frame/bounties/src/benchmarking.rs b/frame/bounties/src/benchmarking.rs index 33af02fbb9ea0..ce805e24d1c8a 100644 --- a/frame/bounties/src/benchmarking.rs +++ b/frame/bounties/src/benchmarking.rs @@ -172,7 +172,7 @@ benchmarks! { let bounty_id = BountyCount::::get() - 1; }: close_bounty(RawOrigin::Root, bounty_id) verify { - assert_last_event::(Event::BountyCanceled(bounty_id).into()) + assert_last_event::(Event::BountyCanceled{index: bounty_id}.into()) } extend_bounty_expiry { @@ -184,7 +184,7 @@ benchmarks! { let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; }: _(RawOrigin::Signed(curator), bounty_id, Vec::new()) verify { - assert_last_event::(Event::BountyExtended(bounty_id).into()) + assert_last_event::(Event::BountyExtended{index: bounty_id}.into()) } spend_funds { @@ -207,7 +207,7 @@ benchmarks! { verify { ensure!(budget_remaining < BalanceOf::::max_value(), "Budget not used"); ensure!(missed_any == false, "Missed some"); - assert_last_event::(Event::BountyBecameActive(b - 1).into()) + assert_last_event::(Event::BountyBecameActive{index: b - 1}.into()) } impl_benchmark_test_suite!(Bounties, crate::tests::new_test_ext(), crate::tests::Test) diff --git a/frame/bounties/src/lib.rs b/frame/bounties/src/lib.rs index 69380502bad3f..c98d68287b321 100644 --- a/frame/bounties/src/lib.rs +++ b/frame/bounties/src/lib.rs @@ -228,20 +228,20 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// New bounty proposal. \[index\] - BountyProposed(BountyIndex), - /// A bounty proposal was rejected; funds were slashed. \[index, bond\] - BountyRejected(BountyIndex, BalanceOf), - /// A bounty proposal is funded and became active. \[index\] - BountyBecameActive(BountyIndex), - /// A bounty is awarded to a beneficiary. \[index, beneficiary\] - BountyAwarded(BountyIndex, T::AccountId), - /// A bounty is claimed by beneficiary. \[index, payout, beneficiary\] - BountyClaimed(BountyIndex, BalanceOf, T::AccountId), - /// A bounty is cancelled. \[index\] - BountyCanceled(BountyIndex), - /// A bounty expiry is extended. \[index\] - BountyExtended(BountyIndex), + /// New bounty proposal. + BountyProposed{index: BountyIndex}, + /// A bounty proposal was rejected; funds were slashed. + BountyRejected{index: BountyIndex, bond: BalanceOf}, + /// A bounty proposal is funded and became active. + BountyBecameActive{index: BountyIndex}, + /// A bounty is awarded to a beneficiary. + BountyAwarded{index: BountyIndex, beneficiary: T::AccountId}, + /// A bounty is claimed by beneficiary. + BountyClaimed{index: BountyIndex, payout: BalanceOf, beneficiary: T::AccountId}, + /// A bounty is cancelled. + BountyCanceled{index: BountyIndex}, + /// A bounty expiry is extended. + BountyExtended{index: BountyIndex}, } /// Number of bounty proposals that have been made. @@ -526,7 +526,7 @@ pub mod pallet { Ok(()) })?; - Self::deposit_event(Event::::BountyAwarded(bounty_id, beneficiary)); + Self::deposit_event(Event::::BountyAwarded{index: bounty_id, beneficiary}); Ok(()) } @@ -571,7 +571,7 @@ pub mod pallet { BountyDescriptions::::remove(bounty_id); - Self::deposit_event(Event::::BountyClaimed(bounty_id, payout, beneficiary)); + Self::deposit_event(Event::::BountyClaimed{index: bounty_id, payout, beneficiary}); Ok(()) } else { Err(Error::::UnexpectedStatus.into()) @@ -612,7 +612,7 @@ pub mod pallet { T::OnSlash::on_unbalanced(imbalance); *maybe_bounty = None; - Self::deposit_event(Event::::BountyRejected(bounty_id, value)); + Self::deposit_event(Event::::BountyRejected{index: bounty_id, bond: value}); // Return early, nothing else to do. return Ok( Some(::WeightInfo::close_bounty_proposed()).into() @@ -656,7 +656,7 @@ pub mod pallet { debug_assert!(res.is_ok()); *maybe_bounty = None; - Self::deposit_event(Event::::BountyCanceled(bounty_id)); + Self::deposit_event(Event::::BountyCanceled{index: bounty_id}); Ok(Some(::WeightInfo::close_bounty_active()).into()) }, ) @@ -696,7 +696,7 @@ pub mod pallet { Ok(()) })?; - Self::deposit_event(Event::::BountyExtended(bounty_id)); + Self::deposit_event(Event::::BountyExtended{index: bounty_id}); Ok(()) } } @@ -753,7 +753,7 @@ impl Pallet { Bounties::::insert(index, &bounty); BountyDescriptions::::insert(index, description); - Self::deposit_event(Event::::BountyProposed(index)); + Self::deposit_event(Event::::BountyProposed{index}); Ok(()) } @@ -787,7 +787,7 @@ impl pallet_treasury::SpendFunds for Pallet { bounty.value, )); - Self::deposit_event(Event::::BountyBecameActive(index)); + Self::deposit_event(Event::::BountyBecameActive{index}); false } else { *missed_any = true; diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index 96c09581fdd1e..ef96997e427ba 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -398,7 +398,7 @@ fn propose_bounty_works() { assert_ok!(Bounties::propose_bounty(Origin::signed(0), 10, b"1234567890".to_vec())); - assert_eq!(last_event(), BountiesEvent::BountyProposed(0)); + assert_eq!(last_event(), BountiesEvent::BountyProposed{index: 0}); let deposit: u64 = 85 + 5; assert_eq!(Balances::reserved_balance(0), deposit); @@ -460,7 +460,7 @@ fn close_bounty_works() { let deposit: u64 = 80 + 5; - assert_eq!(last_event(), BountiesEvent::BountyRejected(0, deposit)); + assert_eq!(last_event(), BountiesEvent::BountyRejected{index: 0, bond: deposit}); assert_eq!(Balances::reserved_balance(0), 0); assert_eq!(Balances::free_balance(0), 100 - deposit); @@ -692,7 +692,7 @@ fn award_and_claim_bounty_works() { assert_ok!(Bounties::claim_bounty(Origin::signed(1), 0)); - assert_eq!(last_event(), BountiesEvent::BountyClaimed(0, 56, 3)); + assert_eq!(last_event(), BountiesEvent::BountyClaimed{index: 0, payout: 56, beneficiary: 3}); assert_eq!(Balances::free_balance(4), 14); // initial 10 + fee 4 @@ -731,7 +731,7 @@ fn claim_handles_high_fee() { assert_ok!(Bounties::claim_bounty(Origin::signed(1), 0)); - assert_eq!(last_event(), BountiesEvent::BountyClaimed(0, 0, 3)); + assert_eq!(last_event(), BountiesEvent::BountyClaimed{index: 0, payout: 0, beneficiary: 3}); assert_eq!(Balances::free_balance(4), 70); // 30 + 50 - 10 assert_eq!(Balances::free_balance(3), 0); @@ -808,7 +808,7 @@ fn award_and_cancel() { assert_ok!(Bounties::unassign_curator(Origin::root(), 0)); assert_ok!(Bounties::close_bounty(Origin::root(), 0)); - assert_eq!(last_event(), BountiesEvent::BountyCanceled(0)); + assert_eq!(last_event(), BountiesEvent::BountyCanceled{index: 0}); assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 0); diff --git a/frame/collective/src/benchmarking.rs b/frame/collective/src/benchmarking.rs index c26a2b43f5b75..d22e38d8f050f 100644 --- a/frame/collective/src/benchmarking.rs +++ b/frame/collective/src/benchmarking.rs @@ -128,7 +128,7 @@ benchmarks_instance_pallet! { let proposal_hash = T::Hashing::hash_of(&proposal); // Note that execution fails due to mis-matched origin assert_last_event::( - Event::MemberExecuted(proposal_hash, Err(DispatchError::BadOrigin)).into() + Event::MemberExecuted{proposal_hash, result: Err(DispatchError::BadOrigin)}.into() ); } @@ -159,7 +159,7 @@ benchmarks_instance_pallet! { let proposal_hash = T::Hashing::hash_of(&proposal); // Note that execution fails due to mis-matched origin assert_last_event::( - Event::Executed(proposal_hash, Err(DispatchError::BadOrigin)).into() + Event::Executed{proposal_hash, result: Err(DispatchError::BadOrigin)}.into() ); } @@ -203,7 +203,7 @@ benchmarks_instance_pallet! { // New proposal is recorded assert_eq!(Collective::::proposals().len(), p as usize); let proposal_hash = T::Hashing::hash_of(&proposal); - assert_last_event::(Event::Proposed(caller, p - 1, proposal_hash, threshold).into()); + assert_last_event::(Event::Proposed{account: caller, proposal_index: p - 1, proposal_hash, threshold}.into()); } vote { @@ -359,7 +359,7 @@ benchmarks_instance_pallet! { verify { // The last proposal is removed. assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Disapproved(last_hash).into()); + assert_last_event::(Event::Disapproved{proposal_hash: last_hash}.into()); } close_early_approved { @@ -440,7 +440,7 @@ benchmarks_instance_pallet! { verify { // The last proposal is removed. assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Executed(last_hash, Err(DispatchError::BadOrigin)).into()); + assert_last_event::(Event::Executed{proposal_hash: last_hash, result: Err(DispatchError::BadOrigin)}.into()); } close_disapproved { @@ -514,7 +514,7 @@ benchmarks_instance_pallet! { }: close(SystemOrigin::Signed(caller), last_hash, index, Weight::max_value(), bytes_in_storage) verify { assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Disapproved(last_hash).into()); + assert_last_event::(Event::Disapproved{proposal_hash: last_hash}.into()); } close_approved { @@ -586,7 +586,7 @@ benchmarks_instance_pallet! { }: close(SystemOrigin::Signed(caller), last_hash, p - 1, Weight::max_value(), bytes_in_storage) verify { assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Executed(last_hash, Err(DispatchError::BadOrigin)).into()); + assert_last_event::(Event::Executed{proposal_hash: last_hash, result: Err(DispatchError::BadOrigin)}.into()); } disapprove_proposal { @@ -634,7 +634,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Root, last_hash) verify { assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Disapproved(last_hash).into()); + assert_last_event::(Event::Disapproved{proposal_hash: last_hash}.into()); } impl_benchmark_test_suite!(Collective, crate::tests::new_test_ext(), crate::tests::Test); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 89d4c8a150c36..02edb7c8435d2 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -279,27 +279,20 @@ pub mod pallet { pub enum Event, I: 'static = ()> { /// A motion (given hash) has been proposed (by given account) with a threshold (given /// `MemberCount`). - /// \[account, proposal_index, proposal_hash, threshold\] - Proposed(T::AccountId, ProposalIndex, T::Hash, MemberCount), + Proposed{account: T::AccountId, proposal_index: ProposalIndex, proposal_hash: T::Hash, threshold: MemberCount}, /// A motion (given hash) has been voted on by given account, leaving /// a tally (yes votes and no votes given respectively as `MemberCount`). - /// \[account, proposal_hash, voted, yes, no\] - Voted(T::AccountId, T::Hash, bool, MemberCount, MemberCount), + Voted{account: T::AccountId, proposal_hash: T::Hash, voted: bool, yes: MemberCount, no: MemberCount}, /// A motion was approved by the required threshold. - /// \[proposal_hash\] - Approved(T::Hash), + Approved{proposal_hash: T::Hash}, /// A motion was not approved by the required threshold. - /// \[proposal_hash\] - Disapproved(T::Hash), + Disapproved{proposal_hash: T::Hash}, /// A motion was executed; result will be `Ok` if it returned without error. - /// \[proposal_hash, result\] - Executed(T::Hash, DispatchResult), + Executed{proposal_hash: T::Hash, result: DispatchResult}, /// A single member did some action; result will be `Ok` if it returned without error. - /// \[proposal_hash, result\] - MemberExecuted(T::Hash, DispatchResult), + MemberExecuted{proposal_hash: T::Hash, result: DispatchResult}, /// A proposal was closed because its threshold was reached or after its duration was up. - /// \[proposal_hash, yes, no\] - Closed(T::Hash, MemberCount, MemberCount), + Closed{proposal_hash: T::Hash, yes: MemberCount, no: MemberCount}, } /// Old name generated by `decl_event`. @@ -435,10 +428,10 @@ pub mod pallet { let proposal_hash = T::Hashing::hash_of(&proposal); let result = proposal.dispatch(RawOrigin::Member(who).into()); - Self::deposit_event(Event::MemberExecuted( + Self::deposit_event(Event::MemberExecuted{ proposal_hash, - result.map(|_| ()).map_err(|e| e.error), - )); + result: result.map(|_| ()).map_err(|e| e.error), + }); Ok(get_result_weight(result) .map(|w| { @@ -514,10 +507,10 @@ pub mod pallet { if threshold < 2 { let seats = Self::members().len() as MemberCount; let result = proposal.dispatch(RawOrigin::Members(1, seats).into()); - Self::deposit_event(Event::Executed( + Self::deposit_event(Event::Executed{ proposal_hash, - result.map(|_| ()).map_err(|e| e.error), - )); + result: result.map(|_| ()).map_err(|e| e.error), + }); Ok(get_result_weight(result) .map(|w| { @@ -545,7 +538,7 @@ pub mod pallet { }; >::insert(proposal_hash, votes); - Self::deposit_event(Event::Proposed(who, index, proposal_hash, threshold)); + Self::deposit_event(Event::Proposed{account: who, proposal_index: index, proposal_hash, threshold}); Ok(Some(T::WeightInfo::propose_proposed( proposal_len as u32, // B @@ -613,7 +606,7 @@ pub mod pallet { let yes_votes = voting.ayes.len() as MemberCount; let no_votes = voting.nays.len() as MemberCount; - Self::deposit_event(Event::Voted(who, proposal, approve, yes_votes, no_votes)); + Self::deposit_event(Event::Voted{account: who, proposal_hash: proposal, voted: approve, yes: yes_votes, no: no_votes}); Voting::::insert(&proposal, voting); @@ -694,7 +687,7 @@ pub mod pallet { length_bound, proposal_weight_bound, )?; - Self::deposit_event(Event::Closed(proposal_hash, yes_votes, no_votes)); + Self::deposit_event(Event::Closed{proposal_hash, yes: yes_votes, no: no_votes}); let (proposal_weight, proposal_count) = Self::do_approve_proposal(seats, yes_votes, proposal_hash, proposal); return Ok(( @@ -706,7 +699,7 @@ pub mod pallet { ) .into()) } else if disapproved { - Self::deposit_event(Event::Closed(proposal_hash, yes_votes, no_votes)); + Self::deposit_event(Event::Closed{proposal_hash, yes: yes_votes, no: no_votes}); let proposal_count = Self::do_disapprove_proposal(proposal_hash); return Ok(( Some(T::WeightInfo::close_early_disapproved(seats, proposal_count)), @@ -739,7 +732,7 @@ pub mod pallet { length_bound, proposal_weight_bound, )?; - Self::deposit_event(Event::Closed(proposal_hash, yes_votes, no_votes)); + Self::deposit_event(Event::Closed{proposal_hash, yes: yes_votes, no: no_votes}); let (proposal_weight, proposal_count) = Self::do_approve_proposal(seats, yes_votes, proposal_hash, proposal); Ok(( @@ -751,7 +744,7 @@ pub mod pallet { ) .into()) } else { - Self::deposit_event(Event::Closed(proposal_hash, yes_votes, no_votes)); + Self::deposit_event(Event::Closed{proposal_hash, yes: yes_votes, no: no_votes}); let proposal_count = Self::do_disapprove_proposal(proposal_hash); Ok((Some(T::WeightInfo::close_disapproved(seats, proposal_count)), Pays::No).into()) } @@ -841,15 +834,15 @@ impl, I: 'static> Pallet { proposal_hash: T::Hash, proposal: >::Proposal, ) -> (Weight, u32) { - Self::deposit_event(Event::Approved(proposal_hash)); + Self::deposit_event(Event::Approved{proposal_hash}); let dispatch_weight = proposal.get_dispatch_info().weight; let origin = RawOrigin::Members(yes_votes, seats).into(); let result = proposal.dispatch(origin); - Self::deposit_event(Event::Executed( + Self::deposit_event(Event::Executed{ proposal_hash, - result.map(|_| ()).map_err(|e| e.error), - )); + result: result.map(|_| ()).map_err(|e| e.error), + }); // default to the dispatch info weight for safety let proposal_weight = get_result_weight(result).unwrap_or(dispatch_weight); // P1 @@ -859,7 +852,7 @@ impl, I: 'static> Pallet { fn do_disapprove_proposal(proposal_hash: T::Hash) -> u32 { // disapproved - Self::deposit_event(Event::Disapproved(proposal_hash)); + Self::deposit_event(Event::Disapproved{proposal_hash}); Self::remove_proposal(proposal_hash) } diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index b8feb64867cf8..82b25c73b081b 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -216,11 +216,11 @@ fn close_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 3))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::Collective(CollectiveEvent::Voted(2, hash, true, 2, 0))), - record(Event::Collective(CollectiveEvent::Closed(hash, 2, 1))), - record(Event::Collective(CollectiveEvent::Disapproved(hash))) + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), + record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 2, no: 1})), + record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})) ] ); }); @@ -315,11 +315,11 @@ fn close_with_prime_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 3))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::Collective(CollectiveEvent::Voted(2, hash, true, 2, 0))), - record(Event::Collective(CollectiveEvent::Closed(hash, 2, 1))), - record(Event::Collective(CollectiveEvent::Disapproved(hash))) + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), + record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 2, no: 1})), + record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})) ] ); }); @@ -354,15 +354,15 @@ fn close_with_voting_prime_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 3))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::Collective(CollectiveEvent::Voted(2, hash, true, 2, 0))), - record(Event::Collective(CollectiveEvent::Closed(hash, 3, 0))), - record(Event::Collective(CollectiveEvent::Approved(hash))), - record(Event::Collective(CollectiveEvent::Executed( - hash, - Err(DispatchError::BadOrigin) - ))) + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), + record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 3, no: 0})), + record(Event::Collective(CollectiveEvent::Approved{proposal_hash: hash})), + record(Event::Collective(CollectiveEvent::Executed{ + proposal_hash: hash, + result: Err(DispatchError::BadOrigin) + })) ] ); }); @@ -404,16 +404,16 @@ fn close_with_no_prime_but_majority_works() { assert_eq!( System::events(), vec![ - record(Event::CollectiveMajority(CollectiveEvent::Proposed(1, 0, hash, 5))), - record(Event::CollectiveMajority(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::CollectiveMajority(CollectiveEvent::Voted(2, hash, true, 2, 0))), - record(Event::CollectiveMajority(CollectiveEvent::Voted(3, hash, true, 3, 0))), - record(Event::CollectiveMajority(CollectiveEvent::Closed(hash, 5, 0))), - record(Event::CollectiveMajority(CollectiveEvent::Approved(hash))), - record(Event::CollectiveMajority(CollectiveEvent::Executed( - hash, - Err(DispatchError::BadOrigin) - ))) + record(Event::CollectiveMajority(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 5})), + record(Event::CollectiveMajority(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::CollectiveMajority(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), + record(Event::CollectiveMajority(CollectiveEvent::Voted{account: 3, proposal_hash: hash, voted: true, yes: 3, no: 0})), + record(Event::CollectiveMajority(CollectiveEvent::Closed{proposal_hash: hash, yes: 5, no: 0})), + record(Event::CollectiveMajority(CollectiveEvent::Approved{proposal_hash: hash})), + record(Event::CollectiveMajority(CollectiveEvent::Executed{ + proposal_hash: hash, + result: Err(DispatchError::BadOrigin) + })) ] ); }); @@ -537,7 +537,7 @@ fn propose_works() { assert_eq!( System::events(), - vec![record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 3)))] + vec![record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3}))] ); }); } @@ -696,9 +696,9 @@ fn motions_vote_after_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 2))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, false, 0, 1))), + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 2})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: false, yes: 0, no: 1})), ] ); }); @@ -812,15 +812,15 @@ fn motions_approval_with_enough_votes_and_lower_voting_threshold_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 2))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::Collective(CollectiveEvent::Voted(2, hash, true, 2, 0))), - record(Event::Collective(CollectiveEvent::Closed(hash, 2, 0))), - record(Event::Collective(CollectiveEvent::Approved(hash))), - record(Event::Collective(CollectiveEvent::Executed( - hash, - Err(DispatchError::BadOrigin) - ))), + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 2})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), + record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 2, no: 0})), + record(Event::Collective(CollectiveEvent::Approved{proposal_hash: hash})), + record(Event::Collective(CollectiveEvent::Executed{ + proposal_hash: hash, + result: Err(DispatchError::BadOrigin) + })), ] ); @@ -840,14 +840,14 @@ fn motions_approval_with_enough_votes_and_lower_voting_threshold_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed(1, 1, hash, 2))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::Collective(CollectiveEvent::Voted(2, hash, true, 2, 0))), - record(Event::Collective(CollectiveEvent::Voted(3, hash, true, 3, 0))), - record(Event::Collective(CollectiveEvent::Closed(hash, 3, 0))), - record(Event::Collective(CollectiveEvent::Approved(hash))), + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 1, proposal_hash: hash, threshold: 2})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 3, proposal_hash: hash, voted: true, yes: 3, no: 0})), + record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 3, no: 0})), + record(Event::Collective(CollectiveEvent::Approved{proposal_hash: hash})), record(Event::Democracy(mock_democracy::pallet::Event::::ExternalProposed)), - record(Event::Collective(CollectiveEvent::Executed(hash, Ok(())))), + record(Event::Collective(CollectiveEvent::Executed{proposal_hash: hash, result: Ok(())})), ] ); }); @@ -873,11 +873,11 @@ fn motions_disapproval_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 3))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::Collective(CollectiveEvent::Voted(2, hash, false, 1, 1))), - record(Event::Collective(CollectiveEvent::Closed(hash, 1, 1))), - record(Event::Collective(CollectiveEvent::Disapproved(hash))), + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: false, yes: 1, no: 1})), + record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 1, no: 1})), + record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})), ] ); }); @@ -903,15 +903,15 @@ fn motions_approval_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 2))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::Collective(CollectiveEvent::Voted(2, hash, true, 2, 0))), - record(Event::Collective(CollectiveEvent::Closed(hash, 2, 0))), - record(Event::Collective(CollectiveEvent::Approved(hash))), - record(Event::Collective(CollectiveEvent::Executed( - hash, - Err(DispatchError::BadOrigin) - ))), + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 2})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), + record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 2, no: 0})), + record(Event::Collective(CollectiveEvent::Approved{proposal_hash: hash})), + record(Event::Collective(CollectiveEvent::Executed{ + proposal_hash: hash, + result: Err(DispatchError::BadOrigin) + })), ] ); }); @@ -932,7 +932,7 @@ fn motion_with_no_votes_closes_with_disapproval() { )); assert_eq!( System::events()[0], - record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 3))) + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})) ); // Closing the motion too early is not possible because it has neither @@ -951,11 +951,11 @@ fn motion_with_no_votes_closes_with_disapproval() { // Events show that the close ended in a disapproval. assert_eq!( System::events()[1], - record(Event::Collective(CollectiveEvent::Closed(hash, 0, 3))) + record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 0, no: 3})) ); assert_eq!( System::events()[2], - record(Event::Collective(CollectiveEvent::Disapproved(hash))) + record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})) ); }) } @@ -1015,10 +1015,10 @@ fn disapprove_proposal_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed(1, 0, hash, 2))), - record(Event::Collective(CollectiveEvent::Voted(1, hash, true, 1, 0))), - record(Event::Collective(CollectiveEvent::Voted(2, hash, true, 2, 0))), - record(Event::Collective(CollectiveEvent::Disapproved(hash))), + record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 2})), + record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), + record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), + record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})), ] ); }) diff --git a/frame/democracy/src/benchmarking.rs b/frame/democracy/src/benchmarking.rs index 34bcb0da301e6..88cd64cfbebd9 100644 --- a/frame/democracy/src/benchmarking.rs +++ b/frame/democracy/src/benchmarking.rs @@ -774,7 +774,7 @@ benchmarks! { }: enact_proposal(RawOrigin::Root, proposal_hash, 0) verify { // Fails due to mismatched origin - assert_last_event::(Event::::Executed(0, Err(BadOrigin.into())).into()); + assert_last_event::(Event::::Executed{ref_index: 0, result: Err(BadOrigin.into())}.into()); } #[extra] diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index 893e4676bef7b..cc08570ccda50 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -507,45 +507,40 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// A motion has been proposed by a public account. \[proposal_index, deposit\] - Proposed(PropIndex, BalanceOf), - /// A public proposal has been tabled for referendum vote. \[proposal_index, deposit, - /// depositors\] - Tabled(PropIndex, BalanceOf, Vec), + /// A motion has been proposed by a public account. + Proposed{proposal_index: PropIndex, deposit: BalanceOf}, + /// A public proposal has been tabled for referendum vote. + Tabled{proposal_index: PropIndex, deposit: BalanceOf, depositors: Vec}, /// An external proposal has been tabled. ExternalTabled, - /// A referendum has begun. \[ref_index, threshold\] - Started(ReferendumIndex, VoteThreshold), - /// A proposal has been approved by referendum. \[ref_index\] - Passed(ReferendumIndex), - /// A proposal has been rejected by referendum. \[ref_index\] - NotPassed(ReferendumIndex), - /// A referendum has been cancelled. \[ref_index\] - Cancelled(ReferendumIndex), - /// A proposal has been enacted. \[ref_index, result\] - Executed(ReferendumIndex, DispatchResult), - /// An account has delegated their vote to another account. \[who, target\] - Delegated(T::AccountId, T::AccountId), - /// An \[account\] has cancelled a previous delegation operation. - Undelegated(T::AccountId), - /// An external proposal has been vetoed. \[who, proposal_hash, until\] - Vetoed(T::AccountId, T::Hash, T::BlockNumber), - /// A proposal's preimage was noted, and the deposit taken. \[proposal_hash, who, deposit\] - PreimageNoted(T::Hash, T::AccountId, BalanceOf), + /// A referendum has begun. + Started{ref_index: ReferendumIndex, threshold: VoteThreshold}, + /// A proposal has been approved by referendum. + Passed{ref_index: ReferendumIndex}, + /// A proposal has been rejected by referendum. + NotPassed{ref_index: ReferendumIndex}, + /// A referendum has been cancelled. + Cancelled{ref_index: ReferendumIndex}, + /// A proposal has been enacted. + Executed{ref_index: ReferendumIndex, result: DispatchResult}, + /// An account has delegated their vote to another account. + Delegated{who: T::AccountId, target: T::AccountId}, + /// An account has cancelled a previous delegation operation. + Undelegated{account: T::AccountId}, + /// An external proposal has been vetoed. + Vetoed{who: T::AccountId, proposal_hash: T::Hash, until: T::BlockNumber}, + /// A proposal's preimage was noted, and the deposit taken. + PreimageNoted{proposal_hash: T::Hash, who: T::AccountId, deposit: BalanceOf}, /// A proposal preimage was removed and used (the deposit was returned). - /// \[proposal_hash, provider, deposit\] - PreimageUsed(T::Hash, T::AccountId, BalanceOf), + PreimageUsed{proposal_hash: T::Hash, provider: T::AccountId, deposit: BalanceOf}, /// A proposal could not be executed because its preimage was invalid. - /// \[proposal_hash, ref_index\] - PreimageInvalid(T::Hash, ReferendumIndex), + PreimageInvalid{proposal_hash: T::Hash, ref_index: ReferendumIndex}, /// A proposal could not be executed because its preimage was missing. - /// \[proposal_hash, ref_index\] - PreimageMissing(T::Hash, ReferendumIndex), + PreimageMissing{proposal_hash: T::Hash, ref_index: ReferendumIndex}, /// A registered preimage was removed and the deposit collected by the reaper. - /// \[proposal_hash, provider, deposit, reaper\] - PreimageReaped(T::Hash, T::AccountId, BalanceOf, T::AccountId), - /// A proposal \[hash\] has been blacklisted permanently. - Blacklisted(T::Hash), + PreimageReaped{proposal_hash: T::Hash, provider: T::AccountId, deposit: BalanceOf, reaper: T::AccountId}, + /// A proposal_hash has been blacklisted permanently. + Blacklisted{proposal_hash: T::Hash}, } #[pallet::error] @@ -657,7 +652,7 @@ pub mod pallet { >::append((index, proposal_hash, who)); - Self::deposit_event(Event::::Proposed(index, value)); + Self::deposit_event(Event::::Proposed{proposal_index: index, deposit: value}); Ok(()) } @@ -882,7 +877,7 @@ pub mod pallet { let until = >::block_number() + T::CooloffPeriod::get(); >::insert(&proposal_hash, (until, existing_vetoers)); - Self::deposit_event(Event::::Vetoed(who, proposal_hash, until)); + Self::deposit_event(Event::::Vetoed{who, proposal_hash, until}); >::kill(); Ok(()) } @@ -1104,7 +1099,7 @@ pub mod pallet { T::Currency::repatriate_reserved(&provider, &who, deposit, BalanceStatus::Free); debug_assert!(res.is_ok()); >::remove(&proposal_hash); - Self::deposit_event(Event::::PreimageReaped(proposal_hash, provider, deposit, who)); + Self::deposit_event(Event::::PreimageReaped{proposal_hash, provider, deposit, reaper: who}); Ok(()) } @@ -1249,7 +1244,7 @@ pub mod pallet { } } - Self::deposit_event(Event::::Blacklisted(proposal_hash)); + Self::deposit_event(Event::::Blacklisted{proposal_hash}); Ok(()) } @@ -1330,7 +1325,7 @@ impl Pallet { /// Remove a referendum. pub fn internal_cancel_referendum(ref_index: ReferendumIndex) { - Self::deposit_event(Event::::Cancelled(ref_index)); + Self::deposit_event(Event::::Cancelled{ref_index}); ReferendumInfoOf::::remove(ref_index); } @@ -1532,7 +1527,7 @@ impl Pallet { T::Currency::extend_lock(DEMOCRACY_ID, &who, balance, WithdrawReasons::TRANSFER); Ok(votes) })?; - Self::deposit_event(Event::::Delegated(who, target)); + Self::deposit_event(Event::::Delegated{who, target}); Ok(votes) } @@ -1558,7 +1553,7 @@ impl Pallet { Voting::Direct { .. } => Err(Error::::NotDelegating.into()), } })?; - Self::deposit_event(Event::::Undelegated(who)); + Self::deposit_event(Event::::Undelegated{account: who}); Ok(votes) } @@ -1589,7 +1584,7 @@ impl Pallet { ReferendumStatus { end, proposal_hash, threshold, delay, tally: Default::default() }; let item = ReferendumInfo::Ongoing(status); >::insert(ref_index, item); - Self::deposit_event(Event::::Started(ref_index, threshold)); + Self::deposit_event(Event::::Started{ref_index, threshold}); ref_index } @@ -1635,7 +1630,7 @@ impl Pallet { for d in &depositors { T::Currency::unreserve(d, deposit); } - Self::deposit_event(Event::::Tabled(prop_index, deposit, depositors)); + Self::deposit_event(Event::::Tabled{proposal_index: prop_index, deposit, depositors}); Self::inject_referendum( now + T::VotingPeriod::get(), proposal, @@ -1655,22 +1650,22 @@ impl Pallet { if let Ok(proposal) = T::Proposal::decode(&mut &data[..]) { let err_amount = T::Currency::unreserve(&provider, deposit); debug_assert!(err_amount.is_zero()); - Self::deposit_event(Event::::PreimageUsed(proposal_hash, provider, deposit)); + Self::deposit_event(Event::::PreimageUsed{proposal_hash, provider, deposit}); let res = proposal .dispatch(frame_system::RawOrigin::Root.into()) .map(|_| ()) .map_err(|e| e.error); - Self::deposit_event(Event::::Executed(index, res)); + Self::deposit_event(Event::::Executed{ref_index: index, result: res}); Ok(()) } else { T::Slash::on_unbalanced(T::Currency::slash_reserved(&provider, deposit).0); - Self::deposit_event(Event::::PreimageInvalid(proposal_hash, index)); + Self::deposit_event(Event::::PreimageInvalid{proposal_hash, ref_index: index}); Err(Error::::PreimageInvalid.into()) } } else { - Self::deposit_event(Event::::PreimageMissing(proposal_hash, index)); + Self::deposit_event(Event::::PreimageMissing{proposal_hash, ref_index: index}); Err(Error::::PreimageMissing.into()) } } @@ -1684,7 +1679,7 @@ impl Pallet { let approved = status.threshold.approved(status.tally, total_issuance); if approved { - Self::deposit_event(Event::::Passed(index)); + Self::deposit_event(Event::::Passed{ref_index: index}); if status.delay.is_zero() { let _ = Self::do_enact_proposal(status.proposal_hash, index); } else { @@ -1713,7 +1708,7 @@ impl Pallet { } } } else { - Self::deposit_event(Event::::NotPassed(index)); + Self::deposit_event(Event::::NotPassed{ref_index: index}); } approved @@ -1870,7 +1865,7 @@ impl Pallet { }; >::insert(proposal_hash, a); - Self::deposit_event(Event::::PreimageNoted(proposal_hash, who, deposit)); + Self::deposit_event(Event::::PreimageNoted{proposal_hash, who, deposit}); Ok(()) } @@ -1896,7 +1891,7 @@ impl Pallet { }; >::insert(proposal_hash, a); - Self::deposit_event(Event::::PreimageNoted(proposal_hash, who, free)); + Self::deposit_event(Event::::PreimageNoted{proposal_hash, who, deposit: free}); Ok(()) } diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index a7863fafa7747..76e9e2021077c 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -886,10 +886,10 @@ pub mod pallet { log!(info, "queued unsigned solution with score {:?}", ready.score); let ejected_a_solution = >::exists(); >::put(ready); - Self::deposit_event(Event::SolutionStored( - ElectionCompute::Unsigned, - ejected_a_solution, - )); + Self::deposit_event(Event::SolutionStored{ + election_compute: ElectionCompute::Unsigned, + prev_ejected: ejected_a_solution, + }); Ok(None.into()) } @@ -1012,7 +1012,7 @@ pub mod pallet { } signed_submissions.put(); - Self::deposit_event(Event::SolutionStored(ElectionCompute::Signed, ejected_a_solution)); + Self::deposit_event(Event::SolutionStored{election_compute: ElectionCompute::Signed, prev_ejected: ejected_a_solution}); Ok(()) } } @@ -1026,18 +1026,18 @@ pub mod pallet { /// solution is unsigned, this means that it has also been processed. /// /// The `bool` is `true` when a previous solution was ejected to make room for this one. - SolutionStored(ElectionCompute, bool), + SolutionStored{election_compute: ElectionCompute, prev_ejected: bool}, /// The election has been finalized, with `Some` of the given computation, or else if the /// election failed, `None`. - ElectionFinalized(Option), + ElectionFinalized{election_compute: Option}, /// An account has been rewarded for their signed submission being finalized. - Rewarded(::AccountId, BalanceOf), + Rewarded{account: ::AccountId, value: BalanceOf}, /// An account has been slashed for submitting an invalid signed submission. - Slashed(::AccountId, BalanceOf), + Slashed{account: ::AccountId, value: BalanceOf}, /// The signed phase of the given round has started. - SignedPhaseStarted(u32), + SignedPhaseStarted{round: u32}, /// The unsigned phase of the given round has started. - UnsignedPhaseStarted(u32), + UnsignedPhaseStarted{round: u32}, } /// Error of the pallet that can be returned in response to dispatches. @@ -1245,7 +1245,7 @@ impl Pallet { pub fn on_initialize_open_signed() { log!(info, "Starting signed phase round {}.", Self::round()); >::put(Phase::Signed); - Self::deposit_event(Event::SignedPhaseStarted(Self::round())); + Self::deposit_event(Event::SignedPhaseStarted{round: Self::round()}); } /// Logic for [`>::on_initialize`] when unsigned phase is being opened. @@ -1253,7 +1253,7 @@ impl Pallet { let round = Self::round(); log!(info, "Starting unsigned phase round {} enabled {}.", round, enabled); >::put(Phase::Unsigned((enabled, now))); - Self::deposit_event(Event::UnsignedPhaseStarted(round)); + Self::deposit_event(Event::UnsignedPhaseStarted{round}); } /// Parts of [`create_snapshot`] that happen inside of this pallet. @@ -1473,14 +1473,14 @@ impl Pallet { |ReadySolution { supports, compute, .. }| Ok((supports, compute)), ) .map(|(supports, compute)| { - Self::deposit_event(Event::ElectionFinalized(Some(compute))); + Self::deposit_event(Event::ElectionFinalized{election_compute: Some(compute)}); if Self::round() != 1 { log!(info, "Finalized election round with compute {:?}.", compute); } supports }) .map_err(|err| { - Self::deposit_event(Event::ElectionFinalized(None)); + Self::deposit_event(Event::ElectionFinalized{election_compute: None}); if Self::round() != 1 { log!(warn, "Failed to finalize election round. reason {:?}", err); } @@ -1737,7 +1737,7 @@ mod tests { roll_to(15); assert_eq!(MultiPhase::current_phase(), Phase::Signed); - assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted(1)]); + assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted{round: 1}]); assert!(MultiPhase::snapshot().is_some()); assert_eq!(MultiPhase::round(), 1); @@ -1750,7 +1750,7 @@ mod tests { assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); assert_eq!( multi_phase_events(), - vec![Event::SignedPhaseStarted(1), Event::UnsignedPhaseStarted(1)], + vec![Event::SignedPhaseStarted{round: 1}, Event::UnsignedPhaseStarted{round: 1}], ); assert!(MultiPhase::snapshot().is_some()); @@ -1861,7 +1861,7 @@ mod tests { assert_eq!(MultiPhase::current_phase(), Phase::Off); roll_to(15); - assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted(1)]); + assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted{round: 1}]); assert_eq!(MultiPhase::current_phase(), Phase::Signed); assert_eq!(MultiPhase::round(), 1); @@ -1873,8 +1873,8 @@ mod tests { assert_eq!( multi_phase_events(), vec![ - Event::SignedPhaseStarted(1), - Event::ElectionFinalized(Some(ElectionCompute::Fallback)) + Event::SignedPhaseStarted{round: 1}, + Event::ElectionFinalized{election_compute: Some(ElectionCompute::Fallback)} ], ); // All storage items must be cleared. @@ -1896,7 +1896,7 @@ mod tests { assert_eq!(MultiPhase::current_phase(), Phase::Off); roll_to(15); - assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted(1)]); + assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted{round: 1}]); assert_eq!(MultiPhase::current_phase(), Phase::Signed); assert_eq!(MultiPhase::round(), 1); diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index d7b42383da757..29bb5b60a3359 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -425,7 +425,7 @@ pub mod pallet { Renouncing::Member => { let _ = Self::remove_and_replace_member(&who, false) .map_err(|_| Error::::InvalidRenouncing)?; - Self::deposit_event(Event::Renounced(who)); + Self::deposit_event(Event::Renounced{candidate: who}); }, Renouncing::RunnerUp => { >::try_mutate::<_, Error, _>(|runners_up| { @@ -437,7 +437,7 @@ pub mod pallet { let SeatHolder { deposit, .. } = runners_up.remove(index); let _remainder = T::Currency::unreserve(&who, deposit); debug_assert!(_remainder.is_zero()); - Self::deposit_event(Event::Renounced(who)); + Self::deposit_event(Event::Renounced{candidate: who}); Ok(()) })?; }, @@ -450,7 +450,7 @@ pub mod pallet { let (_removed, deposit) = candidates.remove(index); let _remainder = T::Currency::unreserve(&who, deposit); debug_assert!(_remainder.is_zero()); - Self::deposit_event(Event::Renounced(who)); + Self::deposit_event(Event::Renounced{candidate: who}); Ok(()) })?; }, @@ -496,7 +496,7 @@ pub mod pallet { let had_replacement = Self::remove_and_replace_member(&who, true)?; debug_assert_eq!(has_replacement, had_replacement); - Self::deposit_event(Event::MemberKicked(who.clone())); + Self::deposit_event(Event::MemberKicked{member: who.clone()}); if !had_replacement { Self::do_phragmen(); @@ -534,29 +534,29 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// A new term with \[new_members\]. This indicates that enough candidates existed to run + /// A new term with new_members. This indicates that enough candidates existed to run /// the election, not that enough have has been elected. The inner value must be examined /// for this purpose. A `NewTerm(\[\])` indicates that some candidates got their bond /// slashed and none were elected, whilst `EmptyTerm` means that no candidates existed to /// begin with. - NewTerm(Vec<(::AccountId, BalanceOf)>), + NewTerm{new_members: Vec<(::AccountId, BalanceOf)>}, /// No (or not enough) candidates existed for this round. This is different from /// `NewTerm(\[\])`. See the description of `NewTerm`. EmptyTerm, /// Internal error happened while trying to perform election. ElectionError, - /// A \[member\] has been removed. This should always be followed by either `NewTerm` or + /// A member has been removed. This should always be followed by either `NewTerm` or /// `EmptyTerm`. - MemberKicked(::AccountId), + MemberKicked{member: ::AccountId}, /// Someone has renounced their candidacy. - Renounced(::AccountId), - /// A \[candidate\] was slashed by \[amount\] due to failing to obtain a seat as member or + Renounced{candidate: ::AccountId}, + /// A candidate was slashed by amount due to failing to obtain a seat as member or /// runner-up. /// /// Note that old members and runners-up are also candidates. - CandidateSlashed(::AccountId, BalanceOf), - /// A \[seat holder\] was slashed by \[amount\] by being forcefully removed from the set. - SeatHolderSlashed(::AccountId, BalanceOf), + CandidateSlashed{candidate: ::AccountId, amount: BalanceOf}, + /// A seat holder was slashed by amount by being forcefully removed from the set. + SeatHolderSlashed{seat_holder: ::AccountId, amount: BalanceOf}, } #[deprecated(note = "use `Event` instead")] @@ -748,7 +748,7 @@ impl Pallet { let (imbalance, _remainder) = T::Currency::slash_reserved(who, removed.deposit); debug_assert!(_remainder.is_zero()); T::LoserCandidate::on_unbalanced(imbalance); - Self::deposit_event(Event::SeatHolderSlashed(who.clone(), removed.deposit)); + Self::deposit_event(Event::SeatHolderSlashed{seat_holder: who.clone(), amount: removed.deposit}); } else { T::Currency::unreserve(who, removed.deposit); } @@ -1001,7 +1001,7 @@ impl Pallet { { let (imbalance, _) = T::Currency::slash_reserved(c, *d); T::LoserCandidate::on_unbalanced(imbalance); - Self::deposit_event(Event::CandidateSlashed(c.clone(), *d)); + Self::deposit_event(Event::CandidateSlashed{candidate: c.clone(), amount: *d}); } }); @@ -1041,7 +1041,7 @@ impl Pallet { // clean candidates. >::kill(); - Self::deposit_event(Event::NewTerm(new_members_sorted_by_id)); + Self::deposit_event(Event::NewTerm{new_members: new_members_sorted_by_id}); >::mutate(|v| *v += 1); }) .map_err(|e| { @@ -2147,10 +2147,10 @@ mod tests { System::set_block_number(5); Elections::on_initialize(System::block_number()); - System::assert_last_event(Event::Elections(super::Event::NewTerm(vec![ + System::assert_last_event(Event::Elections(super::Event::NewTerm{new_members: vec![ (4, 40), (5, 50), - ]))); + ]})); assert_eq!(members_and_stake(), vec![(4, 40), (5, 50)]); assert_eq!(runners_up_and_stake(), vec![]); @@ -2161,7 +2161,7 @@ mod tests { System::set_block_number(10); Elections::on_initialize(System::block_number()); - System::assert_last_event(Event::Elections(super::Event::NewTerm(vec![]))); + System::assert_last_event(Event::Elections(super::Event::NewTerm{new_members: vec![]})); // outgoing have lost their bond. assert_eq!(balances(&4), (37, 0)); @@ -2231,7 +2231,7 @@ mod tests { assert_eq!(Elections::election_rounds(), 1); assert!(members_ids().is_empty()); - System::assert_last_event(Event::Elections(super::Event::NewTerm(vec![]))); + System::assert_last_event(Event::Elections(super::Event::NewTerm{new_members: vec![]})); }); } @@ -2583,10 +2583,10 @@ mod tests { // 5 is an outgoing loser. will also get slashed. assert_eq!(balances(&5), (45, 2)); - System::assert_has_event(Event::Elections(super::Event::NewTerm(vec![ + System::assert_has_event(Event::Elections(super::Event::NewTerm{new_members: vec![ (4, 40), (5, 50), - ]))); + ]})); }) } diff --git a/frame/elections/src/lib.rs b/frame/elections/src/lib.rs index ac13bce31b0f6..d58caa8b21c6e 100644 --- a/frame/elections/src/lib.rs +++ b/frame/elections/src/lib.rs @@ -465,15 +465,14 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// Reaped \[voter, reaper\]. - VoterReaped(T::AccountId, T::AccountId), - /// Slashed \[reaper\]. - BadReaperSlashed(T::AccountId), - /// A tally (for approval votes of \[seats\]) has started. - TallyStarted(u32), + /// Reaped + VoterReaped{voter: T::AccountId, reaper: T::AccountId}, + /// Slashed + BadReaperSlashed{reaper: T::AccountId}, + /// A tally (for approval votes of seats) has started. + TallyStarted{seats: u32}, /// A tally (for approval votes of seat(s)) has ended (with one or more new members). - /// \[incoming, outgoing\] - TallyFinalized(Vec, Vec), + TallyFinalized{incoming: Vec, outgoing: Vec}, } #[pallet::call] @@ -590,11 +589,11 @@ pub mod pallet { T::VotingBond::get(), BalanceStatus::Free, )?; - Self::deposit_event(Event::::VoterReaped(who, reporter)); + Self::deposit_event(Event::::VoterReaped{voter: who, reaper: reporter}); } else { let imbalance = T::Currency::slash_reserved(&reporter, T::VotingBond::get()).0; T::BadReaper::on_unbalanced(imbalance); - Self::deposit_event(Event::::BadReaperSlashed(reporter)); + Self::deposit_event(Event::::BadReaperSlashed{reaper: reporter}); } Ok(()) } @@ -1024,7 +1023,7 @@ impl Pallet { leaderboard_size ]); - Self::deposit_event(Event::::TallyStarted(empty_seats as u32)); + Self::deposit_event(Event::::TallyStarted{seats: empty_seats as u32}); } } @@ -1118,7 +1117,7 @@ impl Pallet { new_candidates.truncate(last_index + 1); } - Self::deposit_event(Event::::TallyFinalized(incoming, outgoing)); + Self::deposit_event(Event::::TallyFinalized{incoming, outgoing}); >::put(new_candidates); CandidateCount::::put(count); diff --git a/frame/example-offchain-worker/src/lib.rs b/frame/example-offchain-worker/src/lib.rs index 9b63ffa663ee2..54f1a097bb003 100644 --- a/frame/example-offchain-worker/src/lib.rs +++ b/frame/example-offchain-worker/src/lib.rs @@ -288,8 +288,7 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Event generated when new price is accepted to contribute to the average. - /// \[price, who\] - NewPrice(u32, T::AccountId), + NewPrice{price: u32, who: T::AccountId}, } #[pallet::validate_unsigned] @@ -655,7 +654,7 @@ impl Pallet { .expect("The average is not empty, because it was just mutated; qed"); log::info!("Current average price is: {}", average); // here we are raising the NewPrice event - Self::deposit_event(Event::NewPrice(price, who)); + Self::deposit_event(Event::NewPrice{price, who}); } /// Calculate current average price. diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index 981274b1ba739..ec09930f676ef 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -523,7 +523,7 @@ pub mod pallet { }); // Let's deposit an event to let the outside world know this happened. - Self::deposit_event(Event::AccumulateDummy(increase_by)); + Self::deposit_event(Event::AccumulateDummy{balance: increase_by}); // All good, no refund. Ok(()) @@ -555,7 +555,7 @@ pub mod pallet { // Put the new value into storage. >::put(new_value); - Self::deposit_event(Event::SetDummy(new_value)); + Self::deposit_event(Event::SetDummy{balance: new_value}); // All good, no refund. Ok(()) @@ -572,9 +572,9 @@ pub mod pallet { pub enum Event { // Just a normal `enum`, here's a dummy event to ensure it compiles. /// Dummy event, just here so there's a generic type that's used. - AccumulateDummy(BalanceOf), - SetDummy(BalanceOf), - SetBar(T::AccountId, BalanceOf), + AccumulateDummy{balance: BalanceOf}, + SetDummy{balance: BalanceOf}, + SetBar{account: T::AccountId, balance: BalanceOf}, } // pallet::storage attributes allow for type-safe usage of the Substrate storage database, diff --git a/frame/gilt/src/lib.rs b/frame/gilt/src/lib.rs index 393b3acb41a36..bf932a06b996d 100644 --- a/frame/gilt/src/lib.rs +++ b/frame/gilt/src/lib.rs @@ -273,17 +273,13 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A bid was successfully placed. - /// \[ who, amount, duration \] - BidPlaced(T::AccountId, BalanceOf, u32), + BidPlaced{who: T::AccountId, amount: BalanceOf, duration: u32}, /// A bid was successfully removed (before being accepted as a gilt). - /// \[ who, amount, duration \] - BidRetracted(T::AccountId, BalanceOf, u32), + BidRetracted{who: T::AccountId, amount: BalanceOf, duration: u32}, /// A bid was accepted as a gilt. The balance may not be released until expiry. - /// \[ index, expiry, who, amount \] - GiltIssued(ActiveIndex, T::BlockNumber, T::AccountId, BalanceOf), + GiltIssued{index: ActiveIndex, expiry: T::BlockNumber, who: T::AccountId, amount: BalanceOf}, /// An expired gilt has been thawed. - /// \[ index, who, original_amount, additional_amount \] - GiltThawed(ActiveIndex, T::AccountId, BalanceOf, BalanceOf), + GiltThawed{index: ActiveIndex, who: T::AccountId, original_amount: BalanceOf, additional_amount: BalanceOf}, } #[pallet::error] @@ -377,7 +373,7 @@ pub mod pallet { qs[queue_index].0 += net.0; qs[queue_index].1 = qs[queue_index].1.saturating_add(net.1); }); - Self::deposit_event(Event::BidPlaced(who.clone(), amount, duration)); + Self::deposit_event(Event::BidPlaced{who: who.clone(), amount, duration}); Ok(().into()) } @@ -415,7 +411,7 @@ pub mod pallet { }); T::Currency::unreserve(&bid.who, bid.amount); - Self::deposit_event(Event::BidRetracted(bid.who, bid.amount, duration)); + Self::deposit_event(Event::BidRetracted{who: bid.who, amount: bid.amount, duration}); Ok(().into()) } @@ -494,7 +490,7 @@ pub mod pallet { debug_assert!(err_amt.is_zero()); } - let e = Event::GiltThawed(index, gilt.who, gilt.amount, gilt_value); + let e = Event::GiltThawed{index, who: gilt.who, original_amount: gilt.amount, additional_amount: gilt_value}; Self::deposit_event(e); }); @@ -604,7 +600,7 @@ pub mod pallet { totals.frozen += bid.amount; totals.proportion = totals.proportion.saturating_add(proportion); totals.index += 1; - let e = Event::GiltIssued(index, expiry, who.clone(), amount); + let e = Event::GiltIssued{index, expiry, who: who.clone(), amount}; Self::deposit_event(e); let gilt = ActiveGilt { amount, proportion, who, expiry }; Active::::insert(index, gilt); diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 9f6967a7d3c85..89e66f125f98b 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -154,9 +154,9 @@ pub mod pallet { // enact the change if we've reached the enacting block if block_number == pending_change.scheduled_at + pending_change.delay { Self::set_grandpa_authorities(&pending_change.next_authorities); - Self::deposit_event(Event::NewAuthorities( - pending_change.next_authorities.to_vec(), - )); + Self::deposit_event(Event::NewAuthorities{ + authority_set: pending_change.next_authorities.to_vec(), + }); >::kill(); } } @@ -255,8 +255,8 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event { - /// New authority set has been applied. \[authority_set\] - NewAuthorities(AuthorityList), + /// New authority set has been applied. + NewAuthorities{authority_set: AuthorityList}, /// Current authority set has been paused. Paused, /// Current authority set has been resumed. diff --git a/frame/grandpa/src/tests.rs b/frame/grandpa/src/tests.rs index 98f54f966fadc..591faf7fe393a 100644 --- a/frame/grandpa/src/tests.rs +++ b/frame/grandpa/src/tests.rs @@ -57,7 +57,7 @@ fn authorities_change_logged() { System::events(), vec![EventRecord { phase: Phase::Finalization, - event: Event::NewAuthorities(to_authorities(vec![(4, 1), (5, 1), (6, 1)])).into(), + event: Event::NewAuthorities{authority_set: to_authorities(vec![(4, 1), (5, 1), (6, 1)])}.into(), topics: vec![], },] ); @@ -93,7 +93,7 @@ fn authorities_change_logged_after_delay() { System::events(), vec![EventRecord { phase: Phase::Finalization, - event: Event::NewAuthorities(to_authorities(vec![(4, 1), (5, 1), (6, 1)])).into(), + event: Event::NewAuthorities{authority_set: to_authorities(vec![(4, 1), (5, 1), (6, 1)])}.into(), topics: vec![], },] ); diff --git a/frame/identity/src/benchmarking.rs b/frame/identity/src/benchmarking.rs index 68869a43992f9..df7aba72fd958 100644 --- a/frame/identity/src/benchmarking.rs +++ b/frame/identity/src/benchmarking.rs @@ -153,7 +153,7 @@ benchmarks! { }; }: _(RawOrigin::Signed(caller.clone()), Box::new(create_identity_info::(x))) verify { - assert_last_event::(Event::::IdentitySet(caller).into()); + assert_last_event::(Event::::IdentitySet{who: caller}.into()); } // We need to split `set_subs` into two benchmarks to accurately isolate the potential @@ -237,7 +237,7 @@ benchmarks! { }; }: _(RawOrigin::Signed(caller.clone()), r - 1, 10u32.into()) verify { - assert_last_event::(Event::::JudgementRequested(caller, r-1).into()); + assert_last_event::(Event::::JudgementRequested{who: caller, registrar_index: r-1}.into()); } cancel_request { @@ -257,7 +257,7 @@ benchmarks! { Identity::::request_judgement(caller_origin, r - 1, 10u32.into())?; }: _(RawOrigin::Signed(caller.clone()), r - 1) verify { - assert_last_event::(Event::::JudgementUnrequested(caller, r-1).into()); + assert_last_event::(Event::::JudgementUnrequested{who: caller, registrar_index: r-1}.into()); } set_fee { @@ -328,7 +328,7 @@ benchmarks! { Identity::::request_judgement(user_origin.clone(), r, 10u32.into())?; }: _(RawOrigin::Signed(caller), r, user_lookup, Judgement::Reasonable) verify { - assert_last_event::(Event::::JudgementGiven(user, r).into()) + assert_last_event::(Event::::JudgementGiven{target: user, registrar_index: r}.into()) } kill_identity { diff --git a/frame/identity/src/lib.rs b/frame/identity/src/lib.rs index a91381f1edd8b..82edf4ebd7147 100644 --- a/frame/identity/src/lib.rs +++ b/frame/identity/src/lib.rs @@ -241,28 +241,27 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// A name was set or reset (which will remove all judgements). \[who\] - IdentitySet(T::AccountId), - /// A name was cleared, and the given balance returned. \[who, deposit\] - IdentityCleared(T::AccountId, BalanceOf), - /// A name was removed and the given balance slashed. \[who, deposit\] - IdentityKilled(T::AccountId, BalanceOf), - /// A judgement was asked from a registrar. \[who, registrar_index\] - JudgementRequested(T::AccountId, RegistrarIndex), - /// A judgement request was retracted. \[who, registrar_index\] - JudgementUnrequested(T::AccountId, RegistrarIndex), - /// A judgement was given by a registrar. \[target, registrar_index\] - JudgementGiven(T::AccountId, RegistrarIndex), - /// A registrar was added. \[registrar_index\] - RegistrarAdded(RegistrarIndex), - /// A sub-identity was added to an identity and the deposit paid. \[sub, main, deposit\] - SubIdentityAdded(T::AccountId, T::AccountId, BalanceOf), + /// A name was set or reset (which will remove all judgements). + IdentitySet{who: T::AccountId}, + /// A name was cleared, and the given balance returned. + IdentityCleared{who: T::AccountId, deposit: BalanceOf}, + /// A name was removed and the given balance slashed. + IdentityKilled{who: T::AccountId, deposit: BalanceOf}, + /// A judgement was asked from a registrar. + JudgementRequested{who: T::AccountId, registrar_index: RegistrarIndex}, + /// A judgement request was retracted. + JudgementUnrequested{who: T::AccountId, registrar_index: RegistrarIndex}, + /// A judgement was given by a registrar. + JudgementGiven{target: T::AccountId, registrar_index: RegistrarIndex}, + /// A registrar was added. + RegistrarAdded{registrar_index: RegistrarIndex}, + /// A sub-identity was added to an identity and the deposit paid. + SubIdentityAdded{sub: T::AccountId, main: T::AccountId, deposit: BalanceOf}, /// A sub-identity was removed from an identity and the deposit freed. - /// \[sub, main, deposit\] - SubIdentityRemoved(T::AccountId, T::AccountId, BalanceOf), + SubIdentityRemoved{sub: T::AccountId, main: T::AccountId, deposit: BalanceOf}, /// A sub-identity was cleared, and the given deposit repatriated from the - /// main identity account to the sub-identity account. \[sub, main, deposit\] - SubIdentityRevoked(T::AccountId, T::AccountId, BalanceOf), + /// main identity account to the sub-identity account. + SubIdentityRevoked{sub: T::AccountId, main: T::AccountId, deposit: BalanceOf}, } #[pallet::call] @@ -301,7 +300,7 @@ pub mod pallet { }, )?; - Self::deposit_event(Event::RegistrarAdded(i)); + Self::deposit_event(Event::RegistrarAdded{registrar_index: i}); Ok(Some(T::WeightInfo::add_registrar(registrar_count as u32)).into()) } @@ -364,7 +363,7 @@ pub mod pallet { let judgements = id.judgements.len(); >::insert(&sender, id); - Self::deposit_event(Event::IdentitySet(sender)); + Self::deposit_event(Event::IdentitySet{who: sender}); Ok(Some(T::WeightInfo::set_identity( judgements as u32, // R @@ -489,7 +488,7 @@ pub mod pallet { let err_amount = T::Currency::unreserve(&sender, deposit.clone()); debug_assert!(err_amount.is_zero()); - Self::deposit_event(Event::IdentityCleared(sender, deposit)); + Self::deposit_event(Event::IdentityCleared{who: sender, deposit}); Ok(Some(T::WeightInfo::clear_identity( id.judgements.len() as u32, // R @@ -558,7 +557,7 @@ pub mod pallet { let extra_fields = id.info.additional.len(); >::insert(&sender, id); - Self::deposit_event(Event::JudgementRequested(sender, reg_index)); + Self::deposit_event(Event::JudgementRequested{who: sender, registrar_index: reg_index}); Ok(Some(T::WeightInfo::request_judgement(judgements as u32, extra_fields as u32)) .into()) @@ -608,7 +607,7 @@ pub mod pallet { let extra_fields = id.info.additional.len(); >::insert(&sender, id); - Self::deposit_event(Event::JudgementUnrequested(sender, reg_index)); + Self::deposit_event(Event::JudgementUnrequested{who: sender, registrar_index: reg_index}); Ok(Some(T::WeightInfo::cancel_request(judgements as u32, extra_fields as u32)).into()) } @@ -791,7 +790,7 @@ pub mod pallet { let judgements = id.judgements.len(); let extra_fields = id.info.additional.len(); >::insert(&target, id); - Self::deposit_event(Event::JudgementGiven(target, reg_index)); + Self::deposit_event(Event::JudgementGiven{target, registrar_index: reg_index}); Ok(Some(T::WeightInfo::provide_judgement(judgements as u32, extra_fields as u32)) .into()) @@ -839,7 +838,7 @@ pub mod pallet { // Slash their deposit from them. T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0); - Self::deposit_event(Event::IdentityKilled(target, deposit)); + Self::deposit_event(Event::IdentityKilled{who: target, deposit}); Ok(Some(T::WeightInfo::kill_identity( id.judgements.len() as u32, // R @@ -882,7 +881,7 @@ pub mod pallet { sub_ids.try_push(sub.clone()).expect("sub ids length checked above; qed"); *subs_deposit = subs_deposit.saturating_add(deposit); - Self::deposit_event(Event::SubIdentityAdded(sub, sender.clone(), deposit)); + Self::deposit_event(Event::SubIdentityAdded{sub, main: sender.clone(), deposit}); Ok(()) }) } @@ -929,7 +928,7 @@ pub mod pallet { *subs_deposit -= deposit; let err_amount = T::Currency::unreserve(&sender, deposit); debug_assert!(err_amount.is_zero()); - Self::deposit_event(Event::SubIdentityRemoved(sub, sender, deposit)); + Self::deposit_event(Event::SubIdentityRemoved{sub: sub, main: sender, deposit}); }); Ok(()) } @@ -954,7 +953,7 @@ pub mod pallet { *subs_deposit -= deposit; let _ = T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free); - Self::deposit_event(Event::SubIdentityRevoked(sender, sup.clone(), deposit)); + Self::deposit_event(Event::SubIdentityRevoked{sub: sender, main: sup.clone(), deposit}); }); Ok(()) } diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index d76bbaaa2fd14..51babc9150a10 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -375,12 +375,12 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// A new heartbeat was received from `AuthorityId` \[authority_id\] - HeartbeatReceived(T::AuthorityId), + /// A new heartbeat was received from `AuthorityId`. + HeartbeatReceived{authority_id: T::AuthorityId}, /// At the end of the session, no offence was committed. AllGood, - /// At the end of the session, at least one validator was found to be \[offline\]. - SomeOffline(Vec>), + /// At the end of the session, at least one validator was found to be offline. + SomeOffline{offline: Vec>}, } #[pallet::error] @@ -496,7 +496,7 @@ pub mod pallet { let keys = Keys::::get(); let public = keys.get(heartbeat.authority_index as usize); if let (false, Some(public)) = (exists, public) { - Self::deposit_event(Event::::HeartbeatReceived(public.clone())); + Self::deposit_event(Event::::HeartbeatReceived{authority_id: public.clone()}); let network_state_bounded = BoundedOpaqueNetworkState::< T::MaxPeerDataEncodingSize, @@ -909,7 +909,7 @@ impl OneSessionHandler for Pallet { if offenders.is_empty() { Self::deposit_event(Event::::AllGood); } else { - Self::deposit_event(Event::::SomeOffline(offenders.clone())); + Self::deposit_event(Event::::SomeOffline{offline: offenders.clone()}); let validator_set_count = keys.len() as u32; let offence = UnresponsivenessOffence { session_index, validator_set_count, offenders }; diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index 0901a89d41ad6..8b71a4ac13c6f 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -105,7 +105,7 @@ pub mod pallet { *maybe_value = Some((who.clone(), T::Deposit::get(), false)); T::Currency::reserve(&who, T::Deposit::get()) })?; - Self::deposit_event(Event::IndexAssigned(who, index)); + Self::deposit_event(Event::IndexAssigned{who, index}); Ok(()) } @@ -146,7 +146,7 @@ pub mod pallet { *maybe_value = Some((new.clone(), amount.saturating_sub(lost), false)); Ok(()) })?; - Self::deposit_event(Event::IndexAssigned(new, index)); + Self::deposit_event(Event::IndexAssigned{who: new, index}); Ok(()) } @@ -179,7 +179,7 @@ pub mod pallet { T::Currency::unreserve(&who, amount); Ok(()) })?; - Self::deposit_event(Event::IndexFreed(index)); + Self::deposit_event(Event::IndexFreed{index}); Ok(()) } @@ -219,7 +219,7 @@ pub mod pallet { } *maybe_value = Some((new.clone(), Zero::zero(), freeze)); }); - Self::deposit_event(Event::IndexAssigned(new, index)); + Self::deposit_event(Event::IndexAssigned{who: new, index}); Ok(()) } @@ -253,7 +253,7 @@ pub mod pallet { *maybe_value = Some((account, Zero::zero(), true)); Ok(()) })?; - Self::deposit_event(Event::IndexFrozen(index, who)); + Self::deposit_event(Event::IndexFrozen{index, who}); Ok(()) } } @@ -261,12 +261,12 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// A account index was assigned. \[index, who\] - IndexAssigned(T::AccountId, T::AccountIndex), - /// A account index has been freed up (unassigned). \[index\] - IndexFreed(T::AccountIndex), - /// A account index has been frozen to its current account ID. \[index, who\] - IndexFrozen(T::AccountIndex, T::AccountId), + /// A account index was assigned. + IndexAssigned{who: T::AccountId, index: T::AccountIndex}, + /// A account index has been freed up (unassigned). + IndexFreed{index: T::AccountIndex}, + /// A account index has been frozen to its current account ID. + IndexFrozen{index: T::AccountIndex, who: T::AccountId}, } /// Old name generated by `decl_event`. diff --git a/frame/lottery/src/lib.rs b/frame/lottery/src/lib.rs index 260b4c2d76ae9..dbf7bf96868e4 100644 --- a/frame/lottery/src/lib.rs +++ b/frame/lottery/src/lib.rs @@ -176,9 +176,9 @@ pub mod pallet { /// A new set of calls have been set! CallsUpdated, /// A winner has been chosen! - Winner(T::AccountId, BalanceOf), + Winner{winner: T::AccountId, lottery_balance: BalanceOf}, /// A ticket has been bought! - TicketBought(T::AccountId, CallIndex), + TicketBought{who: T::AccountId, call_index: CallIndex}, } #[pallet::error] @@ -250,7 +250,7 @@ pub mod pallet { ); debug_assert!(res.is_ok()); - Self::deposit_event(Event::::Winner(winner, lottery_balance)); + Self::deposit_event(Event::::Winner{winner, lottery_balance}); TicketsCount::::kill(); @@ -452,7 +452,7 @@ impl Pallet { }, )?; - Self::deposit_event(Event::::TicketBought(caller.clone(), call_index)); + Self::deposit_event(Event::::TicketBought{who: caller.clone(), call_index}); Ok(()) } diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 8fa2abb0ad3f3..021633e185e03 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -143,7 +143,7 @@ pub mod pallet { /// One of the members' keys changed. KeyChanged, /// Phantom member, never used. - Dummy(PhantomData<(T::AccountId, >::Event)>), + Dummy{_phantom_data: PhantomData<(T::AccountId, >::Event)>}, } /// Old name generated by `decl_event`. diff --git a/frame/multisig/src/lib.rs b/frame/multisig/src/lib.rs index 53567cc212afd..62b58f8ddf428 100644 --- a/frame/multisig/src/lib.rs +++ b/frame/multisig/src/lib.rs @@ -206,20 +206,20 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A new multisig operation has begun. \[approving, multisig, call_hash\] - NewMultisig(T::AccountId, T::AccountId, CallHash), + NewMultisig{approving: T::AccountId, multisig: T::AccountId, call_hash: CallHash}, /// A multisig operation has been approved by someone. /// \[approving, timepoint, multisig, call_hash\] - MultisigApproval(T::AccountId, Timepoint, T::AccountId, CallHash), + MultisigApproval{approving: T::AccountId, timepoint: Timepoint, multisig: T::AccountId, call_hash: CallHash}, /// A multisig operation has been executed. \[approving, timepoint, multisig, call_hash\] - MultisigExecuted( - T::AccountId, - Timepoint, - T::AccountId, - CallHash, - DispatchResult, - ), + MultisigExecuted{ + approving: T::AccountId, + timepoint: Timepoint, + multisig: T::AccountId, + call_hash: CallHash, + result: DispatchResult, + }, /// A multisig operation has been cancelled. \[cancelling, timepoint, multisig, call_hash\] - MultisigCancelled(T::AccountId, Timepoint, T::AccountId, CallHash), + MultisigCancelled{cancelling: T::AccountId, timepoint: Timepoint, multisig: T::AccountId, call_hash: CallHash}, } #[pallet::hooks] @@ -481,7 +481,7 @@ pub mod pallet { >::remove(&id, &call_hash); Self::clear_call(&call_hash); - Self::deposit_event(Event::MultisigCancelled(who, timepoint, id, call_hash)); + Self::deposit_event(Event::MultisigCancelled{cancelling: who, timepoint, multisig: id, call_hash: call_hash}); Ok(()) } } @@ -557,13 +557,13 @@ impl Pallet { T::Currency::unreserve(&m.depositor, m.deposit); let result = call.dispatch(RawOrigin::Signed(id.clone()).into()); - Self::deposit_event(Event::MultisigExecuted( - who, + Self::deposit_event(Event::MultisigExecuted{ + approving: who, timepoint, - id, + multisig: id, call_hash, - result.map(|_| ()).map_err(|e| e.error), - )); + result: result.map(|_| ()).map_err(|e| e.error), + }); Ok(get_result_weight(result) .map(|actual_weight| { T::WeightInfo::as_multi_complete( @@ -594,7 +594,7 @@ impl Pallet { // Record approval. m.approvals.insert(pos, who.clone()); >::insert(&id, call_hash, m); - Self::deposit_event(Event::MultisigApproval(who, timepoint, id, call_hash)); + Self::deposit_event(Event::MultisigApproval{approving: who, timepoint, multisig: id, call_hash}); } else { // If we already approved and didn't store the Call, then this was useless and // we report an error. @@ -638,7 +638,7 @@ impl Pallet { approvals: vec![who.clone()], }, ); - Self::deposit_event(Event::NewMultisig(who, id, call_hash)); + Self::deposit_event(Event::NewMultisig{approving: who, multisig: id, call_hash}); let final_weight = if stored { T::WeightInfo::as_multi_create_store(other_signatories_len as u32, call_len as u32) diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index d46c22ec73d09..57a6791684d5d 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -706,7 +706,7 @@ fn multisig_2_of_3_cannot_reissue_same_call() { let err = DispatchError::from(BalancesError::::InsufficientBalance).stripped(); System::assert_last_event( - pallet_multisig::Event::MultisigExecuted(3, now(), multi, hash, Err(err)).into(), + pallet_multisig::Event::MultisigExecuted{approving: 3, timepoint: now(), multisig: multi, call_hash: hash, result: Err(err)}.into(), ); }); } diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index f502a683f633c..712d6baad7c51 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -89,16 +89,16 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// A name was set. \[who\] - NameSet(T::AccountId), - /// A name was forcibly set. \[target\] - NameForced(T::AccountId), - /// A name was changed. \[who\] - NameChanged(T::AccountId), - /// A name was cleared, and the given balance returned. \[who, deposit\] - NameCleared(T::AccountId, BalanceOf), - /// A name was removed and the given balance slashed. \[target, deposit\] - NameKilled(T::AccountId, BalanceOf), + /// A name was set. + NameSet{who: T::AccountId}, + /// A name was forcibly set. + NameForced{target: T::AccountId}, + /// A name was changed. + NameChanged{who: T::AccountId}, + /// A name was cleared, and the given balance returned. + NameCleared{who: T::AccountId, deposit: BalanceOf}, + /// A name was removed and the given balance slashed. + NameKilled{target: T::AccountId, deposit: BalanceOf}, } /// Error for the nicks pallet. @@ -147,12 +147,12 @@ pub mod pallet { ensure!(name.len() <= T::MaxLength::get() as usize, Error::::TooLong); let deposit = if let Some((_, deposit)) = >::get(&sender) { - Self::deposit_event(Event::::NameChanged(sender.clone())); + Self::deposit_event(Event::::NameChanged{who: sender.clone()}); deposit } else { let deposit = T::ReservationFee::get(); T::Currency::reserve(&sender, deposit.clone())?; - Self::deposit_event(Event::::NameSet(sender.clone())); + Self::deposit_event(Event::::NameSet{who: sender.clone()}); deposit }; @@ -179,7 +179,7 @@ pub mod pallet { let err_amount = T::Currency::unreserve(&sender, deposit.clone()); debug_assert!(err_amount.is_zero()); - Self::deposit_event(Event::::NameCleared(sender, deposit)); + Self::deposit_event(Event::::NameCleared{who: sender, deposit}); Ok(()) } @@ -210,7 +210,7 @@ pub mod pallet { // Slash their deposit from them. T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit.clone()).0); - Self::deposit_event(Event::::NameKilled(target, deposit)); + Self::deposit_event(Event::::NameKilled{target, deposit}); Ok(()) } @@ -238,7 +238,7 @@ pub mod pallet { let deposit = >::get(&target).map(|x| x.1).unwrap_or_else(Zero::zero); >::insert(&target, (name, deposit)); - Self::deposit_event(Event::::NameForced(target)); + Self::deposit_event(Event::::NameForced{target}); Ok(()) } } diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 016f12d2eb838..ab8e9844e93e3 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -128,24 +128,24 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// The given well known node was added. - NodeAdded(PeerId, T::AccountId), + NodeAdded{peer_id: PeerId, who: T::AccountId}, /// The given well known node was removed. - NodeRemoved(PeerId), + NodeRemoved{peer_id: PeerId}, /// The given well known node was swapped; first item was removed, /// the latter was added. - NodeSwapped(PeerId, PeerId), + NodeSwapped{removed: PeerId, added: PeerId}, /// The given well known nodes were reset. - NodesReset(Vec<(PeerId, T::AccountId)>), + NodesReset{nodes: Vec<(PeerId, T::AccountId)>}, /// The given node was claimed by a user. - NodeClaimed(PeerId, T::AccountId), + NodeClaimed{peer_id: PeerId, who: T::AccountId}, /// The given claim was removed by its owner. - ClaimRemoved(PeerId, T::AccountId), + ClaimRemoved{peer_id: PeerId, who: T::AccountId}, /// The node was transferred to another account. - NodeTransferred(PeerId, T::AccountId), + NodeTransferred{peer_id: PeerId, target: T::AccountId}, /// The allowed connections were added to a node. - ConnectionsAdded(PeerId, Vec), + ConnectionsAdded{peer_id: PeerId, allowed_connections: Vec}, /// The allowed connections were removed from a node. - ConnectionsRemoved(PeerId, Vec), + ConnectionsRemoved{peer_id: PeerId, allowed_connections: Vec}, } #[pallet::error] @@ -224,7 +224,7 @@ pub mod pallet { WellKnownNodes::::put(&nodes); >::insert(&node, &owner); - Self::deposit_event(Event::NodeAdded(node, owner)); + Self::deposit_event(Event::NodeAdded{peer_id: node, who: owner}); Ok(()) } @@ -248,7 +248,7 @@ pub mod pallet { >::remove(&node); AdditionalConnections::::remove(&node); - Self::deposit_event(Event::NodeRemoved(node)); + Self::deposit_event(Event::NodeRemoved{peer_id: node}); Ok(()) } @@ -284,7 +284,7 @@ pub mod pallet { Owners::::swap(&remove, &add); AdditionalConnections::::swap(&remove, &add); - Self::deposit_event(Event::NodeSwapped(remove, add)); + Self::deposit_event(Event::NodeSwapped{removed: remove, added: add}); Ok(()) } @@ -305,7 +305,7 @@ pub mod pallet { Self::initialize_nodes(&nodes); - Self::deposit_event(Event::NodesReset(nodes)); + Self::deposit_event(Event::NodesReset{nodes}); Ok(()) } @@ -321,7 +321,7 @@ pub mod pallet { ensure!(!Owners::::contains_key(&node), Error::::AlreadyClaimed); Owners::::insert(&node, &sender); - Self::deposit_event(Event::NodeClaimed(node, sender)); + Self::deposit_event(Event::NodeClaimed{peer_id: node, who: sender}); Ok(()) } @@ -342,7 +342,7 @@ pub mod pallet { Owners::::remove(&node); AdditionalConnections::::remove(&node); - Self::deposit_event(Event::ClaimRemoved(node, sender)); + Self::deposit_event(Event::ClaimRemoved{peer_id: node, who: sender}); Ok(()) } @@ -364,7 +364,7 @@ pub mod pallet { Owners::::insert(&node, &owner); - Self::deposit_event(Event::NodeTransferred(node, owner)); + Self::deposit_event(Event::NodeTransferred{peer_id: node, target: owner}); Ok(()) } @@ -395,7 +395,7 @@ pub mod pallet { AdditionalConnections::::insert(&node, nodes); - Self::deposit_event(Event::ConnectionsAdded(node, connections)); + Self::deposit_event(Event::ConnectionsAdded{peer_id: node, allowed_connections: connections}); Ok(()) } @@ -423,7 +423,7 @@ pub mod pallet { AdditionalConnections::::insert(&node, nodes); - Self::deposit_event(Event::ConnectionsRemoved(node, connections)); + Self::deposit_event(Event::ConnectionsRemoved{peer_id: node, allowed_connections: connections}); Ok(()) } } From 5572b6d72a22692c6501a6a33c2979d6ef33cb53 Mon Sep 17 00:00:00 2001 From: david Date: Mon, 11 Oct 2021 07:20:04 +0100 Subject: [PATCH 04/11] update pallet event field names --- frame/atomic-swap/src/lib.rs | 16 +- frame/aura/src/lib.rs | 4 +- frame/authorship/src/lib.rs | 33 +- frame/babe/src/equivocation.rs | 6 +- frame/babe/src/lib.rs | 10 +- frame/babe/src/tests.rs | 6 +- frame/bags-list/src/lib.rs | 4 +- frame/bags-list/src/list/mod.rs | 16 +- frame/balances/src/lib.rs | 135 +++---- frame/balances/src/tests_local.rs | 6 +- frame/balances/src/tests_reentrancy.rs | 29 +- frame/beefy-mmr/primitives/src/lib.rs | 12 +- frame/beefy-mmr/src/lib.rs | 2 +- frame/beefy/src/lib.rs | 2 +- frame/benchmarking/src/analysis.rs | 12 +- frame/benchmarking/src/lib.rs | 2 +- frame/benchmarking/src/tests.rs | 2 +- frame/benchmarking/src/utils.rs | 4 +- frame/bounties/src/lib.rs | 91 ++--- frame/bounties/src/migrations/v4.rs | 2 +- frame/bounties/src/tests.rs | 16 +- frame/collective/src/lib.rs | 66 ++-- frame/collective/src/migrations/v4.rs | 6 +- frame/collective/src/tests.rs | 349 +++++++++++++++--- frame/contracts/proc-macro/src/lib.rs | 6 +- frame/contracts/src/benchmarking/code.rs | 16 +- frame/contracts/src/exec.rs | 28 +- frame/contracts/src/lib.rs | 7 +- frame/contracts/src/schedule.rs | 38 +- frame/contracts/src/storage.rs | 16 +- frame/contracts/src/tests.rs | 8 +- frame/contracts/src/wasm/code_cache.rs | 7 +- frame/contracts/src/wasm/prepare.rs | 89 ++--- frame/contracts/src/wasm/runtime.rs | 28 +- frame/democracy/src/lib.rs | 125 ++++--- frame/democracy/src/types.rs | 8 +- frame/democracy/src/vote.rs | 10 +- frame/democracy/src/vote_threshold.rs | 20 +- .../election-provider-multi-phase/src/lib.rs | 82 ++-- .../election-provider-multi-phase/src/mock.rs | 2 +- .../src/signed.rs | 16 +- .../src/unsigned.rs | 47 +-- frame/elections-phragmen/src/lib.rs | 81 ++-- frame/elections-phragmen/src/migrations/v4.rs | 2 +- frame/elections/src/lib.rs | 55 ++- frame/elections/src/tests.rs | 2 +- frame/example-offchain-worker/src/lib.rs | 43 ++- frame/example-parallel/src/lib.rs | 6 +- frame/example/src/lib.rs | 21 +- frame/executive/src/lib.rs | 29 +- frame/gilt/src/lib.rs | 38 +- frame/grandpa/src/equivocation.rs | 6 +- frame/grandpa/src/lib.rs | 18 +- frame/grandpa/src/migrations/v4.rs | 2 +- frame/grandpa/src/tests.rs | 14 +- frame/identity/src/benchmarking.rs | 20 +- frame/identity/src/lib.rs | 64 ++-- frame/identity/src/types.rs | 9 +- frame/im-online/src/lib.rs | 41 +- frame/im-online/src/tests.rs | 5 +- frame/indices/src/lib.rs | 16 +- frame/lottery/src/lib.rs | 18 +- frame/membership/src/lib.rs | 4 +- frame/membership/src/migrations/v4.rs | 6 +- frame/merkle-mountain-range/src/lib.rs | 8 +- .../merkle-mountain-range/src/mmr/storage.rs | 2 +- frame/merkle-mountain-range/src/mmr/utils.rs | 2 +- frame/multisig/src/lib.rs | 40 +- frame/multisig/src/tests.rs | 9 +- frame/nicks/src/lib.rs | 20 +- frame/node-authorization/src/lib.rs | 48 +-- frame/offences/src/lib.rs | 4 +- frame/offences/src/tests.rs | 10 +- frame/proxy/src/benchmarking.rs | 18 +- frame/proxy/src/lib.rs | 66 ++-- frame/proxy/src/tests.rs | 80 ++-- frame/scheduler/src/lib.rs | 24 +- frame/scored-pool/src/lib.rs | 10 +- frame/session/src/historical/mod.rs | 8 +- frame/session/src/historical/offchain.rs | 6 +- frame/session/src/lib.rs | 10 +- frame/session/src/mock.rs | 4 +- frame/society/src/lib.rs | 44 +-- frame/staking/reward-curve/src/lib.rs | 32 +- frame/staking/reward-curve/src/log.rs | 4 +- frame/staking/reward-fn/src/lib.rs | 18 +- frame/staking/src/benchmarking.rs | 2 +- frame/staking/src/inflation.rs | 4 +- frame/staking/src/lib.rs | 2 +- frame/staking/src/mock.rs | 6 +- frame/staking/src/pallet/impls.rs | 27 +- frame/staking/src/pallet/mod.rs | 33 +- frame/staking/src/slashing.rs | 16 +- frame/staking/src/testing_utils.rs | 4 +- frame/staking/src/tests.rs | 32 +- frame/sudo/src/lib.rs | 2 +- .../support/procedural/src/clone_no_bound.rs | 16 +- .../src/construct_runtime/expand/event.rs | 10 +- .../src/construct_runtime/expand/origin.rs | 10 +- .../procedural/src/construct_runtime/mod.rs | 4 +- .../procedural/src/construct_runtime/parse.rs | 24 +- frame/support/procedural/src/crate_version.rs | 2 +- .../support/procedural/src/debug_no_bound.rs | 14 +- .../procedural/src/default_no_bound.rs | 19 +- .../procedural/src/dummy_part_checker.rs | 2 +- frame/support/procedural/src/key_prefix.rs | 2 +- .../procedural/src/pallet/expand/call.rs | 2 +- .../procedural/src/pallet/expand/event.rs | 2 +- .../src/pallet/expand/genesis_build.rs | 2 +- .../src/pallet/expand/genesis_config.rs | 10 +- .../procedural/src/pallet/expand/hooks.rs | 2 +- .../procedural/src/pallet/expand/storage.rs | 28 +- frame/support/procedural/src/pallet/mod.rs | 2 +- .../procedural/src/pallet/parse/call.rs | 26 +- .../procedural/src/pallet/parse/config.rs | 34 +- .../procedural/src/pallet/parse/error.rs | 10 +- .../procedural/src/pallet/parse/event.rs | 6 +- .../src/pallet/parse/extra_constants.rs | 18 +- .../src/pallet/parse/genesis_build.rs | 2 +- .../src/pallet/parse/genesis_config.rs | 8 +- .../procedural/src/pallet/parse/helper.rs | 18 +- .../procedural/src/pallet/parse/hooks.rs | 4 +- .../procedural/src/pallet/parse/inherent.rs | 8 +- .../procedural/src/pallet/parse/mod.rs | 69 ++-- .../procedural/src/pallet/parse/origin.rs | 8 +- .../src/pallet/parse/pallet_struct.rs | 12 +- .../procedural/src/pallet/parse/storage.rs | 84 +++-- .../procedural/src/pallet/parse/type_value.rs | 12 +- .../src/pallet/parse/validate_unsigned.rs | 8 +- .../procedural/src/partial_eq_no_bound.rs | 16 +- .../src/storage/genesis_config/builder_def.rs | 14 +- .../genesis_config/genesis_config_def.rs | 8 +- .../support/procedural/src/storage/getters.rs | 8 +- .../procedural/src/storage/metadata.rs | 8 +- frame/support/procedural/src/storage/mod.rs | 40 +- frame/support/procedural/src/storage/parse.rs | 32 +- .../src/storage/print_pallet_upgrade.rs | 14 +- .../procedural/src/storage/storage_struct.rs | 24 +- frame/support/procedural/tools/src/lib.rs | 6 +- frame/support/procedural/tools/src/syn_ext.rs | 4 +- frame/support/src/dispatch.rs | 8 +- frame/support/src/hash.rs | 4 +- frame/support/src/lib.rs | 2 +- .../support/src/storage/bounded_btree_map.rs | 2 +- .../support/src/storage/bounded_btree_set.rs | 2 +- frame/support/src/storage/bounded_vec.rs | 2 +- frame/support/src/storage/child.rs | 21 +- .../src/storage/generator/double_map.rs | 12 +- frame/support/src/storage/generator/map.rs | 14 +- frame/support/src/storage/generator/nmap.rs | 8 +- frame/support/src/storage/migration.rs | 16 +- frame/support/src/storage/mod.rs | 38 +- frame/support/src/traits/members.rs | 8 +- frame/support/src/traits/stored_map.rs | 2 +- frame/support/src/traits/tokens/fungible.rs | 2 +- .../src/traits/tokens/fungible/balanced.rs | 2 +- frame/support/src/traits/tokens/fungibles.rs | 2 +- .../src/traits/tokens/fungibles/balanced.rs | 4 +- frame/support/src/traits/tokens/imbalance.rs | 2 +- .../tokens/imbalance/signed_imbalance.rs | 12 +- frame/support/src/weights.rs | 8 +- frame/support/test/tests/pallet.rs | 2 +- .../test/tests/pallet_compatibility.rs | 5 +- .../tests/pallet_compatibility_instance.rs | 5 +- frame/support/test/tests/pallet_instance.rs | 8 +- frame/system/src/extensions/check_nonce.rs | 4 +- frame/system/src/extensions/check_weight.rs | 9 +- frame/system/src/lib.rs | 20 +- frame/system/src/offchain.rs | 4 +- frame/tips/src/benchmarking.rs | 6 +- frame/tips/src/lib.rs | 10 +- frame/tips/src/migrations/v4.rs | 6 +- frame/transaction-payment/src/lib.rs | 16 +- frame/transaction-payment/src/payment.rs | 2 +- frame/transaction-storage/src/lib.rs | 6 +- frame/uniques/src/lib.rs | 16 +- frame/utility/src/lib.rs | 2 +- frame/vesting/src/lib.rs | 18 +- frame/vesting/src/tests.rs | 8 +- frame/vesting/src/vesting_info.rs | 4 +- 180 files changed, 1989 insertions(+), 1464 deletions(-) diff --git a/frame/atomic-swap/src/lib.rs b/frame/atomic-swap/src/lib.rs index 1cd3774433373..4775cd06b1afd 100644 --- a/frame/atomic-swap/src/lib.rs +++ b/frame/atomic-swap/src/lib.rs @@ -219,11 +219,11 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Swap created. - NewSwap{account: T::AccountId, proof: HashedProof, swap: PendingSwap}, + NewSwap { account: T::AccountId, proof: HashedProof, swap: PendingSwap }, /// Swap claimed. The last parameter indicates whether the execution succeeds. - SwapClaimed{account: T::AccountId, proof: HashedProof, success: bool}, + SwapClaimed { account: T::AccountId, proof: HashedProof, success: bool }, /// Swap cancelled. - SwapCancelled{account: T::AccountId, proof: HashedProof}, + SwapCancelled { account: T::AccountId, proof: HashedProof }, } /// Old name generated by `decl_event`. @@ -267,7 +267,7 @@ pub mod pallet { }; PendingSwaps::::insert(target.clone(), hashed_proof.clone(), swap.clone()); - Self::deposit_event(Event::NewSwap{account: target, proof: hashed_proof, swap}); + Self::deposit_event(Event::NewSwap { account: target, proof: hashed_proof, swap }); Ok(()) } @@ -303,7 +303,11 @@ pub mod pallet { PendingSwaps::::remove(target.clone(), hashed_proof.clone()); - Self::deposit_event(Event::SwapClaimed{account: target, proof: hashed_proof, success: succeeded}); + Self::deposit_event(Event::SwapClaimed { + account: target, + proof: hashed_proof, + success: succeeded, + }); Ok(()) } @@ -332,7 +336,7 @@ pub mod pallet { swap.action.cancel(&swap.source); PendingSwaps::::remove(&target, hashed_proof.clone()); - Self::deposit_event(Event::SwapCancelled{account: target, proof: hashed_proof}); + Self::deposit_event(Event::SwapCancelled { account: target, proof: hashed_proof }); Ok(()) } diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index 4b5294835403a..b0b61928c4761 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -173,7 +173,7 @@ impl Pallet { let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime()); for (id, mut data) in pre_runtime_digests { if id == AURA_ENGINE_ID { - return Slot::decode(&mut data).ok() + return Slot::decode(&mut data).ok(); } } @@ -240,7 +240,7 @@ impl FindAuthor for Pallet { if id == AURA_ENGINE_ID { let slot = Slot::decode(&mut data).ok()?; let author_index = *slot % Self::authorities().len() as u64; - return Some(author_index as u32) + return Some(author_index as u32); } } diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 5d36adabe888f..76efc9eac40cd 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -107,7 +107,7 @@ where if let Some(ref author) = author { if !acc.insert((number.clone(), author.clone())) { - return Err("more than one uncle per number per author included") + return Err("more than one uncle per number per author included"); } } @@ -261,12 +261,12 @@ pub mod pallet { existing_hashes.push(hash); if new_uncles.len() == MAX_UNCLES { - break + break; } - }, + } Err(_) => { // skip this uncle - }, + } } } } @@ -283,8 +283,9 @@ pub mod pallet { _data: &InherentData, ) -> result::Result<(), Self::Error> { match call { - Call::set_uncles { ref new_uncles } if new_uncles.len() > MAX_UNCLES => - Err(InherentError::Uncles(Error::::TooManyUncles.as_str().into())), + Call::set_uncles { ref new_uncles } if new_uncles.len() > MAX_UNCLES => { + Err(InherentError::Uncles(Error::::TooManyUncles.as_str().into())) + } _ => Ok(()), } } @@ -303,7 +304,7 @@ impl Pallet { pub fn author() -> T::AccountId { // Check the memoized storage value. if let Some(author) = >::get() { - return author + return author; } let digest = >::digest(); @@ -360,30 +361,30 @@ impl Pallet { let hash = uncle.hash(); if uncle.number() < &One::one() { - return Err(Error::::GenesisUncle.into()) + return Err(Error::::GenesisUncle.into()); } if uncle.number() > &maximum_height { - return Err(Error::::TooHighUncle.into()) + return Err(Error::::TooHighUncle.into()); } { let parent_number = uncle.number().clone() - One::one(); let parent_hash = >::block_hash(&parent_number); if &parent_hash != uncle.parent_hash() { - return Err(Error::::InvalidUncleParent.into()) + return Err(Error::::InvalidUncleParent.into()); } } if uncle.number() < &minimum_height { - return Err(Error::::OldUncle.into()) + return Err(Error::::OldUncle.into()); } let duplicate = existing_uncles.into_iter().any(|h| *h == hash); let in_chain = >::block_hash(uncle.number()) == hash; if duplicate || in_chain { - return Err(Error::::UncleAlreadyIncluded.into()) + return Err(Error::::UncleAlreadyIncluded.into()); } // check uncle validity. @@ -482,7 +483,7 @@ mod tests { { for (id, data) in digests { if id == TEST_ID { - return u64::decode(&mut &data[..]).ok() + return u64::decode(&mut &data[..]).ok(); } } @@ -506,10 +507,10 @@ mod tests { Err(_) => return Err("wrong seal"), Ok(a) => { if a != author { - return Err("wrong author in seal") + return Err("wrong author in seal"); } - break - }, + break; + } } } } diff --git a/frame/babe/src/equivocation.rs b/frame/babe/src/equivocation.rs index 2397918d1ef13..65fdc90ea37d0 100644 --- a/frame/babe/src/equivocation.rs +++ b/frame/babe/src/equivocation.rs @@ -189,15 +189,15 @@ impl Pallet { if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call { // discard equivocation report not coming from the local node match source { - TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ }, + TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ } _ => { log::warn!( target: "runtime::babe", "rejecting unsigned report equivocation transaction because it is not local/in-block.", ); - return InvalidTransaction::Call.into() - }, + return InvalidTransaction::Call.into(); + } } // check report staleness diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index 9c755eea6c446..d173eeeb87aac 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -441,11 +441,11 @@ impl FindAuthor for Pallet { for (id, mut data) in digests.into_iter() { if id == BABE_ENGINE_ID { let pre_digest: PreDigest = PreDigest::decode(&mut data).ok()?; - return Some(pre_digest.authority_index()) + return Some(pre_digest.authority_index()); } } - return None + return None; } } @@ -661,7 +661,7 @@ impl Pallet { // => let's ensure that we only modify the storage once per block let initialized = Self::initialized().is_some(); if initialized { - return + return; } let maybe_pre_digest: Option = @@ -790,7 +790,7 @@ impl Pallet { // validate the equivocation proof if !sp_consensus_babe::check_equivocation_proof(equivocation_proof) { - return Err(Error::::InvalidEquivocationProof.into()) + return Err(Error::::InvalidEquivocationProof.into()); } let validator_set_count = key_owner_proof.validator_count(); @@ -802,7 +802,7 @@ impl Pallet { // check that the slot number is consistent with the session index // in the key ownership proof (i.e. slot is for that epoch) if epoch_index != session_index { - return Err(Error::::InvalidKeyOwnershipProof.into()) + return Err(Error::::InvalidKeyOwnershipProof.into()); } // check the membership proof and extract the offender's id diff --git a/frame/babe/src/tests.rs b/frame/babe/src/tests.rs index 34d861d5d97f7..acd066f444056 100644 --- a/frame/babe/src/tests.rs +++ b/frame/babe/src/tests.rs @@ -219,8 +219,8 @@ fn can_estimate_current_epoch_progress() { ); } else { assert!( - Babe::estimate_current_session_progress(i).0.unwrap() < - Permill::from_percent(100) + Babe::estimate_current_session_progress(i).0.unwrap() + < Permill::from_percent(100) ); } } @@ -462,7 +462,7 @@ fn report_equivocation_current_session_works() { // check that the balances of all other validators are left intact. for validator in &validators { if *validator == offending_validator_id { - continue + continue; } assert_eq!(Balances::total_balance(validator), 10_000_000); diff --git a/frame/bags-list/src/lib.rs b/frame/bags-list/src/lib.rs index 77a52ede7d8c1..6e7c0a2e9e1f5 100644 --- a/frame/bags-list/src/lib.rs +++ b/frame/bags-list/src/lib.rs @@ -175,7 +175,7 @@ pub mod pallet { #[pallet::generate_deposit(pub(crate) fn deposit_event)] pub enum Event { /// Moved an account from one bag to another. - Rebagged{who: T::AccountId, from: VoteWeight, to: VoteWeight}, + Rebagged { who: T::AccountId, from: VoteWeight, to: VoteWeight }, } #[pallet::call] @@ -222,7 +222,7 @@ impl Pallet { let maybe_movement = list::Node::::get(&account) .and_then(|node| List::update_position_for(node, new_weight)); if let Some((from, to)) = maybe_movement { - Self::deposit_event(Event::::Rebagged{who: account.clone(), from, to}); + Self::deposit_event(Event::::Rebagged { who: account.clone(), from, to }); }; maybe_movement } diff --git a/frame/bags-list/src/list/mod.rs b/frame/bags-list/src/list/mod.rs index 3f55f22271910..b7f7d2a9050c5 100644 --- a/frame/bags-list/src/list/mod.rs +++ b/frame/bags-list/src/list/mod.rs @@ -130,7 +130,7 @@ impl List { pub fn migrate(old_thresholds: &[VoteWeight]) -> u32 { let new_thresholds = T::BagThresholds::get(); if new_thresholds == old_thresholds { - return 0 + return 0; } // we can't check all preconditions, but we can check one @@ -163,7 +163,7 @@ impl List { if !affected_old_bags.insert(affected_bag) { // If the previous threshold list was [10, 20], and we insert [3, 5], then there's // no point iterating through bag 10 twice. - continue + continue; } if let Some(bag) = Bag::::get(affected_bag) { @@ -175,7 +175,7 @@ impl List { // a removed bag means that all members of that bag must be rebagged for removed_bag in removed_bags.clone() { if !affected_old_bags.insert(removed_bag) { - continue + continue; } if let Some(bag) = Bag::::get(removed_bag) { @@ -263,7 +263,7 @@ impl List { /// Returns an error if the list already contains `id`. pub(crate) fn insert(id: T::AccountId, weight: VoteWeight) -> Result<(), Error> { if Self::contains(&id) { - return Err(Error::Duplicate) + return Err(Error::Duplicate); } let bag_weight = notional_bag_for::(weight); @@ -568,7 +568,7 @@ impl Bag { // infinite loop. debug_assert!(false, "system logic error: inserting a node who has the id of tail"); crate::log!(warn, "system logic error: inserting a node who has the id of tail"); - return + return; }; } @@ -775,9 +775,9 @@ impl Node { ); frame_support::ensure!( - !self.is_terminal() || - expected_bag.head.as_ref() == Some(id) || - expected_bag.tail.as_ref() == Some(id), + !self.is_terminal() + || expected_bag.head.as_ref() == Some(id) + || expected_bag.tail.as_ref() == Some(id), "a terminal node is neither its bag head or tail" ); diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 8dfc1f17155ba..1e032fd30503a 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -346,7 +346,7 @@ pub mod pallet { (account.free, account.reserved) })?; - Self::deposit_event(Event::BalanceSet{who, free, reserved}); + Self::deposit_event(Event::BalanceSet { who, free, reserved }); Ok(().into()) } @@ -455,22 +455,22 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { /// An account was created with some free balance. - Endowed{account: T::AccountId, free_balance: T::Balance}, + Endowed { account: T::AccountId, free_balance: T::Balance }, /// An account was removed whose balance was non-zero but below ExistentialDeposit, /// resulting in an outright loss. - DustLost{account: T::AccountId, balance: T::Balance}, + DustLost { account: T::AccountId, balance: T::Balance }, /// Transfer succeeded. - Transfer{from: T::AccountId, to: T::AccountId, value: T::Balance}, + Transfer { from: T::AccountId, to: T::AccountId, value: T::Balance }, /// A balance was set by root. - BalanceSet{who: T::AccountId, free: T::Balance, reserved: T::Balance}, + BalanceSet { who: T::AccountId, free: T::Balance, reserved: T::Balance }, /// Some amount was deposited (e.g. for transaction fees). Deposit{who: T::AccountId, deposit: T::Balance}, /// Some amount was withdrawn from the account (e.g. for transaction fees). \[who, value\] Withdraw{who: T::AccountId, amount: T::Balance}, /// Some balance was reserved (moved from free to reserved). - Reserved{who: T::AccountId, value: T::Balance}, + Reserved { who: T::AccountId, value: T::Balance }, /// Some balance was unreserved (moved from reserved to free). - Unreserved{who: T::AccountId, value: T::Balance}, + Unreserved { who: T::AccountId, value: T::Balance }, /// Some balance was moved from the reserve of the first account to the second account. /// Final argument indicates the destination balance type. ReserveRepatriated{from: T::AccountId, to: T::AccountId, balance: T::Balance, destination_status: Status}, @@ -646,7 +646,7 @@ impl BitOr for Reasons { type Output = Reasons; fn bitor(self, other: Reasons) -> Reasons { if self == other { - return self + return self; } Reasons::All } @@ -740,7 +740,7 @@ pub struct DustCleaner, I: 'static = ()>( impl, I: 'static> Drop for DustCleaner { fn drop(&mut self) { if let Some((who, dust)) = self.0.take() { - Pallet::::deposit_event(Event::DustLost{account: who, balance: dust.peek()}); + Pallet::::deposit_event(Event::DustLost { account: who, balance: dust.peek() }); T::DustRemoval::on_unbalanced(dust); } } @@ -804,11 +804,11 @@ impl, I: 'static> Pallet { account: &AccountData, ) -> DepositConsequence { if amount.is_zero() { - return DepositConsequence::Success + return DepositConsequence::Success; } if TotalIssuance::::get().checked_add(&amount).is_none() { - return DepositConsequence::Overflow + return DepositConsequence::Overflow; } let new_total_balance = match account.total().checked_add(&amount) { @@ -817,7 +817,7 @@ impl, I: 'static> Pallet { }; if new_total_balance < T::ExistentialDeposit::get() { - return DepositConsequence::BelowMinimum + return DepositConsequence::BelowMinimum; } // NOTE: We assume that we are a provider, so don't need to do any checks in the @@ -832,11 +832,11 @@ impl, I: 'static> Pallet { account: &AccountData, ) -> WithdrawConsequence { if amount.is_zero() { - return WithdrawConsequence::Success + return WithdrawConsequence::Success; } if TotalIssuance::::get().checked_sub(&amount).is_none() { - return WithdrawConsequence::Underflow + return WithdrawConsequence::Underflow; } let new_total_balance = match account.total().checked_sub(&amount) { @@ -853,7 +853,7 @@ impl, I: 'static> Pallet { if frame_system::Pallet::::can_dec_provider(who) { WithdrawConsequence::ReducedToZero(new_total_balance) } else { - return WithdrawConsequence::WouldDie + return WithdrawConsequence::WouldDie; } } else { WithdrawConsequence::Success @@ -868,7 +868,7 @@ impl, I: 'static> Pallet { // Eventual free funds must be no less than the frozen balance. let min_balance = account.frozen(Reasons::All); if new_free_balance < min_balance { - return WithdrawConsequence::Frozen + return WithdrawConsequence::Frozen; } success @@ -937,7 +937,7 @@ impl, I: 'static> Pallet { }); result.map(|(maybe_endowed, maybe_dust, result)| { if let Some(endowed) = maybe_endowed { - Self::deposit_event(Event::Endowed{account: who.clone(), free_balance: endowed}); + Self::deposit_event(Event::Endowed { account: who.clone(), free_balance: endowed }); } let dust_cleaner = DustCleaner(maybe_dust.map(|dust| (who.clone(), dust))); (result, dust_cleaner) @@ -1011,14 +1011,14 @@ impl, I: 'static> Pallet { status: Status, ) -> Result { if value.is_zero() { - return Ok(Zero::zero()) + return Ok(Zero::zero()); } if slashed == beneficiary { return match status { Status::Free => Ok(Self::unreserve(slashed, value)), Status::Reserved => Ok(value.saturating_sub(Self::reserved_balance(slashed))), - } + }; } let ((actual, _maybe_one_dust), _maybe_other_dust) = Self::try_mutate_account_with_dust( @@ -1031,16 +1031,18 @@ impl, I: 'static> Pallet { let actual = cmp::min(from_account.reserved, value); ensure!(best_effort || actual == value, Error::::InsufficientBalance); match status { - Status::Free => + Status::Free => { to_account.free = to_account .free .checked_add(&actual) - .ok_or(ArithmeticError::Overflow)?, - Status::Reserved => + .ok_or(ArithmeticError::Overflow)? + } + Status::Reserved => { to_account.reserved = to_account .reserved .checked_add(&actual) - .ok_or(ArithmeticError::Overflow)?, + .ok_or(ArithmeticError::Overflow)? + } } from_account.reserved -= actual; Ok(actual) @@ -1049,7 +1051,7 @@ impl, I: 'static> Pallet { }, )?; - Self::deposit_event(Event::ReserveRepatriated{ + Self::deposit_event(Event::ReserveRepatriated { from: slashed.clone(), to: beneficiary.clone(), balance: actual, @@ -1099,7 +1101,7 @@ impl, I: 'static> fungible::Inspect for Pallet impl, I: 'static> fungible::Mutate for Pallet { fn mint_into(who: &T::AccountId, amount: Self::Balance) -> DispatchResult { if amount.is_zero() { - return Ok(()) + return Ok(()); } Self::try_mutate_account(who, |account, _is_new| -> DispatchResult { Self::deposit_consequence(who, amount, &account).into_result()?; @@ -1116,7 +1118,7 @@ impl, I: 'static> fungible::Mutate for Pallet { amount: Self::Balance, ) -> Result { if amount.is_zero() { - return Ok(Self::Balance::zero()) + return Ok(Self::Balance::zero()); } let actual = Self::try_mutate_account( who, @@ -1167,7 +1169,7 @@ impl, I: 'static> fungible::InspectHold for Pallet, I: 'static> fungible::InspectHold for Pallet, I: 'static> fungible::MutateHold for Pallet { fn hold(who: &T::AccountId, amount: Self::Balance) -> DispatchResult { if amount.is_zero() { - return Ok(()) + return Ok(()); } ensure!(Self::can_reserve(who, amount), Error::::InsufficientBalance); Self::mutate_account(who, |a| { @@ -1196,7 +1198,7 @@ impl, I: 'static> fungible::MutateHold for Pallet Result { if amount.is_zero() { - return Ok(amount) + return Ok(amount); } // Done on a best-effort basis. Self::try_mutate_account(who, |a, _| { @@ -1402,7 +1404,7 @@ where // Check if `value` amount of free balance can be slashed from `who`. fn can_slash(who: &T::AccountId, value: Self::Balance) -> bool { if value.is_zero() { - return true + return true; } Self::free_balance(who) >= value } @@ -1419,7 +1421,7 @@ where // Is a no-op if amount to be burned is zero. fn burn(mut amount: Self::Balance) -> Self::PositiveImbalance { if amount.is_zero() { - return PositiveImbalance::zero() + return PositiveImbalance::zero(); } >::mutate(|issued| { *issued = issued.checked_sub(&amount).unwrap_or_else(|| { @@ -1435,7 +1437,7 @@ where // Is a no-op if amount to be issued it zero. fn issue(mut amount: Self::Balance) -> Self::NegativeImbalance { if amount.is_zero() { - return NegativeImbalance::zero() + return NegativeImbalance::zero(); } >::mutate(|issued| { *issued = issued.checked_add(&amount).unwrap_or_else(|| { @@ -1465,7 +1467,7 @@ where new_balance: T::Balance, ) -> DispatchResult { if amount.is_zero() { - return Ok(()) + return Ok(()); } let min_balance = Self::account(who).frozen(reasons.into()); ensure!(new_balance >= min_balance, Error::::LiquidityRestrictions); @@ -1481,7 +1483,7 @@ where existence_requirement: ExistenceRequirement, ) -> DispatchResult { if value.is_zero() || transactor == dest { - return Ok(()) + return Ok(()); } Self::try_mutate_account_with_dust( @@ -1529,7 +1531,7 @@ where )?; // Emit transfer event. - Self::deposit_event(Event::Transfer{from: transactor.clone(), to: dest.clone(), value}); + Self::deposit_event(Event::Transfer { from: transactor.clone(), to: dest.clone(), value }); Ok(()) } @@ -1545,10 +1547,10 @@ where /// inconsistent or `can_slash` wasn't used appropriately. fn slash(who: &T::AccountId, value: Self::Balance) -> (Self::NegativeImbalance, Self::Balance) { if value.is_zero() { - return (NegativeImbalance::zero(), Zero::zero()) + return (NegativeImbalance::zero(), Zero::zero()); } if Self::total_balance(&who).is_zero() { - return (NegativeImbalance::zero(), value) + return (NegativeImbalance::zero(), value); } for attempt in 0..2 { @@ -1615,7 +1617,7 @@ where value: Self::Balance, ) -> Result { if value.is_zero() { - return Ok(PositiveImbalance::zero()) + return Ok(PositiveImbalance::zero()); } Self::try_mutate_account( @@ -1640,7 +1642,7 @@ where /// - `value` is so large it would cause the balance of `who` to overflow. fn deposit_creating(who: &T::AccountId, value: Self::Balance) -> Self::PositiveImbalance { if value.is_zero() { - return Self::PositiveImbalance::zero() + return Self::PositiveImbalance::zero(); } let r = Self::try_mutate_account( @@ -1675,7 +1677,7 @@ where liveness: ExistenceRequirement, ) -> result::Result { if value.is_zero() { - return Ok(NegativeImbalance::zero()) + return Ok(NegativeImbalance::zero()); } Self::try_mutate_account( @@ -1744,7 +1746,7 @@ where /// Always `true` if value to be reserved is zero. fn can_reserve(who: &T::AccountId, value: Self::Balance) -> bool { if value.is_zero() { - return true + return true; } Self::account(who).free.checked_sub(&value).map_or(false, |new_balance| { Self::ensure_can_withdraw(who, value, WithdrawReasons::RESERVE, new_balance).is_ok() @@ -1760,7 +1762,7 @@ where /// Is a no-op if value to be reserved is zero. fn reserve(who: &T::AccountId, value: Self::Balance) -> DispatchResult { if value.is_zero() { - return Ok(()) + return Ok(()); } Self::try_mutate_account(who, |account, _| -> DispatchResult { @@ -1771,7 +1773,7 @@ where Self::ensure_can_withdraw(&who, value.clone(), WithdrawReasons::RESERVE, account.free) })?; - Self::deposit_event(Event::Reserved{who: who.clone(), value}); + Self::deposit_event(Event::Reserved { who: who.clone(), value }); Ok(()) } @@ -1780,10 +1782,10 @@ where /// Is a no-op if the value to be unreserved is zero or the account does not exist. fn unreserve(who: &T::AccountId, value: Self::Balance) -> Self::Balance { if value.is_zero() { - return Zero::zero() + return Zero::zero(); } if Self::total_balance(&who).is_zero() { - return value + return value; } let actual = match Self::mutate_account(who, |account| { @@ -1799,11 +1801,11 @@ where // This should never happen since we don't alter the total amount in the account. // If it ever does, then we should fail gracefully though, indicating that nothing // could be done. - return value - }, + return value; + } }; - Self::deposit_event(Event::Unreserved{who: who.clone(), value: actual.clone()}); + Self::deposit_event(Event::Unreserved { who: who.clone(), value: actual.clone() }); value - actual } @@ -1816,10 +1818,10 @@ where value: Self::Balance, ) -> (Self::NegativeImbalance, Self::Balance) { if value.is_zero() { - return (NegativeImbalance::zero(), Zero::zero()) + return (NegativeImbalance::zero(), Zero::zero()); } if Self::total_balance(&who).is_zero() { - return (NegativeImbalance::zero(), value) + return (NegativeImbalance::zero(), value); } // NOTE: `mutate_account` may fail if it attempts to reduce the balance to the point that an @@ -1897,7 +1899,7 @@ where value: Self::Balance, ) -> DispatchResult { if value.is_zero() { - return Ok(()) + return Ok(()); } Reserves::::try_mutate(who, |reserves| -> DispatchResult { @@ -1905,12 +1907,12 @@ where Ok(index) => { // this add can't overflow but just to be defensive. reserves[index].amount = reserves[index].amount.saturating_add(value); - }, + } Err(index) => { reserves .try_insert(index, ReserveData { id: id.clone(), amount: value }) .map_err(|_| Error::::TooManyReserves)?; - }, + } }; >::reserve(who, value)?; Ok(()) @@ -1926,7 +1928,7 @@ where value: Self::Balance, ) -> Self::Balance { if value.is_zero() { - return Zero::zero() + return Zero::zero(); } Reserves::::mutate_exists(who, |maybe_reserves| -> Self::Balance { @@ -1954,7 +1956,7 @@ where } value - actual - }, + } Err(_) => value, } } else { @@ -1973,7 +1975,7 @@ where value: Self::Balance, ) -> (Self::NegativeImbalance, Self::Balance) { if value.is_zero() { - return (NegativeImbalance::zero(), Zero::zero()) + return (NegativeImbalance::zero(), Zero::zero()); } Reserves::::mutate(who, |reserves| -> (Self::NegativeImbalance, Self::Balance) { @@ -1992,7 +1994,7 @@ where Self::deposit_event(Event::Slashed{who: who.clone(), amount_slashed: actual}); (imb, value - actual) - }, + } Err(_) => (NegativeImbalance::zero(), value), } }) @@ -2012,15 +2014,16 @@ where status: Status, ) -> Result { if value.is_zero() { - return Ok(Zero::zero()) + return Ok(Zero::zero()); } if slashed == beneficiary { return match status { Status::Free => Ok(Self::unreserve_named(id, slashed, value)), - Status::Reserved => - Ok(value.saturating_sub(Self::reserved_balance_named(id, slashed))), - } + Status::Reserved => { + Ok(value.saturating_sub(Self::reserved_balance_named(id, slashed))) + } + }; } Reserves::::try_mutate(slashed, |reserves| -> Result { @@ -2052,7 +2055,7 @@ where reserves[index].amount.saturating_add(actual); Ok(actual) - }, + } Err(index) => { let remain = >::repatriate_reserved( @@ -2074,7 +2077,7 @@ where .map_err(|_| Error::::TooManyReserves)?; Ok(actual) - }, + } } }, )? @@ -2094,7 +2097,7 @@ where reserves[index].amount -= actual; Ok(value - actual) - }, + } Err(_) => Ok(value), } }) @@ -2118,7 +2121,7 @@ where reasons: WithdrawReasons, ) { if amount.is_zero() || reasons.is_empty() { - return + return; } let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() }); let mut locks = Self::locks(who) @@ -2140,7 +2143,7 @@ where reasons: WithdrawReasons, ) { if amount.is_zero() || reasons.is_empty() { - return + return; } let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() }); let mut locks = Self::locks(who) diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index 9913b5940496e..a6febf270c24a 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -164,8 +164,8 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { events(), [ Event::System(system::Event::NewAccount(1)), - Event::Balances(crate::Event::Endowed{account: 1, free_balance: 100}), - Event::Balances(crate::Event::BalanceSet{who: 1, free: 100, reserved: 0}), + Event::Balances(crate::Event::Endowed { account: 1, free_balance: 100 }), + Event::Balances(crate::Event::BalanceSet { who: 1, free: 100, reserved: 0 }), ] ); @@ -182,7 +182,7 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { events(), [ Event::System(system::Event::KilledAccount(1)), - Event::Balances(crate::Event::DustLost{account: 1, balance: 1}), + Event::Balances(crate::Event::DustLost { account: 1, balance: 1 }), Event::Balances(crate::Event::Slashed{who: 1, amount_slashed: 1}) ] ); diff --git a/frame/balances/src/tests_reentrancy.rs b/frame/balances/src/tests_reentrancy.rs index e1d8cfe5a15c7..e171bb8629501 100644 --- a/frame/balances/src/tests_reentrancy.rs +++ b/frame/balances/src/tests_reentrancy.rs @@ -169,8 +169,15 @@ fn transfer_dust_removal_tst1_should_work() { // Verify the events assert_eq!(System::events().len(), 12); - System::assert_has_event(Event::Balances(crate::Event::Transfer{from: 2, to: 3, value: 450})); - System::assert_has_event(Event::Balances(crate::Event::DustLost{account: 2, balance: 50})); + System::assert_has_event(Event::Balances(crate::Event::Transfer { + from: 2, + to: 3, + value: 450, + })); + System::assert_has_event(Event::Balances(crate::Event::DustLost { + account: 2, + balance: 50, + })); System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 50})); }); } @@ -197,8 +204,15 @@ fn transfer_dust_removal_tst2_should_work() { // Verify the events assert_eq!(System::events().len(), 10); - System::assert_has_event(Event::Balances(crate::Event::Transfer{from: 2, to: 1, value: 450})); - System::assert_has_event(Event::Balances(crate::Event::DustLost{account: 2, balance: 50})); + System::assert_has_event(Event::Balances(crate::Event::Transfer { + from: 2, + to: 1, + value: 450, + })); + System::assert_has_event(Event::Balances(crate::Event::DustLost { + account: 2, + balance: 50, + })); System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 50})); }); } @@ -234,14 +248,17 @@ fn repatriating_reserved_balance_dust_removal_should_work() { // Verify the events assert_eq!(System::events().len(), 11); - System::assert_has_event(Event::Balances(crate::Event::ReserveRepatriated{ + System::assert_has_event(Event::Balances(crate::Event::ReserveRepatriated { from: 2, to: 1, balance: 450, destination_status: Status::Free, })); - System::assert_last_event(Event::Balances(crate::Event::DustLost{account: 2, balance: 50})); + System::assert_last_event(Event::Balances(crate::Event::DustLost { + account: 2, + balance: 50, + })); System::assert_last_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 50})); }); } diff --git a/frame/beefy-mmr/primitives/src/lib.rs b/frame/beefy-mmr/primitives/src/lib.rs index 4d4d4e8721ac8..9adae4a2935a7 100644 --- a/frame/beefy-mmr/primitives/src/lib.rs +++ b/frame/beefy-mmr/primitives/src/lib.rs @@ -113,7 +113,7 @@ where // swap collections to avoid allocations upper = next; next = t; - }, + } }; } } @@ -282,7 +282,7 @@ where L: Into>, { if leaf_index >= number_of_leaves { - return false + return false; } let leaf_hash = match leaf.into() { @@ -354,11 +354,11 @@ where combined[32..64].copy_from_slice(&b); next.push(H::hash(&combined)); - }, + } // Odd number of items. Promote the item to the upper layer. (Some(a), None) if !next.is_empty() => { next.push(a); - }, + } // Last item = root. (Some(a), None) => return Ok(a), // Finish up, no more items. @@ -368,8 +368,8 @@ where "[merkelize_row] Next: {:?}", next.iter().map(hex::encode).collect::>() ); - return Err(next) - }, + return Err(next); + } } } } diff --git a/frame/beefy-mmr/src/lib.rs b/frame/beefy-mmr/src/lib.rs index 001831639b169..fc47477ef3a8a 100644 --- a/frame/beefy-mmr/src/lib.rs +++ b/frame/beefy-mmr/src/lib.rs @@ -219,7 +219,7 @@ where let current_next = Self::beefy_next_authorities(); // avoid computing the merkle tree if validator set id didn't change. if id == current_next.id { - return current_next + return current_next; } let beefy_addresses = pallet_beefy::Pallet::::next_authorities() diff --git a/frame/beefy/src/lib.rs b/frame/beefy/src/lib.rs index 3b28d454849cf..ed6102f6aafde 100644 --- a/frame/beefy/src/lib.rs +++ b/frame/beefy/src/lib.rs @@ -123,7 +123,7 @@ impl Pallet { fn initialize_authorities(authorities: &[T::BeefyId]) { if authorities.is_empty() { - return + return; } assert!(>::get().is_empty(), "Authorities are already initialized!"); diff --git a/frame/benchmarking/src/analysis.rs b/frame/benchmarking/src/analysis.rs index 2bb20ebe2e7f8..63ee55febb4a8 100644 --- a/frame/benchmarking/src/analysis.rs +++ b/frame/benchmarking/src/analysis.rs @@ -78,7 +78,7 @@ impl Analysis { // results. Note: We choose the median value because it is more robust to outliers. fn median_value(r: &Vec, selector: BenchmarkSelector) -> Option { if r.is_empty() { - return None + return None; } let mut values: Vec = r @@ -106,7 +106,7 @@ impl Analysis { pub fn median_slopes(r: &Vec, selector: BenchmarkSelector) -> Option { if r[0].components.is_empty() { - return Self::median_value(r, selector) + return Self::median_value(r, selector); } let results = r[0] @@ -201,7 +201,7 @@ impl Analysis { pub fn min_squares_iqr(r: &Vec, selector: BenchmarkSelector) -> Option { if r[0].components.is_empty() { - return Self::median_value(r, selector) + return Self::median_value(r, selector); } let mut results = BTreeMap::, Vec>::new(); @@ -257,7 +257,7 @@ impl Analysis { .map(|(p, vs)| { // Avoid divide by zero if vs.len() == 0 { - return (p.clone(), 0, 0) + return (p.clone(), 0, 0); } let total = vs.iter().fold(0u128, |acc, v| acc + *v); let mean = total / vs.len() as u128; @@ -284,7 +284,7 @@ impl Analysis { let min_squares = Self::min_squares_iqr(r, selector); if median_slopes.is_none() || min_squares.is_none() { - return None + return None; } let median_slopes = median_slopes.unwrap(); @@ -316,7 +316,7 @@ fn ms(mut nanos: u128) -> String { while x > 1 { if nanos > x * 1_000 { nanos = nanos / x * x; - break + break; } x /= 10; } diff --git a/frame/benchmarking/src/lib.rs b/frame/benchmarking/src/lib.rs index 1805424426f6e..b9807ca2ea355 100644 --- a/frame/benchmarking/src/lib.rs +++ b/frame/benchmarking/src/lib.rs @@ -905,7 +905,7 @@ macro_rules! impl_bench_name_tests { // Every variant must implement [`BenchmarkingSetup`]. // // ```nocompile -// +// // struct Transfer; // impl BenchmarkingSetup for Transfer { ... } // diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index a2cf381e6ecf8..0d7da7fc7bc61 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -65,7 +65,7 @@ mod pallet_test { #[pallet::weight(0)] pub fn always_error(_origin: OriginFor) -> DispatchResult { - return Err("I always fail".into()) + return Err("I always fail".into()); } } } diff --git a/frame/benchmarking/src/utils.rs b/frame/benchmarking/src/utils.rs index c24ad2f64e18d..ce8e0133a6de7 100644 --- a/frame/benchmarking/src/utils.rs +++ b/frame/benchmarking/src/utils.rs @@ -258,11 +258,11 @@ pub trait Benchmarking { item.reads += add.reads; item.writes += add.writes; item.whitelisted = item.whitelisted || add.whitelisted; - }, + } // If the key does not exist, add it. None => { whitelist.push(add); - }, + } } self.set_whitelist(whitelist); } diff --git a/frame/bounties/src/lib.rs b/frame/bounties/src/lib.rs index c98d68287b321..33132c160e864 100644 --- a/frame/bounties/src/lib.rs +++ b/frame/bounties/src/lib.rs @@ -229,19 +229,19 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// New bounty proposal. - BountyProposed{index: BountyIndex}, + BountyProposed { index: BountyIndex }, /// A bounty proposal was rejected; funds were slashed. - BountyRejected{index: BountyIndex, bond: BalanceOf}, + BountyRejected { index: BountyIndex, bond: BalanceOf }, /// A bounty proposal is funded and became active. - BountyBecameActive{index: BountyIndex}, + BountyBecameActive { index: BountyIndex }, /// A bounty is awarded to a beneficiary. - BountyAwarded{index: BountyIndex, beneficiary: T::AccountId}, + BountyAwarded { index: BountyIndex, beneficiary: T::AccountId }, /// A bounty is claimed by beneficiary. - BountyClaimed{index: BountyIndex, payout: BalanceOf, beneficiary: T::AccountId}, + BountyClaimed { index: BountyIndex, payout: BalanceOf, beneficiary: T::AccountId }, /// A bounty is cancelled. - BountyCanceled{index: BountyIndex}, + BountyCanceled { index: BountyIndex }, /// A bounty expiry is extended. - BountyExtended{index: BountyIndex}, + BountyExtended { index: BountyIndex }, } /// Number of bounty proposals that have been made. @@ -342,7 +342,7 @@ pub mod pallet { Bounties::::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult { let mut bounty = maybe_bounty.as_mut().ok_or(Error::::InvalidIndex)?; match bounty.status { - BountyStatus::Proposed | BountyStatus::Approved | BountyStatus::Funded => {}, + BountyStatus::Proposed | BountyStatus::Approved | BountyStatus::Funded => {} _ => return Err(Error::::UnexpectedStatus.into()), }; @@ -395,13 +395,13 @@ pub mod pallet { match bounty.status { BountyStatus::Proposed | BountyStatus::Approved | BountyStatus::Funded => { // No curator to unassign at this point. - return Err(Error::::UnexpectedStatus.into()) - }, + return Err(Error::::UnexpectedStatus.into()); + } BountyStatus::CuratorProposed { ref curator } => { // A curator has been proposed, but not accepted yet. // Either `RejectOrigin` or the proposed curator can unassign the curator. ensure!(maybe_sender.map_or(true, |sender| sender == *curator), BadOrigin); - }, + } BountyStatus::Active { ref curator, ref update_due } => { // The bounty is active. match maybe_sender { @@ -409,7 +409,7 @@ pub mod pallet { None => { slash_curator(curator, &mut bounty.curator_deposit); // Continue to change bounty status below... - }, + } Some(sender) => { // If the sender is not the curator, and the curator is inactive, // slash the curator. @@ -420,7 +420,7 @@ pub mod pallet { // Continue to change bounty status below... } else { // Curator has more time to give an update. - return Err(Error::::Premature.into()) + return Err(Error::::Premature.into()); } } else { // Else this is the curator, willingly giving up their role. @@ -430,9 +430,9 @@ pub mod pallet { debug_assert!(err_amount.is_zero()); // Continue to change bounty status below... } - }, + } } - }, + } BountyStatus::PendingPayout { ref curator, .. } => { // The bounty is pending payout, so only council can unassign a curator. // By doing so, they are claiming the curator is acting maliciously, so @@ -440,7 +440,7 @@ pub mod pallet { ensure!(maybe_sender.is_none(), BadOrigin); slash_curator(curator, &mut bounty.curator_deposit); // Continue to change bounty status below... - }, + } }; bounty.status = BountyStatus::Funded; @@ -475,13 +475,13 @@ pub mod pallet { T::Currency::reserve(curator, deposit)?; bounty.curator_deposit = deposit; - let update_due = frame_system::Pallet::::block_number() + - T::BountyUpdatePeriod::get(); + let update_due = frame_system::Pallet::::block_number() + + T::BountyUpdatePeriod::get(); bounty.status = BountyStatus::Active { curator: curator.clone(), update_due }; Ok(()) - }, + } _ => Err(Error::::UnexpectedStatus.into()), } })?; @@ -513,20 +513,20 @@ pub mod pallet { match &bounty.status { BountyStatus::Active { curator, .. } => { ensure!(signer == *curator, Error::::RequireCurator); - }, + } _ => return Err(Error::::UnexpectedStatus.into()), } bounty.status = BountyStatus::PendingPayout { curator: signer, beneficiary: beneficiary.clone(), - unlock_at: frame_system::Pallet::::block_number() + - T::BountyDepositPayoutDelay::get(), + unlock_at: frame_system::Pallet::::block_number() + + T::BountyDepositPayoutDelay::get(), }; Ok(()) })?; - Self::deposit_event(Event::::BountyAwarded{index: bounty_id, beneficiary}); + Self::deposit_event(Event::::BountyAwarded { index: bounty_id, beneficiary }); Ok(()) } @@ -571,7 +571,11 @@ pub mod pallet { BountyDescriptions::::remove(bounty_id); - Self::deposit_event(Event::::BountyClaimed{index: bounty_id, payout, beneficiary}); + Self::deposit_event(Event::::BountyClaimed { + index: bounty_id, + payout, + beneficiary, + }); Ok(()) } else { Err(Error::::UnexpectedStatus.into()) @@ -612,34 +616,37 @@ pub mod pallet { T::OnSlash::on_unbalanced(imbalance); *maybe_bounty = None; - Self::deposit_event(Event::::BountyRejected{index: bounty_id, bond: value}); + Self::deposit_event(Event::::BountyRejected { + index: bounty_id, + bond: value, + }); // Return early, nothing else to do. return Ok( Some(::WeightInfo::close_bounty_proposed()).into() - ) - }, + ); + } BountyStatus::Approved => { // For weight reasons, we don't allow a council to cancel in this phase. // We ask for them to wait until it is funded before they can cancel. - return Err(Error::::UnexpectedStatus.into()) - }, + return Err(Error::::UnexpectedStatus.into()); + } BountyStatus::Funded | BountyStatus::CuratorProposed { .. } => { // Nothing extra to do besides the removal of the bounty below. - }, + } BountyStatus::Active { curator, .. } => { // Cancelled by council, refund deposit of the working curator. let err_amount = T::Currency::unreserve(&curator, bounty.curator_deposit); debug_assert!(err_amount.is_zero()); // Then execute removal of the bounty below. - }, + } BountyStatus::PendingPayout { .. } => { // Bounty is already pending payout. If council wants to cancel // this bounty, it should mean the curator was acting maliciously. // So the council should first unassign the curator, slashing their // deposit. - return Err(Error::::PendingPayout.into()) - }, + return Err(Error::::PendingPayout.into()); + } } let bounty_account = Self::bounty_account_id(bounty_id); @@ -656,7 +663,7 @@ pub mod pallet { debug_assert!(res.is_ok()); *maybe_bounty = None; - Self::deposit_event(Event::::BountyCanceled{index: bounty_id}); + Self::deposit_event(Event::::BountyCanceled { index: bounty_id }); Ok(Some(::WeightInfo::close_bounty_active()).into()) }, ) @@ -686,17 +693,17 @@ pub mod pallet { match bounty.status { BountyStatus::Active { ref curator, ref mut update_due } => { ensure!(*curator == signer, Error::::RequireCurator); - *update_due = (frame_system::Pallet::::block_number() + - T::BountyUpdatePeriod::get()) + *update_due = (frame_system::Pallet::::block_number() + + T::BountyUpdatePeriod::get()) .max(*update_due); - }, + } _ => return Err(Error::::UnexpectedStatus.into()), } Ok(()) })?; - Self::deposit_event(Event::::BountyExtended{index: bounty_id}); + Self::deposit_event(Event::::BountyExtended { index: bounty_id }); Ok(()) } } @@ -734,8 +741,8 @@ impl Pallet { let index = Self::bounty_count(); // reserve deposit for new bounty - let bond = T::BountyDepositBase::get() + - T::DataDepositPerByte::get() * (description.len() as u32).into(); + let bond = T::BountyDepositBase::get() + + T::DataDepositPerByte::get() * (description.len() as u32).into(); T::Currency::reserve(&proposer, bond) .map_err(|_| Error::::InsufficientProposersBalance)?; @@ -753,7 +760,7 @@ impl Pallet { Bounties::::insert(index, &bounty); BountyDescriptions::::insert(index, description); - Self::deposit_event(Event::::BountyProposed{index}); + Self::deposit_event(Event::::BountyProposed { index }); Ok(()) } @@ -787,7 +794,7 @@ impl pallet_treasury::SpendFunds for Pallet { bounty.value, )); - Self::deposit_event(Event::::BountyBecameActive{index}); + Self::deposit_event(Event::::BountyBecameActive { index }); false } else { *missed_any = true; diff --git a/frame/bounties/src/migrations/v4.rs b/frame/bounties/src/migrations/v4.rs index a1ca0e47680b0..d39e2c317ca06 100644 --- a/frame/bounties/src/migrations/v4.rs +++ b/frame/bounties/src/migrations/v4.rs @@ -54,7 +54,7 @@ pub fn migrate< target: "runtime::bounties", "New pallet name is equal to the old prefix. No migration needs to be done.", ); - return 0 + return 0; } let on_chain_storage_version =

::on_chain_storage_version(); diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index ef96997e427ba..344bb6495c3bc 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -398,7 +398,7 @@ fn propose_bounty_works() { assert_ok!(Bounties::propose_bounty(Origin::signed(0), 10, b"1234567890".to_vec())); - assert_eq!(last_event(), BountiesEvent::BountyProposed{index: 0}); + assert_eq!(last_event(), BountiesEvent::BountyProposed { index: 0 }); let deposit: u64 = 85 + 5; assert_eq!(Balances::reserved_balance(0), deposit); @@ -460,7 +460,7 @@ fn close_bounty_works() { let deposit: u64 = 80 + 5; - assert_eq!(last_event(), BountiesEvent::BountyRejected{index: 0, bond: deposit}); + assert_eq!(last_event(), BountiesEvent::BountyRejected { index: 0, bond: deposit }); assert_eq!(Balances::reserved_balance(0), 0); assert_eq!(Balances::free_balance(0), 100 - deposit); @@ -692,7 +692,10 @@ fn award_and_claim_bounty_works() { assert_ok!(Bounties::claim_bounty(Origin::signed(1), 0)); - assert_eq!(last_event(), BountiesEvent::BountyClaimed{index: 0, payout: 56, beneficiary: 3}); + assert_eq!( + last_event(), + BountiesEvent::BountyClaimed { index: 0, payout: 56, beneficiary: 3 } + ); assert_eq!(Balances::free_balance(4), 14); // initial 10 + fee 4 @@ -731,7 +734,10 @@ fn claim_handles_high_fee() { assert_ok!(Bounties::claim_bounty(Origin::signed(1), 0)); - assert_eq!(last_event(), BountiesEvent::BountyClaimed{index: 0, payout: 0, beneficiary: 3}); + assert_eq!( + last_event(), + BountiesEvent::BountyClaimed { index: 0, payout: 0, beneficiary: 3 } + ); assert_eq!(Balances::free_balance(4), 70); // 30 + 50 - 10 assert_eq!(Balances::free_balance(3), 0); @@ -808,7 +814,7 @@ fn award_and_cancel() { assert_ok!(Bounties::unassign_curator(Origin::root(), 0)); assert_ok!(Bounties::close_bounty(Origin::root(), 0)); - assert_eq!(last_event(), BountiesEvent::BountyCanceled{index: 0}); + assert_eq!(last_event(), BountiesEvent::BountyCanceled { index: 0 }); assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 0); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 02edb7c8435d2..cdb554944499d 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -279,20 +279,31 @@ pub mod pallet { pub enum Event, I: 'static = ()> { /// A motion (given hash) has been proposed (by given account) with a threshold (given /// `MemberCount`). - Proposed{account: T::AccountId, proposal_index: ProposalIndex, proposal_hash: T::Hash, threshold: MemberCount}, + Proposed { + account: T::AccountId, + proposal_index: ProposalIndex, + proposal_hash: T::Hash, + threshold: MemberCount, + }, /// A motion (given hash) has been voted on by given account, leaving /// a tally (yes votes and no votes given respectively as `MemberCount`). - Voted{account: T::AccountId, proposal_hash: T::Hash, voted: bool, yes: MemberCount, no: MemberCount}, + Voted { + account: T::AccountId, + proposal_hash: T::Hash, + voted: bool, + yes: MemberCount, + no: MemberCount, + }, /// A motion was approved by the required threshold. - Approved{proposal_hash: T::Hash}, + Approved { proposal_hash: T::Hash }, /// A motion was not approved by the required threshold. - Disapproved{proposal_hash: T::Hash}, + Disapproved { proposal_hash: T::Hash }, /// A motion was executed; result will be `Ok` if it returned without error. - Executed{proposal_hash: T::Hash, result: DispatchResult}, + Executed { proposal_hash: T::Hash, result: DispatchResult }, /// A single member did some action; result will be `Ok` if it returned without error. - MemberExecuted{proposal_hash: T::Hash, result: DispatchResult}, + MemberExecuted { proposal_hash: T::Hash, result: DispatchResult }, /// A proposal was closed because its threshold was reached or after its duration was up. - Closed{proposal_hash: T::Hash, yes: MemberCount, no: MemberCount}, + Closed { proposal_hash: T::Hash, yes: MemberCount, no: MemberCount }, } /// Old name generated by `decl_event`. @@ -428,7 +439,7 @@ pub mod pallet { let proposal_hash = T::Hashing::hash_of(&proposal); let result = proposal.dispatch(RawOrigin::Member(who).into()); - Self::deposit_event(Event::MemberExecuted{ + Self::deposit_event(Event::MemberExecuted { proposal_hash, result: result.map(|_| ()).map_err(|e| e.error), }); @@ -507,7 +518,7 @@ pub mod pallet { if threshold < 2 { let seats = Self::members().len() as MemberCount; let result = proposal.dispatch(RawOrigin::Members(1, seats).into()); - Self::deposit_event(Event::Executed{ + Self::deposit_event(Event::Executed { proposal_hash, result: result.map(|_| ()).map_err(|e| e.error), }); @@ -538,7 +549,12 @@ pub mod pallet { }; >::insert(proposal_hash, votes); - Self::deposit_event(Event::Proposed{account: who, proposal_index: index, proposal_hash, threshold}); + Self::deposit_event(Event::Proposed { + account: who, + proposal_index: index, + proposal_hash, + threshold, + }); Ok(Some(T::WeightInfo::propose_proposed( proposal_len as u32, // B @@ -588,7 +604,7 @@ pub mod pallet { if position_yes.is_none() { voting.ayes.push(who.clone()); } else { - return Err(Error::::DuplicateVote.into()) + return Err(Error::::DuplicateVote.into()); } if let Some(pos) = position_no { voting.nays.swap_remove(pos); @@ -597,7 +613,7 @@ pub mod pallet { if position_no.is_none() { voting.nays.push(who.clone()); } else { - return Err(Error::::DuplicateVote.into()) + return Err(Error::::DuplicateVote.into()); } if let Some(pos) = position_yes { voting.ayes.swap_remove(pos); @@ -606,7 +622,13 @@ pub mod pallet { let yes_votes = voting.ayes.len() as MemberCount; let no_votes = voting.nays.len() as MemberCount; - Self::deposit_event(Event::Voted{account: who, proposal_hash: proposal, voted: approve, yes: yes_votes, no: no_votes}); + Self::deposit_event(Event::Voted { + account: who, + proposal_hash: proposal, + voted: approve, + yes: yes_votes, + no: no_votes, + }); Voting::::insert(&proposal, voting); @@ -687,7 +709,7 @@ pub mod pallet { length_bound, proposal_weight_bound, )?; - Self::deposit_event(Event::Closed{proposal_hash, yes: yes_votes, no: no_votes}); + Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes }); let (proposal_weight, proposal_count) = Self::do_approve_proposal(seats, yes_votes, proposal_hash, proposal); return Ok(( @@ -697,15 +719,15 @@ pub mod pallet { ), Pays::Yes, ) - .into()) + .into()); } else if disapproved { - Self::deposit_event(Event::Closed{proposal_hash, yes: yes_votes, no: no_votes}); + Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes }); let proposal_count = Self::do_disapprove_proposal(proposal_hash); return Ok(( Some(T::WeightInfo::close_early_disapproved(seats, proposal_count)), Pays::No, ) - .into()) + .into()); } // Only allow actual closing of the proposal after the voting period has ended. @@ -732,7 +754,7 @@ pub mod pallet { length_bound, proposal_weight_bound, )?; - Self::deposit_event(Event::Closed{proposal_hash, yes: yes_votes, no: no_votes}); + Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes }); let (proposal_weight, proposal_count) = Self::do_approve_proposal(seats, yes_votes, proposal_hash, proposal); Ok(( @@ -744,7 +766,7 @@ pub mod pallet { ) .into()) } else { - Self::deposit_event(Event::Closed{proposal_hash, yes: yes_votes, no: no_votes}); + Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes }); let proposal_count = Self::do_disapprove_proposal(proposal_hash); Ok((Some(T::WeightInfo::close_disapproved(seats, proposal_count)), Pays::No).into()) } @@ -834,12 +856,12 @@ impl, I: 'static> Pallet { proposal_hash: T::Hash, proposal: >::Proposal, ) -> (Weight, u32) { - Self::deposit_event(Event::Approved{proposal_hash}); + Self::deposit_event(Event::Approved { proposal_hash }); let dispatch_weight = proposal.get_dispatch_info().weight; let origin = RawOrigin::Members(yes_votes, seats).into(); let result = proposal.dispatch(origin); - Self::deposit_event(Event::Executed{ + Self::deposit_event(Event::Executed { proposal_hash, result: result.map(|_| ()).map_err(|e| e.error), }); @@ -852,7 +874,7 @@ impl, I: 'static> Pallet { fn do_disapprove_proposal(proposal_hash: T::Hash) -> u32 { // disapproved - Self::deposit_event(Event::Disapproved{proposal_hash}); + Self::deposit_event(Event::Disapproved { proposal_hash }); Self::remove_proposal(proposal_hash) } diff --git a/frame/collective/src/migrations/v4.rs b/frame/collective/src/migrations/v4.rs index 68284ba4df91d..f1537c97cd57a 100644 --- a/frame/collective/src/migrations/v4.rs +++ b/frame/collective/src/migrations/v4.rs @@ -45,7 +45,7 @@ pub fn migrate::on_chain_storage_version(); @@ -84,7 +84,7 @@ pub fn pre_migrate>(old_p log_migration("pre-migration", old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return + return; } let new_pallet_prefix = twox_128(new_pallet_name.as_bytes()); @@ -112,7 +112,7 @@ pub fn post_migrate>(old_ log_migration("post-migration", old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return + return; } // Assert that nothing remains at the old prefix. diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index 82b25c73b081b..7e52b10a9b1d6 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -216,11 +216,32 @@ fn close_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), - record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 2, no: 1})), - record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})) + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 3 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 2, + proposal_hash: hash, + voted: true, + yes: 2, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Closed { + proposal_hash: hash, + yes: 2, + no: 1 + })), + record(Event::Collective(CollectiveEvent::Disapproved { proposal_hash: hash })) ] ); }); @@ -315,11 +336,32 @@ fn close_with_prime_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), - record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 2, no: 1})), - record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})) + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 3 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 2, + proposal_hash: hash, + voted: true, + yes: 2, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Closed { + proposal_hash: hash, + yes: 2, + no: 1 + })), + record(Event::Collective(CollectiveEvent::Disapproved { proposal_hash: hash })) ] ); }); @@ -354,12 +396,33 @@ fn close_with_voting_prime_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), - record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 3, no: 0})), - record(Event::Collective(CollectiveEvent::Approved{proposal_hash: hash})), - record(Event::Collective(CollectiveEvent::Executed{ + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 3 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 2, + proposal_hash: hash, + voted: true, + yes: 2, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Closed { + proposal_hash: hash, + yes: 3, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Approved { proposal_hash: hash })), + record(Event::Collective(CollectiveEvent::Executed { proposal_hash: hash, result: Err(DispatchError::BadOrigin) })) @@ -404,13 +467,42 @@ fn close_with_no_prime_but_majority_works() { assert_eq!( System::events(), vec![ - record(Event::CollectiveMajority(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 5})), - record(Event::CollectiveMajority(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::CollectiveMajority(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), - record(Event::CollectiveMajority(CollectiveEvent::Voted{account: 3, proposal_hash: hash, voted: true, yes: 3, no: 0})), - record(Event::CollectiveMajority(CollectiveEvent::Closed{proposal_hash: hash, yes: 5, no: 0})), - record(Event::CollectiveMajority(CollectiveEvent::Approved{proposal_hash: hash})), - record(Event::CollectiveMajority(CollectiveEvent::Executed{ + record(Event::CollectiveMajority(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 5 + })), + record(Event::CollectiveMajority(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::CollectiveMajority(CollectiveEvent::Voted { + account: 2, + proposal_hash: hash, + voted: true, + yes: 2, + no: 0 + })), + record(Event::CollectiveMajority(CollectiveEvent::Voted { + account: 3, + proposal_hash: hash, + voted: true, + yes: 3, + no: 0 + })), + record(Event::CollectiveMajority(CollectiveEvent::Closed { + proposal_hash: hash, + yes: 5, + no: 0 + })), + record(Event::CollectiveMajority(CollectiveEvent::Approved { + proposal_hash: hash + })), + record(Event::CollectiveMajority(CollectiveEvent::Executed { proposal_hash: hash, result: Err(DispatchError::BadOrigin) })) @@ -537,7 +629,12 @@ fn propose_works() { assert_eq!( System::events(), - vec![record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3}))] + vec![record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 3 + }))] ); }); } @@ -696,9 +793,26 @@ fn motions_vote_after_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 2})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: false, yes: 0, no: 1})), + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 2 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: false, + yes: 0, + no: 1 + })), ] ); }); @@ -812,12 +926,33 @@ fn motions_approval_with_enough_votes_and_lower_voting_threshold_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 2})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), - record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 2, no: 0})), - record(Event::Collective(CollectiveEvent::Approved{proposal_hash: hash})), - record(Event::Collective(CollectiveEvent::Executed{ + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 2 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 2, + proposal_hash: hash, + voted: true, + yes: 2, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Closed { + proposal_hash: hash, + yes: 2, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Approved { proposal_hash: hash })), + record(Event::Collective(CollectiveEvent::Executed { proposal_hash: hash, result: Err(DispatchError::BadOrigin) })), @@ -840,14 +975,44 @@ fn motions_approval_with_enough_votes_and_lower_voting_threshold_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 1, proposal_hash: hash, threshold: 2})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 3, proposal_hash: hash, voted: true, yes: 3, no: 0})), - record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 3, no: 0})), - record(Event::Collective(CollectiveEvent::Approved{proposal_hash: hash})), + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 1, + proposal_hash: hash, + threshold: 2 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 2, + proposal_hash: hash, + voted: true, + yes: 2, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 3, + proposal_hash: hash, + voted: true, + yes: 3, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Closed { + proposal_hash: hash, + yes: 3, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Approved { proposal_hash: hash })), record(Event::Democracy(mock_democracy::pallet::Event::::ExternalProposed)), - record(Event::Collective(CollectiveEvent::Executed{proposal_hash: hash, result: Ok(())})), + record(Event::Collective(CollectiveEvent::Executed { + proposal_hash: hash, + result: Ok(()) + })), ] ); }); @@ -873,11 +1038,32 @@ fn motions_disapproval_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: false, yes: 1, no: 1})), - record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 1, no: 1})), - record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})), + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 3 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 2, + proposal_hash: hash, + voted: false, + yes: 1, + no: 1 + })), + record(Event::Collective(CollectiveEvent::Closed { + proposal_hash: hash, + yes: 1, + no: 1 + })), + record(Event::Collective(CollectiveEvent::Disapproved { proposal_hash: hash })), ] ); }); @@ -903,12 +1089,33 @@ fn motions_approval_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 2})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), - record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 2, no: 0})), - record(Event::Collective(CollectiveEvent::Approved{proposal_hash: hash})), - record(Event::Collective(CollectiveEvent::Executed{ + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 2 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 2, + proposal_hash: hash, + voted: true, + yes: 2, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Closed { + proposal_hash: hash, + yes: 2, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Approved { proposal_hash: hash })), + record(Event::Collective(CollectiveEvent::Executed { proposal_hash: hash, result: Err(DispatchError::BadOrigin) })), @@ -932,7 +1139,12 @@ fn motion_with_no_votes_closes_with_disapproval() { )); assert_eq!( System::events()[0], - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 3})) + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 3 + })) ); // Closing the motion too early is not possible because it has neither @@ -951,11 +1163,15 @@ fn motion_with_no_votes_closes_with_disapproval() { // Events show that the close ended in a disapproval. assert_eq!( System::events()[1], - record(Event::Collective(CollectiveEvent::Closed{proposal_hash: hash, yes: 0, no: 3})) + record(Event::Collective(CollectiveEvent::Closed { + proposal_hash: hash, + yes: 0, + no: 3 + })) ); assert_eq!( System::events()[2], - record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})) + record(Event::Collective(CollectiveEvent::Disapproved { proposal_hash: hash })) ); }) } @@ -1015,10 +1231,27 @@ fn disapprove_proposal_works() { assert_eq!( System::events(), vec![ - record(Event::Collective(CollectiveEvent::Proposed{account: 1, proposal_index: 0, proposal_hash: hash, threshold: 2})), - record(Event::Collective(CollectiveEvent::Voted{account: 1, proposal_hash: hash, voted: true, yes: 1, no: 0})), - record(Event::Collective(CollectiveEvent::Voted{account: 2, proposal_hash: hash, voted: true, yes: 2, no: 0})), - record(Event::Collective(CollectiveEvent::Disapproved{proposal_hash: hash})), + record(Event::Collective(CollectiveEvent::Proposed { + account: 1, + proposal_index: 0, + proposal_hash: hash, + threshold: 2 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 1, + proposal_hash: hash, + voted: true, + yes: 1, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Voted { + account: 2, + proposal_hash: hash, + voted: true, + yes: 2, + no: 0 + })), + record(Event::Collective(CollectiveEvent::Disapproved { proposal_hash: hash })), ] ); }) diff --git a/frame/contracts/proc-macro/src/lib.rs b/frame/contracts/proc-macro/src/lib.rs index 302a0d01a93d9..e3bf0f1aac86f 100644 --- a/frame/contracts/proc-macro/src/lib.rs +++ b/frame/contracts/proc-macro/src/lib.rs @@ -55,7 +55,7 @@ fn derive_debug( name.span() => compile_error!("WeightDebug is only supported for structs."); } - .into() + .into(); }; #[cfg(feature = "full")] @@ -90,7 +90,7 @@ fn iterate_fields(data: &DataStruct, fmt: impl Fn(&Ident) -> TokenStream) -> Tok let recurse = fields.named.iter().filter_map(|f| { let name = f.ident.as_ref()?; if name.to_string().starts_with('_') { - return None + return None; } let value = fmt(name); let ret = quote_spanned! { f.span() => @@ -101,7 +101,7 @@ fn iterate_fields(data: &DataStruct, fmt: impl Fn(&Ident) -> TokenStream) -> Tok quote! { #( #recurse )* } - }, + } Fields::Unnamed(fields) => quote_spanned! { fields.span() => compile_error!("Unnamed fields are not supported") diff --git a/frame/contracts/src/benchmarking/code.rs b/frame/contracts/src/benchmarking/code.rs index b24005ec58699..8524add953c92 100644 --- a/frame/contracts/src/benchmarking/code.rs +++ b/frame/contracts/src/benchmarking/code.rs @@ -490,14 +490,14 @@ pub mod body { let current = *offset; *offset += *increment_by; vec![Instruction::I32Const(current as i32)] - }, + } DynInstr::RandomUnaligned(low, high) => { let unaligned = rng.gen_range(*low, *high) | 1; vec![Instruction::I32Const(unaligned as i32)] - }, + } DynInstr::RandomI32(low, high) => { vec![Instruction::I32Const(rng.gen_range(*low, *high))] - }, + } DynInstr::RandomI32Repeated(num) => (&mut rng) .sample_iter(Standard) .take(*num) @@ -510,19 +510,19 @@ pub mod body { .collect(), DynInstr::RandomGetLocal(low, high) => { vec![Instruction::GetLocal(rng.gen_range(*low, *high))] - }, + } DynInstr::RandomSetLocal(low, high) => { vec![Instruction::SetLocal(rng.gen_range(*low, *high))] - }, + } DynInstr::RandomTeeLocal(low, high) => { vec![Instruction::TeeLocal(rng.gen_range(*low, *high))] - }, + } DynInstr::RandomGetGlobal(low, high) => { vec![Instruction::GetGlobal(rng.gen_range(*low, *high))] - }, + } DynInstr::RandomSetGlobal(low, high) => { vec![Instruction::SetGlobal(rng.gen_range(*low, *high))] - }, + } }) .chain(sp_std::iter::once(Instruction::End)) .collect(); diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 7fa0b0b274449..dd78f2cbfa608 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -577,7 +577,7 @@ where let executable = E::from_storage(contract.code_hash, schedule, gas_meter)?; (dest, contract, executable, ExportedFunction::Call) - }, + } FrameArgs::Instantiate { sender, trie_seed, executable, salt } => { let account_id = >::contract_address(&sender, executable.code_hash(), &salt); @@ -588,7 +588,7 @@ where executable.code_hash().clone(), )?; (account_id, contract, executable, ExportedFunction::Constructor) - }, + } }; let frame = Frame { @@ -611,7 +611,7 @@ where gas_limit: Weight, ) -> Result { if self.frames.len() == T::CallStack::size() { - return Err(Error::::MaxCallDepthReached.into()) + return Err(Error::::MaxCallDepthReached.into()); } if CONTRACT_INFO_CAN_CHANGE { @@ -656,7 +656,7 @@ where // It is not allowed to terminate a contract inside its constructor. if let CachedContract::Terminated = frame.contract_info { - return Err(Error::::TerminatedInConstructor.into()) + return Err(Error::::TerminatedInConstructor.into()); } // Deposit an instantiation event. @@ -704,7 +704,7 @@ where prev.nested_meter.absorb_nested(frame.nested_meter); // Only gas counter changes are persisted in case of a failure. if !persist { - return + return; } if let CachedContract::Cached(contract) = frame.contract_info { // optimization: Predecessor is the same contract. @@ -713,7 +713,7 @@ where // trigger a rollback. if prev.account_id == *account_id { prev.contract_info = CachedContract::Cached(contract); - return + return; } // Predecessor is a different contract: We persist the info and invalidate the first @@ -738,7 +738,7 @@ where self.gas_meter.absorb_nested(mem::take(&mut self.first_frame.nested_meter)); // Only gas counter changes are persisted in case of a failure. if !persist { - return + return; } if let CachedContract::Cached(contract) = &self.first_frame.contract_info { >::insert(&self.first_frame.account_id, contract.clone()); @@ -763,19 +763,19 @@ where value: BalanceOf, ) -> DispatchResult { if value == 0u32.into() { - return Ok(()) + return Ok(()); } let existence_requirement = match (allow_death, sender_is_contract) { (true, _) => ExistenceRequirement::AllowDeath, (false, true) => { ensure!( - T::Currency::total_balance(from).saturating_sub(value) >= - Contracts::::subsistence_threshold(), + T::Currency::total_balance(from).saturating_sub(value) + >= Contracts::::subsistence_threshold(), Error::::BelowSubsistenceThreshold, ); ExistenceRequirement::KeepAlive - }, + } (false, false) => ExistenceRequirement::KeepAlive, }; @@ -795,7 +795,7 @@ where // we can error out early. This avoids executing the constructor in cases where // we already know that the contract has too little balance. if frame.entry_point == ExportedFunction::Constructor && value < subsistence_threshold { - return Err(>::NewContractNotFunded.into()) + return Err(>::NewContractNotFunded.into()); } Self::transfer(self.caller_is_origin(), false, self.caller(), &frame.account_id, value) @@ -879,7 +879,7 @@ where let try_call = || { if !self.allows_reentry(&to) { - return Err(>::ReentranceDenied.into()) + return Err(>::ReentranceDenied.into()); } // We ignore instantiate frames in our search for a cached contract. // Otherwise it would be possible to recursively call a contract from its own @@ -931,7 +931,7 @@ where fn terminate(&mut self, beneficiary: &AccountIdOf) -> Result<(), DispatchError> { if self.is_recursive() { - return Err(Error::::TerminatedWhileReentrant.into()) + return Err(Error::::TerminatedWhileReentrant.into()); } let frame = self.top_frame_mut(); let info = frame.terminate(); diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index 62b74b9b7b954..cb74779ec459e 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -729,9 +729,10 @@ where >::CodeTooLarge ); executable - }, - Code::Existing(hash) => - PrefabWasmModule::from_storage(hash, &schedule, &mut gas_meter)?, + } + Code::Existing(hash) => { + PrefabWasmModule::from_storage(hash, &schedule, &mut gas_meter)? + } }; ExecStack::>::run_instantiate( origin, diff --git a/frame/contracts/src/schedule.rs b/frame/contracts/src/schedule.rs index c14165b4c6aec..1c1a6754dbe8f 100644 --- a/frame/contracts/src/schedule.rs +++ b/frame/contracts/src/schedule.rs @@ -669,25 +669,25 @@ impl<'a, T: Config> rules::Rules for ScheduleRules<'a, T> { let weight = match *instruction { End | Unreachable | Return | Else => 0, I32Const(_) | I64Const(_) | Block(_) | Loop(_) | Nop | Drop => w.i64const, - I32Load(_, _) | - I32Load8S(_, _) | - I32Load8U(_, _) | - I32Load16S(_, _) | - I32Load16U(_, _) | - I64Load(_, _) | - I64Load8S(_, _) | - I64Load8U(_, _) | - I64Load16S(_, _) | - I64Load16U(_, _) | - I64Load32S(_, _) | - I64Load32U(_, _) => w.i64load, - I32Store(_, _) | - I32Store8(_, _) | - I32Store16(_, _) | - I64Store(_, _) | - I64Store8(_, _) | - I64Store16(_, _) | - I64Store32(_, _) => w.i64store, + I32Load(_, _) + | I32Load8S(_, _) + | I32Load8U(_, _) + | I32Load16S(_, _) + | I32Load16U(_, _) + | I64Load(_, _) + | I64Load8S(_, _) + | I64Load8U(_, _) + | I64Load16S(_, _) + | I64Load16U(_, _) + | I64Load32S(_, _) + | I64Load32U(_, _) => w.i64load, + I32Store(_, _) + | I32Store8(_, _) + | I32Store16(_, _) + | I64Store(_, _) + | I64Store8(_, _) + | I64Store16(_, _) + | I64Store32(_, _) => w.i64store, Select => w.select, If(_) => w.r#if, Br(_) => w.br, diff --git a/frame/contracts/src/storage.rs b/frame/contracts/src/storage.rs index 41db0796717e4..702f219fdda8a 100644 --- a/frame/contracts/src/storage.rs +++ b/frame/contracts/src/storage.rs @@ -115,7 +115,7 @@ where ch: CodeHash, ) -> Result, DispatchError> { if >::contains_key(account) { - return Err(Error::::DuplicateContract.into()) + return Err(Error::::DuplicateContract.into()); } let contract = ContractInfo:: { code_hash: ch, trie_id, _reserved: None }; @@ -140,10 +140,10 @@ where /// and weight limit. pub fn deletion_budget(queue_len: usize, weight_limit: Weight) -> (u64, u32) { let base_weight = T::WeightInfo::on_initialize(); - let weight_per_queue_item = T::WeightInfo::on_initialize_per_queue_item(1) - - T::WeightInfo::on_initialize_per_queue_item(0); - let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - - T::WeightInfo::on_initialize_per_trie_key(0); + let weight_per_queue_item = T::WeightInfo::on_initialize_per_queue_item(1) + - T::WeightInfo::on_initialize_per_queue_item(0); + let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) + - T::WeightInfo::on_initialize_per_trie_key(0); let decoding_weight = weight_per_queue_item.saturating_mul(queue_len as Weight); // `weight_per_key` being zero makes no sense and would constitute a failure to @@ -163,7 +163,7 @@ where pub fn process_deletion_queue_batch(weight_limit: Weight) -> Weight { let queue_len = >::decode_len().unwrap_or(0); if queue_len == 0 { - return 0 + return 0; } let (weight_per_key, mut remaining_key_budget) = @@ -173,7 +173,7 @@ where // proceeding. Too little weight for decoding might happen during runtime upgrades // which consume the whole block before the other `on_initialize` blocks are called. if remaining_key_budget == 0 { - return weight_limit + return weight_limit; } let mut queue = >::get(); @@ -189,7 +189,7 @@ where // noone waits for the trie to be deleted. queue.swap_remove(0); count - }, + } }; remaining_key_budget = remaining_key_budget.saturating_sub(keys_removed); } diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 310c1d4cb2dd9..b75bdd7f58d9f 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -162,7 +162,7 @@ impl ChainExtension for TestExtension { env.write(&input, false, None)?; TEST_EXTENSION.with(|e| e.borrow_mut().last_seen_buffer = input); Ok(RetVal::Converging(func_id)) - }, + } 1 => { let env = env.only_in(); TEST_EXTENSION.with(|e| { @@ -170,17 +170,17 @@ impl ChainExtension for TestExtension { (env.val0(), env.val1(), env.val2(), env.val3()) }); Ok(RetVal::Converging(func_id)) - }, + } 2 => { let mut env = env.buf_in_buf_out(); let weight = env.read(2)?[1].into(); env.charge_weight(weight)?; Ok(RetVal::Converging(func_id)) - }, + } 3 => Ok(RetVal::Diverging { flags: ReturnFlags::REVERT, data: vec![42, 99] }), _ => { panic!("Passed unknown func_id to test chain extension: {}", func_id); - }, + } } } diff --git a/frame/contracts/src/wasm/code_cache.rs b/frame/contracts/src/wasm/code_cache.rs index afb68d4d81179..b080aa5d2d8c1 100644 --- a/frame/contracts/src/wasm/code_cache.rs +++ b/frame/contracts/src/wasm/code_cache.rs @@ -60,7 +60,7 @@ where None => { *existing = Some(prefab_module); Contracts::::deposit_event(Event::CodeStored { code_hash }) - }, + } }); } @@ -230,8 +230,9 @@ where // the contract. match *self { Instrument(len) => T::WeightInfo::instrument(len / 1024), - Load(len) => - T::WeightInfo::code_load(len / 1024).saturating_sub(T::WeightInfo::code_load(0)), + Load(len) => { + T::WeightInfo::code_load(len / 1024).saturating_sub(T::WeightInfo::code_load(0)) + } UpdateRefcount(len) => T::WeightInfo::code_refcount(len / 1024) .saturating_sub(T::WeightInfo::code_refcount(0)), } diff --git a/frame/contracts/src/wasm/prepare.rs b/frame/contracts/src/wasm/prepare.rs index c766914f3d46e..77600ea026ffe 100644 --- a/frame/contracts/src/wasm/prepare.rs +++ b/frame/contracts/src/wasm/prepare.rs @@ -64,7 +64,7 @@ impl<'a, T: Config> ContractModule<'a, T> { /// we reject such a module. fn ensure_no_internal_memory(&self) -> Result<(), &'static str> { if self.module.memory_section().map_or(false, |ms| ms.entries().len() > 0) { - return Err("module declares internal memory") + return Err("module declares internal memory"); } Ok(()) } @@ -75,13 +75,13 @@ impl<'a, T: Config> ContractModule<'a, T> { // In Wasm MVP spec, there may be at most one table declared. Double check this // explicitly just in case the Wasm version changes. if table_section.entries().len() > 1 { - return Err("multiple tables declared") + return Err("multiple tables declared"); } if let Some(table_type) = table_section.entries().first() { // Check the table's initial size as there is no instruction or environment function // capable of growing the table. if table_type.limits().initial() > limit { - return Err("table exceeds maximum size allowed") + return Err("table exceeds maximum size allowed"); } } } @@ -93,13 +93,13 @@ impl<'a, T: Config> ContractModule<'a, T> { let code_section = if let Some(type_section) = self.module.code_section() { type_section } else { - return Ok(()) + return Ok(()); }; for instr in code_section.bodies().iter().flat_map(|body| body.code().elements()) { use self::elements::Instruction::BrTable; if let BrTable(table) = instr { if table.table.len() > limit as usize { - return Err("BrTable's immediate value is too big.") + return Err("BrTable's immediate value is too big."); } } } @@ -109,7 +109,7 @@ impl<'a, T: Config> ContractModule<'a, T> { fn ensure_global_variable_limit(&self, limit: u32) -> Result<(), &'static str> { if let Some(global_section) = self.module.global_section() { if global_section.entries().len() > limit as usize { - return Err("module declares too many globals") + return Err("module declares too many globals"); } } Ok(()) @@ -120,9 +120,10 @@ impl<'a, T: Config> ContractModule<'a, T> { if let Some(global_section) = self.module.global_section() { for global in global_section.entries() { match global.global_type().content_type() { - ValueType::F32 | ValueType::F64 => - return Err("use of floating point type in globals is forbidden"), - _ => {}, + ValueType::F32 | ValueType::F64 => { + return Err("use of floating point type in globals is forbidden") + } + _ => {} } } } @@ -131,9 +132,10 @@ impl<'a, T: Config> ContractModule<'a, T> { for func_body in code_section.bodies() { for local in func_body.locals() { match local.value_type() { - ValueType::F32 | ValueType::F64 => - return Err("use of floating point type in locals is forbidden"), - _ => {}, + ValueType::F32 | ValueType::F64 => { + return Err("use of floating point type in locals is forbidden") + } + _ => {} } } } @@ -146,14 +148,15 @@ impl<'a, T: Config> ContractModule<'a, T> { let return_type = func_type.results().get(0); for value_type in func_type.params().iter().chain(return_type) { match value_type { - ValueType::F32 | ValueType::F64 => + ValueType::F32 | ValueType::F64 => { return Err( "use of floating point type in function types is forbidden", - ), - _ => {}, + ) + } + _ => {} } } - }, + } } } } @@ -166,12 +169,12 @@ impl<'a, T: Config> ContractModule<'a, T> { let type_section = if let Some(type_section) = self.module.type_section() { type_section } else { - return Ok(()) + return Ok(()); }; for Type::Function(func) in type_section.types() { if func.params().len() > limit as usize { - return Err("Use of a function type with too many parameters.") + return Err("Use of a function type with too many parameters."); } } @@ -244,8 +247,8 @@ impl<'a, T: Config> ContractModule<'a, T> { Some(fn_idx) => fn_idx, None => { // Underflow here means fn_idx points to imported function which we don't allow! - return Err("entry point points to an imported function") - }, + return Err("entry point points to an imported function"); + } }; // Then check the signature. @@ -258,18 +261,18 @@ impl<'a, T: Config> ContractModule<'a, T> { let Type::Function(ref func_ty) = types .get(func_ty_idx as usize) .ok_or_else(|| "function has a non-existent type")?; - if !(func_ty.params().is_empty() && - (func_ty.results().is_empty() || func_ty.results() == [ValueType::I32])) + if !(func_ty.params().is_empty() + && (func_ty.results().is_empty() || func_ty.results() == [ValueType::I32])) { - return Err("entry point has wrong signature") + return Err("entry point has wrong signature"); } } if !deploy_found { - return Err("deploy function isn't exported") + return Err("deploy function isn't exported"); } if !call_found { - return Err("call function isn't exported") + return Err("call function isn't exported"); } Ok(()) @@ -300,33 +303,33 @@ impl<'a, T: Config> ContractModule<'a, T> { &External::Function(ref type_idx) => type_idx, &External::Memory(ref memory_type) => { if import.module() != IMPORT_MODULE_MEMORY { - return Err("Invalid module for imported memory") + return Err("Invalid module for imported memory"); } if import.field() != "memory" { - return Err("Memory import must have the field name 'memory'") + return Err("Memory import must have the field name 'memory'"); } if imported_mem_type.is_some() { - return Err("Multiple memory imports defined") + return Err("Multiple memory imports defined"); } imported_mem_type = Some(memory_type); - continue - }, + continue; + } }; let Type::Function(ref func_ty) = types .get(*type_idx as usize) .ok_or_else(|| "validation: import entry points to a non-existent type")?; - if !T::ChainExtension::enabled() && - import.field().as_bytes() == b"seal_call_chain_extension" + if !T::ChainExtension::enabled() + && import.field().as_bytes() == b"seal_call_chain_extension" { - return Err("module uses chain extensions but chain extensions are disabled") + return Err("module uses chain extensions but chain extensions are disabled"); } - if import_fn_banlist.iter().any(|f| import.field().as_bytes() == *f) || - !C::can_satisfy(import.module().as_bytes(), import.field().as_bytes(), func_ty) + if import_fn_banlist.iter().any(|f| import.field().as_bytes() == *f) + || !C::can_satisfy(import.module().as_bytes(), import.field().as_bytes(), func_ty) { - return Err("module imports a non-existent function") + return Err("module imports a non-existent function"); } } Ok(imported_mem_type) @@ -345,19 +348,21 @@ fn get_memory_limits( // Inspect the module to extract the initial and maximum page count. let limits = memory_type.limits(); match (limits.initial(), limits.maximum()) { - (initial, Some(maximum)) if initial > maximum => + (initial, Some(maximum)) if initial > maximum => { return Err( "Requested initial number of pages should not exceed the requested maximum", - ), - (_, Some(maximum)) if maximum > schedule.limits.memory_pages => - return Err("Maximum number of pages should not exceed the configured maximum."), + ) + } + (_, Some(maximum)) if maximum > schedule.limits.memory_pages => { + return Err("Maximum number of pages should not exceed the configured maximum.") + } (initial, Some(maximum)) => Ok((initial, maximum)), (_, None) => { // Maximum number of pages should be always declared. // This isn't a hard requirement and can be treated as a maximum set // to configured maximum. - return Err("Maximum number of pages should be always declared.") - }, + return Err("Maximum number of pages should be always declared."); + } } } else { // If none memory imported then just crate an empty placeholder. diff --git a/frame/contracts/src/wasm/runtime.rs b/frame/contracts/src/wasm/runtime.rs index 52b864bf18eac..fcf64ac78badd 100644 --- a/frame/contracts/src/wasm/runtime.rs +++ b/frame/contracts/src/wasm/runtime.rs @@ -244,14 +244,16 @@ impl RuntimeCosts { .saturating_add(s.deposit_event_per_topic.saturating_mul(num_topic.into())) .saturating_add(s.deposit_event_per_byte.saturating_mul(len.into())), DebugMessage => s.debug_message, - SetStorage(len) => - s.set_storage.saturating_add(s.set_storage_per_byte.saturating_mul(len.into())), + SetStorage(len) => { + s.set_storage.saturating_add(s.set_storage_per_byte.saturating_mul(len.into())) + } ClearStorage => s.clear_storage, GetStorageBase => s.get_storage, GetStorageCopyOut(len) => s.get_storage_per_byte.saturating_mul(len.into()), Transfer => s.transfer, - CallBase(len) => - s.call.saturating_add(s.call_per_input_byte.saturating_mul(len.into())), + CallBase(len) => { + s.call.saturating_add(s.call_per_input_byte.saturating_mul(len.into())) + } CallSurchargeTransfer => s.call_transfer_surcharge, CallCopyOut(len) => s.call_per_output_byte.saturating_mul(len.into()), InstantiateBase { input_data_len, salt_len } => s @@ -388,11 +390,12 @@ where let flags = ReturnFlags::from_bits(flags) .ok_or_else(|| "used reserved bit in return flags")?; Ok(ExecReturnValue { flags, data: Bytes(data) }) - }, - TrapReason::Termination => - Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Bytes(Vec::new()) }), + } + TrapReason::Termination => { + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Bytes(Vec::new()) }) + } TrapReason::SupervisorError(error) => Err(error)?, - } + }; } // Check the exact type of the error. @@ -407,8 +410,9 @@ where // a trap for now. Eventually, we might want to revisit this. Err(sp_sandbox::Error::Module) => Err("validation error")?, // Any other kind of a trap should result in a failure. - Err(sp_sandbox::Error::Execution) | Err(sp_sandbox::Error::OutOfBounds) => - Err(Error::::ContractTrapped)?, + Err(sp_sandbox::Error::Execution) | Err(sp_sandbox::Error::OutOfBounds) => { + Err(Error::::ContractTrapped)? + } } } @@ -539,7 +543,7 @@ where create_token: impl FnOnce(u32) -> Option, ) -> Result<(), DispatchError> { if allow_skip && out_ptr == u32::MAX { - return Ok(()) + return Ok(()); } let buf_len = buf.len() as u32; @@ -673,7 +677,7 @@ where return Err(TrapReason::Return(ReturnData { flags: return_value.flags.bits(), data: return_value.data.0, - })) + })); } } diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index cc08570ccda50..78f8a8559cf4a 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -508,39 +508,44 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A motion has been proposed by a public account. - Proposed{proposal_index: PropIndex, deposit: BalanceOf}, + Proposed { proposal_index: PropIndex, deposit: BalanceOf }, /// A public proposal has been tabled for referendum vote. - Tabled{proposal_index: PropIndex, deposit: BalanceOf, depositors: Vec}, + Tabled { proposal_index: PropIndex, deposit: BalanceOf, depositors: Vec }, /// An external proposal has been tabled. ExternalTabled, /// A referendum has begun. - Started{ref_index: ReferendumIndex, threshold: VoteThreshold}, + Started { ref_index: ReferendumIndex, threshold: VoteThreshold }, /// A proposal has been approved by referendum. - Passed{ref_index: ReferendumIndex}, + Passed { ref_index: ReferendumIndex }, /// A proposal has been rejected by referendum. - NotPassed{ref_index: ReferendumIndex}, + NotPassed { ref_index: ReferendumIndex }, /// A referendum has been cancelled. - Cancelled{ref_index: ReferendumIndex}, + Cancelled { ref_index: ReferendumIndex }, /// A proposal has been enacted. - Executed{ref_index: ReferendumIndex, result: DispatchResult}, + Executed { ref_index: ReferendumIndex, result: DispatchResult }, /// An account has delegated their vote to another account. - Delegated{who: T::AccountId, target: T::AccountId}, + Delegated { who: T::AccountId, target: T::AccountId }, /// An account has cancelled a previous delegation operation. - Undelegated{account: T::AccountId}, + Undelegated { account: T::AccountId }, /// An external proposal has been vetoed. - Vetoed{who: T::AccountId, proposal_hash: T::Hash, until: T::BlockNumber}, + Vetoed { who: T::AccountId, proposal_hash: T::Hash, until: T::BlockNumber }, /// A proposal's preimage was noted, and the deposit taken. - PreimageNoted{proposal_hash: T::Hash, who: T::AccountId, deposit: BalanceOf}, + PreimageNoted { proposal_hash: T::Hash, who: T::AccountId, deposit: BalanceOf }, /// A proposal preimage was removed and used (the deposit was returned). - PreimageUsed{proposal_hash: T::Hash, provider: T::AccountId, deposit: BalanceOf}, + PreimageUsed { proposal_hash: T::Hash, provider: T::AccountId, deposit: BalanceOf }, /// A proposal could not be executed because its preimage was invalid. - PreimageInvalid{proposal_hash: T::Hash, ref_index: ReferendumIndex}, + PreimageInvalid { proposal_hash: T::Hash, ref_index: ReferendumIndex }, /// A proposal could not be executed because its preimage was missing. - PreimageMissing{proposal_hash: T::Hash, ref_index: ReferendumIndex}, + PreimageMissing { proposal_hash: T::Hash, ref_index: ReferendumIndex }, /// A registered preimage was removed and the deposit collected by the reaper. - PreimageReaped{proposal_hash: T::Hash, provider: T::AccountId, deposit: BalanceOf, reaper: T::AccountId}, + PreimageReaped { + proposal_hash: T::Hash, + provider: T::AccountId, + deposit: BalanceOf, + reaper: T::AccountId, + }, /// A proposal_hash has been blacklisted permanently. - Blacklisted{proposal_hash: T::Hash}, + Blacklisted { proposal_hash: T::Hash }, } #[pallet::error] @@ -652,7 +657,7 @@ pub mod pallet { >::append((index, proposal_hash, who)); - Self::deposit_event(Event::::Proposed{proposal_index: index, deposit: value}); + Self::deposit_event(Event::::Proposed { proposal_index: index, deposit: value }); Ok(()) } @@ -877,7 +882,7 @@ pub mod pallet { let until = >::block_number() + T::CooloffPeriod::get(); >::insert(&proposal_hash, (until, existing_vetoers)); - Self::deposit_event(Event::::Vetoed{who, proposal_hash, until}); + Self::deposit_event(Event::::Vetoed { who, proposal_hash, until }); >::kill(); Ok(()) } @@ -1083,8 +1088,9 @@ pub mod pallet { let (provider, deposit, since, expiry) = >::get(&proposal_hash) .and_then(|m| match m { - PreimageStatus::Available { provider, deposit, since, expiry, .. } => - Some((provider, deposit, since, expiry)), + PreimageStatus::Available { provider, deposit, since, expiry, .. } => { + Some((provider, deposit, since, expiry)) + } _ => None, }) .ok_or(Error::::PreimageMissing)?; @@ -1099,7 +1105,12 @@ pub mod pallet { T::Currency::repatriate_reserved(&provider, &who, deposit, BalanceStatus::Free); debug_assert!(res.is_ok()); >::remove(&proposal_hash); - Self::deposit_event(Event::::PreimageReaped{proposal_hash, provider, deposit, reaper: who}); + Self::deposit_event(Event::::PreimageReaped { + proposal_hash, + provider, + deposit, + reaper: who, + }); Ok(()) } @@ -1244,7 +1255,7 @@ pub mod pallet { } } - Self::deposit_event(Event::::Blacklisted{proposal_hash}); + Self::deposit_event(Event::::Blacklisted { proposal_hash }); Ok(()) } @@ -1325,7 +1336,7 @@ impl Pallet { /// Remove a referendum. pub fn internal_cancel_referendum(ref_index: ReferendumIndex) { - Self::deposit_event(Event::::Cancelled{ref_index}); + Self::deposit_event(Event::::Cancelled { ref_index }); ReferendumInfoOf::::remove(ref_index); } @@ -1366,14 +1377,14 @@ impl Pallet { status.tally.reduce(approve, *delegations); } votes[i].1 = vote; - }, + } Err(i) => { ensure!( votes.len() as u32 <= T::MaxVotes::get(), Error::::MaxVotesReached ); votes.insert(i, (ref_index, vote)); - }, + } } // Shouldn't be possible to fail, but we handle it gracefully. status.tally.add(vote).ok_or(ArithmeticError::Overflow)?; @@ -1418,7 +1429,7 @@ impl Pallet { status.tally.reduce(approve, *delegations); } ReferendumInfoOf::::insert(ref_index, ReferendumInfo::Ongoing(status)); - }, + } Some(ReferendumInfo::Finished { end, approved }) => { if let Some((lock_periods, balance)) = votes[i].1.locked_if(approved) { let unlock_at = end + T::VoteLockingPeriod::get() * lock_periods.into(); @@ -1431,8 +1442,8 @@ impl Pallet { prior.accumulate(unlock_at, balance) } } - }, - None => {}, // Referendum was cancelled. + } + None => {} // Referendum was cancelled. } votes.remove(i); } @@ -1448,7 +1459,7 @@ impl Pallet { // We don't support second level delegating, so we don't need to do anything more. *delegations = delegations.saturating_add(amount); 1 - }, + } Voting::Direct { votes, delegations, .. } => { *delegations = delegations.saturating_add(amount); for &(ref_index, account_vote) in votes.iter() { @@ -1461,7 +1472,7 @@ impl Pallet { } } votes.len() as u32 - }, + } }) } @@ -1472,7 +1483,7 @@ impl Pallet { // We don't support second level delegating, so we don't need to do anything more. *delegations = delegations.saturating_sub(amount); 1 - }, + } Voting::Direct { votes, delegations, .. } => { *delegations = delegations.saturating_sub(amount); for &(ref_index, account_vote) in votes.iter() { @@ -1485,7 +1496,7 @@ impl Pallet { } } votes.len() as u32 - }, + } }) } @@ -1514,12 +1525,12 @@ impl Pallet { // remove any delegation votes to our current target. Self::reduce_upstream_delegation(&target, conviction.votes(balance)); voting.set_common(delegations, prior); - }, + } Voting::Direct { votes, delegations, prior } => { // here we just ensure that we're currently idling with no votes recorded. ensure!(votes.is_empty(), Error::::VotesExist); voting.set_common(delegations, prior); - }, + } } let votes = Self::increase_upstream_delegation(&target, conviction.votes(balance)); // Extend the lock to `balance` (rather than setting it) since we don't know what other @@ -1527,7 +1538,7 @@ impl Pallet { T::Currency::extend_lock(DEMOCRACY_ID, &who, balance, WithdrawReasons::TRANSFER); Ok(votes) })?; - Self::deposit_event(Event::::Delegated{who, target}); + Self::deposit_event(Event::::Delegated { who, target }); Ok(votes) } @@ -1549,11 +1560,11 @@ impl Pallet { voting.set_common(delegations, prior); Ok(votes) - }, + } Voting::Direct { .. } => Err(Error::::NotDelegating.into()), } })?; - Self::deposit_event(Event::::Undelegated{account: who}); + Self::deposit_event(Event::::Undelegated { account: who }); Ok(votes) } @@ -1584,7 +1595,7 @@ impl Pallet { ReferendumStatus { end, proposal_hash, threshold, delay, tally: Default::default() }; let item = ReferendumInfo::Ongoing(status); >::insert(ref_index, item); - Self::deposit_event(Event::::Started{ref_index, threshold}); + Self::deposit_event(Event::::Started { ref_index, threshold }); ref_index } @@ -1630,7 +1641,11 @@ impl Pallet { for d in &depositors { T::Currency::unreserve(d, deposit); } - Self::deposit_event(Event::::Tabled{proposal_index: prop_index, deposit, depositors}); + Self::deposit_event(Event::::Tabled { + proposal_index: prop_index, + deposit, + depositors, + }); Self::inject_referendum( now + T::VotingPeriod::get(), proposal, @@ -1650,22 +1665,25 @@ impl Pallet { if let Ok(proposal) = T::Proposal::decode(&mut &data[..]) { let err_amount = T::Currency::unreserve(&provider, deposit); debug_assert!(err_amount.is_zero()); - Self::deposit_event(Event::::PreimageUsed{proposal_hash, provider, deposit}); + Self::deposit_event(Event::::PreimageUsed { proposal_hash, provider, deposit }); let res = proposal .dispatch(frame_system::RawOrigin::Root.into()) .map(|_| ()) .map_err(|e| e.error); - Self::deposit_event(Event::::Executed{ref_index: index, result: res}); + Self::deposit_event(Event::::Executed { ref_index: index, result: res }); Ok(()) } else { T::Slash::on_unbalanced(T::Currency::slash_reserved(&provider, deposit).0); - Self::deposit_event(Event::::PreimageInvalid{proposal_hash, ref_index: index}); + Self::deposit_event(Event::::PreimageInvalid { + proposal_hash, + ref_index: index, + }); Err(Error::::PreimageInvalid.into()) } } else { - Self::deposit_event(Event::::PreimageMissing{proposal_hash, ref_index: index}); + Self::deposit_event(Event::::PreimageMissing { proposal_hash, ref_index: index }); Err(Error::::PreimageMissing.into()) } } @@ -1679,7 +1697,7 @@ impl Pallet { let approved = status.threshold.approved(status.tally, total_issuance); if approved { - Self::deposit_event(Event::::Passed{ref_index: index}); + Self::deposit_event(Event::::Passed { ref_index: index }); if status.delay.is_zero() { let _ = Self::do_enact_proposal(status.proposal_hash, index); } else { @@ -1688,8 +1706,9 @@ impl Pallet { Preimages::::mutate_exists( &status.proposal_hash, |maybe_pre| match *maybe_pre { - Some(PreimageStatus::Available { ref mut expiry, .. }) => - *expiry = Some(when), + Some(PreimageStatus::Available { ref mut expiry, .. }) => { + *expiry = Some(when) + } ref mut a => *a = Some(PreimageStatus::Missing(when)), }, ); @@ -1708,7 +1727,7 @@ impl Pallet { } } } else { - Self::deposit_event(Event::::NotPassed{ref_index: index}); + Self::deposit_event(Event::::NotPassed { ref_index: index }); } approved @@ -1803,7 +1822,7 @@ impl Pallet { _ => { sp_runtime::print("Failed to decode `PreimageStatus` variant"); Err(Error::::NotImminent.into()) - }, + } } } @@ -1831,8 +1850,8 @@ impl Pallet { Ok(0) => return Err(Error::::PreimageMissing.into()), _ => { sp_runtime::print("Failed to decode `PreimageStatus` variant"); - return Err(Error::::PreimageMissing.into()) - }, + return Err(Error::::PreimageMissing.into()); + } } // Decode the length of the vector. @@ -1865,7 +1884,7 @@ impl Pallet { }; >::insert(proposal_hash, a); - Self::deposit_event(Event::::PreimageNoted{proposal_hash, who, deposit}); + Self::deposit_event(Event::::PreimageNoted { proposal_hash, who, deposit }); Ok(()) } @@ -1891,7 +1910,7 @@ impl Pallet { }; >::insert(proposal_hash, a); - Self::deposit_event(Event::::PreimageNoted{proposal_hash, who, deposit: free}); + Self::deposit_event(Event::::PreimageNoted { proposal_hash, who, deposit: free }); Ok(()) } @@ -1910,6 +1929,6 @@ fn decode_compact_u32_at(key: &[u8]) -> Option { sp_runtime::print("Failed to decode compact u32 at:"); sp_runtime::print(key); None - }, + } } } diff --git a/frame/democracy/src/types.rs b/frame/democracy/src/types.rs index 2eb004ba61bc4..e6c117b6ca655 100644 --- a/frame/democracy/src/types.rs +++ b/frame/democracy/src/types.rs @@ -104,14 +104,14 @@ impl< true => self.ayes = self.ayes.checked_add(&votes)?, false => self.nays = self.nays.checked_add(&votes)?, } - }, + } AccountVote::Split { aye, nay } => { let aye = Conviction::None.votes(aye); let nay = Conviction::None.votes(nay); self.turnout = self.turnout.checked_add(&aye.capital)?.checked_add(&nay.capital)?; self.ayes = self.ayes.checked_add(&aye.votes)?; self.nays = self.nays.checked_add(&nay.votes)?; - }, + } } Some(()) } @@ -126,14 +126,14 @@ impl< true => self.ayes = self.ayes.checked_sub(&votes)?, false => self.nays = self.nays.checked_sub(&votes)?, } - }, + } AccountVote::Split { aye, nay } => { let aye = Conviction::None.votes(aye); let nay = Conviction::None.votes(nay); self.turnout = self.turnout.checked_sub(&aye.capital)?.checked_sub(&nay.capital)?; self.ayes = self.ayes.checked_sub(&aye.votes)?; self.nays = self.nays.checked_sub(&nay.votes)?; - }, + } } Some(()) } diff --git a/frame/democracy/src/vote.rs b/frame/democracy/src/vote.rs index 03ca020ca0949..29f5bd7e6038c 100644 --- a/frame/democracy/src/vote.rs +++ b/frame/democracy/src/vote.rs @@ -81,8 +81,9 @@ impl AccountVote { pub fn locked_if(self, approved: bool) -> Option<(u32, Balance)> { // winning side: can only be removed after the lock period ends. match self { - AccountVote::Standard { vote, balance } if vote.aye == approved => - Some((vote.conviction.lock_periods(), balance)), + AccountVote::Standard { vote, balance } if vote.aye == approved => { + Some((vote.conviction.lock_periods(), balance)) + } _ => None, } } @@ -181,8 +182,9 @@ impl Balance { match self { - Voting::Direct { votes, prior, .. } => - votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)), + Voting::Direct { votes, prior, .. } => { + votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)) + } Voting::Delegating { balance, .. } => *balance, } } diff --git a/frame/democracy/src/vote_threshold.rs b/frame/democracy/src/vote_threshold.rs index ad8bce290ed4f..cd230bf558c24 100644 --- a/frame/democracy/src/vote_threshold.rs +++ b/frame/democracy/src/vote_threshold.rs @@ -58,18 +58,18 @@ fn compare_rationals< let q1 = n1 / d1; let q2 = n2 / d2; if q1 < q2 { - return true + return true; } if q2 < q1 { - return false + return false; } let r1 = n1 % d1; let r2 = n2 % d2; if r2.is_zero() { - return false + return false; } if r1.is_zero() { - return true + return true; } n1 = d2; n2 = d1; @@ -93,13 +93,15 @@ impl< let sqrt_voters = tally.turnout.integer_sqrt(); let sqrt_electorate = electorate.integer_sqrt(); if sqrt_voters.is_zero() { - return false + return false; } match *self { - VoteThreshold::SuperMajorityApprove => - compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate), - VoteThreshold::SuperMajorityAgainst => - compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters), + VoteThreshold::SuperMajorityApprove => { + compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate) + } + VoteThreshold::SuperMajorityAgainst => { + compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters) + } VoteThreshold::SimpleMajority => tally.ayes > tally.nays, } } diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 76e9e2021077c..3c712c08c29d1 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -723,14 +723,14 @@ pub mod pallet { Ok(_) => { Self::on_initialize_open_signed(); T::WeightInfo::on_initialize_open_signed() - }, + } Err(why) => { // Not much we can do about this at this point. log!(warn, "failed to open signed phase due to {:?}", why); T::WeightInfo::on_initialize_nothing() - }, + } } - }, + } Phase::Signed | Phase::Off if remaining <= unsigned_deadline && remaining > Zero::zero() => { @@ -762,11 +762,11 @@ pub mod pallet { Ok(_) => { Self::on_initialize_open_unsigned(enabled, now); T::WeightInfo::on_initialize_open_unsigned() - }, + } Err(why) => { log!(warn, "failed to open unsigned phase due to {:?}", why); T::WeightInfo::on_initialize_nothing() - }, + } } } else { Self::on_initialize_open_unsigned(enabled, now); @@ -792,10 +792,10 @@ pub mod pallet { match lock.try_lock() { Ok(_guard) => { Self::do_synchronized_offchain_worker(now); - }, + } Err(deadline) => { log!(debug, "offchain worker lock not released, deadline is {:?}", deadline); - }, + } }; } @@ -886,7 +886,7 @@ pub mod pallet { log!(info, "queued unsigned solution with score {:?}", ready.score); let ejected_a_solution = >::exists(); >::put(ready); - Self::deposit_event(Event::SolutionStored{ + Self::deposit_event(Event::SolutionStored { election_compute: ElectionCompute::Unsigned, prev_ejected: ejected_a_solution, }); @@ -958,8 +958,8 @@ pub mod pallet { // ensure witness data is correct. ensure!( - num_signed_submissions >= - >::decode_len().unwrap_or_default() as u32, + num_signed_submissions + >= >::decode_len().unwrap_or_default() as u32, Error::::SignedInvalidWitness, ); @@ -1012,7 +1012,10 @@ pub mod pallet { } signed_submissions.put(); - Self::deposit_event(Event::SolutionStored{election_compute: ElectionCompute::Signed, prev_ejected: ejected_a_solution}); + Self::deposit_event(Event::SolutionStored { + election_compute: ElectionCompute::Signed, + prev_ejected: ejected_a_solution, + }); Ok(()) } } @@ -1026,18 +1029,18 @@ pub mod pallet { /// solution is unsigned, this means that it has also been processed. /// /// The `bool` is `true` when a previous solution was ejected to make room for this one. - SolutionStored{election_compute: ElectionCompute, prev_ejected: bool}, + SolutionStored { election_compute: ElectionCompute, prev_ejected: bool }, /// The election has been finalized, with `Some` of the given computation, or else if the /// election failed, `None`. - ElectionFinalized{election_compute: Option}, + ElectionFinalized { election_compute: Option }, /// An account has been rewarded for their signed submission being finalized. - Rewarded{account: ::AccountId, value: BalanceOf}, + Rewarded { account: ::AccountId, value: BalanceOf }, /// An account has been slashed for submitting an invalid signed submission. - Slashed{account: ::AccountId, value: BalanceOf}, + Slashed { account: ::AccountId, value: BalanceOf }, /// The signed phase of the given round has started. - SignedPhaseStarted{round: u32}, + SignedPhaseStarted { round: u32 }, /// The unsigned phase of the given round has started. - UnsignedPhaseStarted{round: u32}, + UnsignedPhaseStarted { round: u32 }, } /// Error of the pallet that can be returned in response to dispatches. @@ -1074,7 +1077,7 @@ pub mod pallet { if let Call::submit_unsigned { raw_solution, .. } = call { // Discard solution not coming from the local OCW. match source { - TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ }, + TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ } _ => return InvalidTransaction::Call.into(), } @@ -1229,15 +1232,15 @@ impl Pallet { Self::mine_check_save_submit() }); log!(debug, "initial offchain thread output: {:?}", initial_output); - }, + } Phase::Unsigned((true, opened)) if opened < now => { // Try and resubmit the cached solution, and recompute ONLY if it is not // feasible. let resubmit_output = Self::ensure_offchain_repeat_frequency(now) .and_then(|_| Self::restore_or_compute_then_maybe_submit()); log!(debug, "resubmit offchain thread output: {:?}", resubmit_output); - }, - _ => {}, + } + _ => {} } } @@ -1245,7 +1248,7 @@ impl Pallet { pub fn on_initialize_open_signed() { log!(info, "Starting signed phase round {}.", Self::round()); >::put(Phase::Signed); - Self::deposit_event(Event::SignedPhaseStarted{round: Self::round()}); + Self::deposit_event(Event::SignedPhaseStarted { round: Self::round() }); } /// Logic for [`>::on_initialize`] when unsigned phase is being opened. @@ -1253,7 +1256,7 @@ impl Pallet { let round = Self::round(); log!(info, "Starting unsigned phase round {} enabled {}.", round, enabled); >::put(Phase::Unsigned((enabled, now))); - Self::deposit_event(Event::UnsignedPhaseStarted{round}); + Self::deposit_event(Event::UnsignedPhaseStarted { round }); } /// Parts of [`create_snapshot`] that happen inside of this pallet. @@ -1307,7 +1310,7 @@ impl Pallet { // Defensive-only. if targets.len() > target_limit || voters.len() > voter_limit { debug_assert!(false, "Snapshot limit has not been respected."); - return Err(ElectionError::DataProvider("Snapshot too big for submission.")) + return Err(ElectionError::DataProvider("Snapshot too big for submission.")); } Ok((targets, voters, desired_targets)) @@ -1417,7 +1420,7 @@ impl Pallet { // Check that all of the targets are valid based on the snapshot. if assignment.distribution.iter().any(|(d, _)| !targets.contains(d)) { - return Err(FeasibilityError::InvalidVote) + return Err(FeasibilityError::InvalidVote); } Ok(()) }) @@ -1473,14 +1476,14 @@ impl Pallet { |ReadySolution { supports, compute, .. }| Ok((supports, compute)), ) .map(|(supports, compute)| { - Self::deposit_event(Event::ElectionFinalized{election_compute: Some(compute)}); + Self::deposit_event(Event::ElectionFinalized { election_compute: Some(compute) }); if Self::round() != 1 { log!(info, "Finalized election round with compute {:?}.", compute); } supports }) .map_err(|err| { - Self::deposit_event(Event::ElectionFinalized{election_compute: None}); + Self::deposit_event(Event::ElectionFinalized { election_compute: None }); if Self::round() != 1 { log!(warn, "Failed to finalize election round. reason {:?}", err); } @@ -1510,12 +1513,12 @@ impl ElectionProvider for Pallet { Self::weigh_supports(&supports); Self::rotate_round(); Ok(supports) - }, + } Err(why) => { log!(error, "Entering emergency mode: {:?}", why); >::put(Phase::Emergency); Err(why) - }, + } } } } @@ -1737,7 +1740,7 @@ mod tests { roll_to(15); assert_eq!(MultiPhase::current_phase(), Phase::Signed); - assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted{round: 1}]); + assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted { round: 1 }]); assert!(MultiPhase::snapshot().is_some()); assert_eq!(MultiPhase::round(), 1); @@ -1750,7 +1753,10 @@ mod tests { assert_eq!(MultiPhase::current_phase(), Phase::Unsigned((true, 25))); assert_eq!( multi_phase_events(), - vec![Event::SignedPhaseStarted{round: 1}, Event::UnsignedPhaseStarted{round: 1}], + vec![ + Event::SignedPhaseStarted { round: 1 }, + Event::UnsignedPhaseStarted { round: 1 } + ], ); assert!(MultiPhase::snapshot().is_some()); @@ -1861,7 +1867,7 @@ mod tests { assert_eq!(MultiPhase::current_phase(), Phase::Off); roll_to(15); - assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted{round: 1}]); + assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted { round: 1 }]); assert_eq!(MultiPhase::current_phase(), Phase::Signed); assert_eq!(MultiPhase::round(), 1); @@ -1873,8 +1879,8 @@ mod tests { assert_eq!( multi_phase_events(), vec![ - Event::SignedPhaseStarted{round: 1}, - Event::ElectionFinalized{election_compute: Some(ElectionCompute::Fallback)} + Event::SignedPhaseStarted { round: 1 }, + Event::ElectionFinalized { election_compute: Some(ElectionCompute::Fallback) } ], ); // All storage items must be cleared. @@ -1896,7 +1902,7 @@ mod tests { assert_eq!(MultiPhase::current_phase(), Phase::Off); roll_to(15); - assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted{round: 1}]); + assert_eq!(multi_phase_events(), vec![Event::SignedPhaseStarted { round: 1 }]); assert_eq!(MultiPhase::current_phase(), Phase::Signed); assert_eq!(MultiPhase::round(), 1); @@ -2061,9 +2067,9 @@ mod tests { }; let mut active = 1; - while weight_with(active) <= - ::BlockWeights::get().max_block || - active == all_voters + while weight_with(active) + <= ::BlockWeights::get().max_block + || active == all_voters { active += 1; } diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index 1a65316be1f10..5030ee5bcba49 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -426,7 +426,7 @@ impl ElectionDataProvider for StakingMock { let targets = Targets::get(); if maybe_max_len.map_or(false, |max_len| targets.len() > max_len) { - return Err("Targets too big") + return Err("Targets too big"); } Ok(targets) diff --git a/frame/election-provider-multi-phase/src/signed.rs b/frame/election-provider-multi-phase/src/signed.rs index 61215059c53a6..3ef929938b515 100644 --- a/frame/election-provider-multi-phase/src/signed.rs +++ b/frame/election-provider-multi-phase/src/signed.rs @@ -275,12 +275,12 @@ impl SignedSubmissions { self.indices .try_insert(submission.raw_solution.score, prev_idx) .expect("didn't change the map size; qed"); - return InsertResult::NotInserted - }, + return InsertResult::NotInserted; + } Ok(None) => { // successfully inserted into the set; no need to take out weakest member None - }, + } Err((insert_score, insert_idx)) => { // could not insert into the set because it is full. // note that we short-circuit return here in case the iteration produces `None`. @@ -294,11 +294,11 @@ impl SignedSubmissions { // if we haven't improved on the weakest score, don't change anything. if !is_score_better(insert_score, weakest_score, threshold) { - return InsertResult::NotInserted + return InsertResult::NotInserted; } self.swap_out_submission(weakest_score, Some((insert_score, insert_idx))) - }, + } }; // we've taken out the weakest, so update the storage map and the next index @@ -382,13 +382,13 @@ impl Pallet { weight = weight .saturating_add(T::WeightInfo::finalize_signed_phase_accept_solution()); - break - }, + break; + } Err(_) => { Self::finalize_signed_phase_reject_solution(&who, deposit); weight = weight .saturating_add(T::WeightInfo::finalize_signed_phase_reject_solution()); - }, + } } } diff --git a/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index 0ed9b5427b1ec..f5e2a3330526c 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/frame/election-provider-multi-phase/src/unsigned.rs @@ -108,15 +108,16 @@ fn save_solution(call: &Call) -> Result<(), MinerError> { let storage = StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL); match storage.mutate::<_, (), _>(|_| Ok(call.clone())) { Ok(_) => Ok(()), - Err(MutateStorageError::ConcurrentModification(_)) => - Err(MinerError::FailedToStoreSolution), + Err(MutateStorageError::ConcurrentModification(_)) => { + Err(MinerError::FailedToStoreSolution) + } Err(MutateStorageError::ValueFunctionFailed(_)) => { // this branch should be unreachable according to the definition of // `StorageValueRef::mutate`: that function should only ever `Err` if the closure we // pass it returns an error. however, for safety in case the definition changes, we do // not optimize the branch away or panic. Err(MinerError::FailedToStoreSolution) - }, + } } } @@ -179,7 +180,7 @@ impl Pallet { let call = Self::mine_checked_call()?; save_solution(&call)?; Ok(call) - }, + } MinerError::Feasibility(_) => { log!(trace, "wiping infeasible solution."); // kill the infeasible solution, hopefully in the next runs (whenever they @@ -187,11 +188,11 @@ impl Pallet { kill_ocw_solution::(); clear_offchain_repeat_frequency(); Err(error) - }, + } _ => { // nothing to do. Return the error as-is. Err(error) - }, + } } })?; @@ -443,7 +444,7 @@ impl Pallet { // not much we can do if assignments are already empty. if high == low { - return Ok(()) + return Ok(()); } while high - low > 1 { @@ -454,8 +455,8 @@ impl Pallet { high = test; } } - let maximum_allowed_voters = if low < assignments.len() && - encoded_size_of(&assignments[..low + 1])? <= max_allowed_length + let maximum_allowed_voters = if low < assignments.len() + && encoded_size_of(&assignments[..low + 1])? <= max_allowed_length { low + 1 } else { @@ -467,8 +468,8 @@ impl Pallet { encoded_size_of(&assignments[..maximum_allowed_voters]).unwrap() <= max_allowed_length ); debug_assert!(if maximum_allowed_voters < assignments.len() { - encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap() > - max_allowed_length + encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap() + > max_allowed_length } else { true }); @@ -498,7 +499,7 @@ impl Pallet { max_weight: Weight, ) -> u32 { if size.voters < 1 { - return size.voters + return size.voters; } let max_voters = size.voters.max(1); @@ -517,7 +518,7 @@ impl Pallet { Some(voters) if voters < max_voters => Ok(voters), _ => Err(()), } - }, + } Ordering::Greater => voters.checked_sub(step).ok_or(()), Ordering::Equal => Ok(voters), } @@ -532,7 +533,7 @@ impl Pallet { // proceed with the binary search Ok(next) if next != voters => { voters = next; - }, + } // we are out of bounds, break out of the loop. Err(()) => break, // we found the right value - early exit the function. @@ -578,16 +579,17 @@ impl Pallet { |maybe_head: Result, _>| { match maybe_head { Ok(Some(head)) if now < head => Err("fork."), - Ok(Some(head)) if now >= head && now <= head + threshold => - Err("recently executed."), + Ok(Some(head)) if now >= head && now <= head + threshold => { + Err("recently executed.") + } Ok(Some(head)) if now > head + threshold => { // we can run again now. Write the new head. Ok(now) - }, + } _ => { // value doesn't exists. Probably this node just booted up. Write, and run Ok(now) - }, + } } }, ); @@ -596,8 +598,9 @@ impl Pallet { // all good Ok(_) => Ok(()), // failed to write. - Err(MutateStorageError::ConcurrentModification(_)) => - Err(MinerError::Lock("failed to write to offchain db (concurrent modification).")), + Err(MutateStorageError::ConcurrentModification(_)) => { + Err(MinerError::Lock("failed to write to offchain db (concurrent modification).")) + } // fork etc. Err(MutateStorageError::ValueFunctionFailed(why)) => Err(MinerError::Lock(why)), } @@ -621,8 +624,8 @@ impl Pallet { // ensure correct number of winners. ensure!( - Self::desired_targets().unwrap_or_default() == - raw_solution.solution.unique_targets().len() as u32, + Self::desired_targets().unwrap_or_default() + == raw_solution.solution.unique_targets().len() as u32, Error::::PreDispatchWrongWinnerCount, ); diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 29bb5b60a3359..8d4e5d354b382 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -325,14 +325,14 @@ pub mod pallet { let to_reserve = new_deposit - old_deposit; T::Currency::reserve(&who, to_reserve) .map_err(|_| Error::::UnableToPayBond)?; - }, - Ordering::Equal => {}, + } + Ordering::Equal => {} Ordering::Less => { // Must unreserve a bit. let to_unreserve = old_deposit - new_deposit; let _remainder = T::Currency::unreserve(&who, to_unreserve); debug_assert!(_remainder.is_zero()); - }, + } }; // Amount to be locked up. @@ -425,8 +425,8 @@ pub mod pallet { Renouncing::Member => { let _ = Self::remove_and_replace_member(&who, false) .map_err(|_| Error::::InvalidRenouncing)?; - Self::deposit_event(Event::Renounced{candidate: who}); - }, + Self::deposit_event(Event::Renounced { candidate: who }); + } Renouncing::RunnerUp => { >::try_mutate::<_, Error, _>(|runners_up| { let index = runners_up @@ -437,10 +437,10 @@ pub mod pallet { let SeatHolder { deposit, .. } = runners_up.remove(index); let _remainder = T::Currency::unreserve(&who, deposit); debug_assert!(_remainder.is_zero()); - Self::deposit_event(Event::Renounced{candidate: who}); + Self::deposit_event(Event::Renounced { candidate: who }); Ok(()) })?; - }, + } Renouncing::Candidate(count) => { >::try_mutate::<_, Error, _>(|candidates| { ensure!(count >= candidates.len() as u32, Error::::InvalidWitnessData); @@ -450,10 +450,10 @@ pub mod pallet { let (_removed, deposit) = candidates.remove(index); let _remainder = T::Currency::unreserve(&who, deposit); debug_assert!(_remainder.is_zero()); - Self::deposit_event(Event::Renounced{candidate: who}); + Self::deposit_event(Event::Renounced { candidate: who }); Ok(()) })?; - }, + } }; Ok(None.into()) } @@ -491,12 +491,12 @@ pub mod pallet { return Err(Error::::InvalidReplacement.with_weight( // refund. The weight value comes from a benchmark which is special to this. T::WeightInfo::remove_member_wrong_refund(), - )) + )); } let had_replacement = Self::remove_and_replace_member(&who, true)?; debug_assert_eq!(has_replacement, had_replacement); - Self::deposit_event(Event::MemberKicked{member: who.clone()}); + Self::deposit_event(Event::MemberKicked { member: who.clone() }); if !had_replacement { Self::do_phragmen(); @@ -539,7 +539,7 @@ pub mod pallet { /// for this purpose. A `NewTerm(\[\])` indicates that some candidates got their bond /// slashed and none were elected, whilst `EmptyTerm` means that no candidates existed to /// begin with. - NewTerm{new_members: Vec<(::AccountId, BalanceOf)>}, + NewTerm { new_members: Vec<(::AccountId, BalanceOf)> }, /// No (or not enough) candidates existed for this round. This is different from /// `NewTerm(\[\])`. See the description of `NewTerm`. EmptyTerm, @@ -547,16 +547,19 @@ pub mod pallet { ElectionError, /// A member has been removed. This should always be followed by either `NewTerm` or /// `EmptyTerm`. - MemberKicked{member: ::AccountId}, + MemberKicked { member: ::AccountId }, /// Someone has renounced their candidacy. - Renounced{candidate: ::AccountId}, + Renounced { candidate: ::AccountId }, /// A candidate was slashed by amount due to failing to obtain a seat as member or /// runner-up. /// /// Note that old members and runners-up are also candidates. - CandidateSlashed{candidate: ::AccountId, amount: BalanceOf}, + CandidateSlashed { candidate: ::AccountId, amount: BalanceOf }, /// A seat holder was slashed by amount by being forcefully removed from the set. - SeatHolderSlashed{seat_holder: ::AccountId, amount: BalanceOf}, + SeatHolderSlashed { + seat_holder: ::AccountId, + amount: BalanceOf, + }, } #[deprecated(note = "use `Event` instead")] @@ -677,7 +680,7 @@ pub mod pallet { match members.binary_search_by(|m| m.who.cmp(member)) { Ok(_) => { panic!("Duplicate member in elections-phragmen genesis: {}", member) - }, + } Err(pos) => members.insert( pos, SeatHolder { @@ -748,7 +751,10 @@ impl Pallet { let (imbalance, _remainder) = T::Currency::slash_reserved(who, removed.deposit); debug_assert!(_remainder.is_zero()); T::LoserCandidate::on_unbalanced(imbalance); - Self::deposit_event(Event::SeatHolderSlashed{seat_holder: who.clone(), amount: removed.deposit}); + Self::deposit_event(Event::SeatHolderSlashed { + seat_holder: who.clone(), + amount: removed.deposit, + }); } else { T::Currency::unreserve(who, removed.deposit); } @@ -784,7 +790,7 @@ impl Pallet { &remaining_member_ids_sorted[..], ); true - }, + } None => { T::ChangeMembers::change_members_sorted( &[], @@ -792,7 +798,7 @@ impl Pallet { &remaining_member_ids_sorted[..], ); false - }, + } }; // if there was a prime before and they are not the one being removed, then set them @@ -883,7 +889,7 @@ impl Pallet { if candidates_and_deposit.len().is_zero() { Self::deposit_event(Event::EmptyTerm); - return T::DbWeight::get().reads(5) + return T::DbWeight::get().reads(5); } // All of the new winners that come out of phragmen will thus have a deposit recorded. @@ -996,12 +1002,15 @@ impl Pallet { // All candidates/members/runners-up who are no longer retaining a position as a // seat holder will lose their bond. candidates_and_deposit.iter().for_each(|(c, d)| { - if new_members_ids_sorted.binary_search(c).is_err() && - new_runners_up_ids_sorted.binary_search(c).is_err() + if new_members_ids_sorted.binary_search(c).is_err() + && new_runners_up_ids_sorted.binary_search(c).is_err() { let (imbalance, _) = T::Currency::slash_reserved(c, *d); T::LoserCandidate::on_unbalanced(imbalance); - Self::deposit_event(Event::CandidateSlashed{candidate: c.clone(), amount: *d}); + Self::deposit_event(Event::CandidateSlashed { + candidate: c.clone(), + amount: *d, + }); } }); @@ -1041,7 +1050,7 @@ impl Pallet { // clean candidates. >::kill(); - Self::deposit_event(Event::NewTerm{new_members: new_members_sorted_by_id}); + Self::deposit_event(Event::NewTerm { new_members: new_members_sorted_by_id }); >::mutate(|v| *v += 1); }) .map_err(|e| { @@ -2147,10 +2156,9 @@ mod tests { System::set_block_number(5); Elections::on_initialize(System::block_number()); - System::assert_last_event(Event::Elections(super::Event::NewTerm{new_members: vec![ - (4, 40), - (5, 50), - ]})); + System::assert_last_event(Event::Elections(super::Event::NewTerm { + new_members: vec![(4, 40), (5, 50)], + })); assert_eq!(members_and_stake(), vec![(4, 40), (5, 50)]); assert_eq!(runners_up_and_stake(), vec![]); @@ -2161,7 +2169,9 @@ mod tests { System::set_block_number(10); Elections::on_initialize(System::block_number()); - System::assert_last_event(Event::Elections(super::Event::NewTerm{new_members: vec![]})); + System::assert_last_event(Event::Elections(super::Event::NewTerm { + new_members: vec![], + })); // outgoing have lost their bond. assert_eq!(balances(&4), (37, 0)); @@ -2231,7 +2241,9 @@ mod tests { assert_eq!(Elections::election_rounds(), 1); assert!(members_ids().is_empty()); - System::assert_last_event(Event::Elections(super::Event::NewTerm{new_members: vec![]})); + System::assert_last_event(Event::Elections(super::Event::NewTerm { + new_members: vec![], + })); }); } @@ -2583,10 +2595,9 @@ mod tests { // 5 is an outgoing loser. will also get slashed. assert_eq!(balances(&5), (45, 2)); - System::assert_has_event(Event::Elections(super::Event::NewTerm{new_members: vec![ - (4, 40), - (5, 50), - ]})); + System::assert_has_event(Event::Elections(super::Event::NewTerm { + new_members: vec![(4, 40), (5, 50)], + })); }) } diff --git a/frame/elections-phragmen/src/migrations/v4.rs b/frame/elections-phragmen/src/migrations/v4.rs index 9acc1297294d9..e52f793ee1ef2 100644 --- a/frame/elections-phragmen/src/migrations/v4.rs +++ b/frame/elections-phragmen/src/migrations/v4.rs @@ -38,7 +38,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { target: "runtime::elections-phragmen", "New pallet name is equal to the old prefix. No migration needs to be done.", ); - return 0 + return 0; } let storage_version = StorageVersion::get::>(); log::info!( diff --git a/frame/elections/src/lib.rs b/frame/elections/src/lib.rs index d58caa8b21c6e..4a7f37e554f4a 100644 --- a/frame/elections/src/lib.rs +++ b/frame/elections/src/lib.rs @@ -466,13 +466,13 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Reaped - VoterReaped{voter: T::AccountId, reaper: T::AccountId}, + VoterReaped { voter: T::AccountId, reaper: T::AccountId }, /// Slashed - BadReaperSlashed{reaper: T::AccountId}, + BadReaperSlashed { reaper: T::AccountId }, /// A tally (for approval votes of seats) has started. - TallyStarted{seats: u32}, + TallyStarted { seats: u32 }, /// A tally (for approval votes of seat(s)) has ended (with one or more new members). - TallyFinalized{incoming: Vec, outgoing: Vec}, + TallyFinalized { incoming: Vec, outgoing: Vec }, } #[pallet::call] @@ -589,11 +589,11 @@ pub mod pallet { T::VotingBond::get(), BalanceStatus::Free, )?; - Self::deposit_event(Event::::VoterReaped{voter: who, reaper: reporter}); + Self::deposit_event(Event::::VoterReaped { voter: who, reaper: reporter }); } else { let imbalance = T::Currency::slash_reserved(&reporter, T::VotingBond::get()).0; T::BadReaper::on_unbalanced(imbalance); - Self::deposit_event(Event::::BadReaperSlashed{reaper: reporter}); + Self::deposit_event(Event::::BadReaperSlashed { reaper: reporter }); } Ok(()) } @@ -657,8 +657,8 @@ pub mod pallet { let count = Self::candidate_count() as usize; let candidates = Self::candidates(); ensure!( - (slot == count && count == candidates.len()) || - (slot < candidates.len() && candidates[slot] == T::AccountId::default()), + (slot == count && count == candidates.len()) + || (slot < candidates.len() && candidates[slot] == T::AccountId::default()), Error::::InvalidCandidateSlot, ); // NOTE: This must be last as it has side-effects. @@ -732,7 +732,7 @@ pub mod pallet { } else { None } - }, + } _ => None, }) .fold(Zero::zero(), |acc, n| acc + n); @@ -850,14 +850,13 @@ impl Pallet { None } else { let c = Self::members(); - let (next_possible, count, coming) = if let Some((tally_end, comers, leavers)) = - Self::next_finalize() - { - // if there's a tally in progress, then next tally can begin immediately afterwards - (tally_end, c.len() - leavers.len() + comers as usize, comers) - } else { - (>::block_number(), c.len(), 0) - }; + let (next_possible, count, coming) = + if let Some((tally_end, comers, leavers)) = Self::next_finalize() { + // if there's a tally in progress, then next tally can begin immediately afterwards + (tally_end, c.len() - leavers.len() + comers as usize, comers) + } else { + (>::block_number(), c.len(), 0) + }; if count < desired_seats as usize { Some(next_possible) } else { @@ -952,7 +951,7 @@ impl Pallet { CellStatus::Hole => { // requested cell was a valid hole. >::mutate(set_index, |set| set[vec_index] = Some(who.clone())); - }, + } CellStatus::Head | CellStatus::Occupied => { // Either occupied or out-of-range. let next = Self::next_nonfull_voter_set(); @@ -974,7 +973,7 @@ impl Pallet { NextVoterSet::::put(next + 1); } >::append(next, Some(who.clone())); - }, + } } T::Currency::reserve(&who, T::VotingBond::get())?; @@ -1023,7 +1022,7 @@ impl Pallet { leaderboard_size ]); - Self::deposit_event(Event::::TallyStarted{seats: empty_seats as u32}); + Self::deposit_event(Event::::TallyStarted { seats: empty_seats as u32 }); } } @@ -1117,7 +1116,7 @@ impl Pallet { new_candidates.truncate(last_index + 1); } - Self::deposit_event(Event::::TallyFinalized{incoming, outgoing}); + Self::deposit_event(Event::::TallyFinalized { incoming, outgoing }); >::put(new_candidates); CandidateCount::::put(count); @@ -1144,7 +1143,7 @@ impl Pallet { loop { let next_set = >::get(index); if next_set.is_empty() { - break + break; } else { index += 1; all.extend(next_set); @@ -1226,7 +1225,7 @@ impl Pallet { pub fn bool_to_flag(x: Vec) -> Vec { let mut result: Vec = Vec::with_capacity(x.len() / APPROVAL_FLAG_LEN); if x.is_empty() { - return result + return result; } result.push(0); let mut index = 0; @@ -1236,7 +1235,7 @@ impl Pallet { result[index] += (if x[counter] { 1 } else { 0 }) << shl_index; counter += 1; if counter > x.len() - 1 { - break + break; } if counter % APPROVAL_FLAG_LEN == 0 { result.push(0); @@ -1250,7 +1249,7 @@ impl Pallet { pub fn flag_to_bool(chunk: Vec) -> Vec { let mut result = Vec::with_capacity(chunk.len()); if chunk.is_empty() { - return vec![] + return vec![]; } chunk .into_iter() @@ -1275,7 +1274,7 @@ impl Pallet { loop { let chunk = Self::approvals_of((who.clone(), index)); if chunk.is_empty() { - break + break; } all.extend(Self::flag_to_bool(chunk)); index += 1; @@ -1292,7 +1291,7 @@ impl Pallet { >::remove((who.clone(), index)); index += 1; } else { - break + break; } } } @@ -1310,7 +1309,7 @@ impl Pallet { fn get_offset(stake: BalanceOf, t: VoteIndex) -> BalanceOf { let decay_ratio: BalanceOf = T::DecayRatio::get().into(); if t > 150 { - return stake * decay_ratio + return stake * decay_ratio; } let mut offset = stake; let mut r = Zero::zero(); diff --git a/frame/elections/src/tests.rs b/frame/elections/src/tests.rs index 0df84c6d79baf..f4b54cdb094b9 100644 --- a/frame/elections/src/tests.rs +++ b/frame/elections/src/tests.rs @@ -966,7 +966,7 @@ fn election_seats_should_be_released() { assert_ok!(Elections::end_block(System::block_number())); if Elections::members().len() == 0 { free_block = current; - break + break; } } // 11 + 2 which is the next voting period. diff --git a/frame/example-offchain-worker/src/lib.rs b/frame/example-offchain-worker/src/lib.rs index 54f1a097bb003..f93493e0d185b 100644 --- a/frame/example-offchain-worker/src/lib.rs +++ b/frame/example-offchain-worker/src/lib.rs @@ -195,10 +195,12 @@ pub mod pallet { let should_send = Self::choose_transaction_type(block_number); let res = match should_send { TransactionType::Signed => Self::fetch_price_and_send_signed(), - TransactionType::UnsignedForAny => - Self::fetch_price_and_send_unsigned_for_any_account(block_number), - TransactionType::UnsignedForAll => - Self::fetch_price_and_send_unsigned_for_all_accounts(block_number), + TransactionType::UnsignedForAny => { + Self::fetch_price_and_send_unsigned_for_any_account(block_number) + } + TransactionType::UnsignedForAll => { + Self::fetch_price_and_send_unsigned_for_all_accounts(block_number) + } TransactionType::Raw => Self::fetch_price_and_send_raw_unsigned(block_number), TransactionType::None => Ok(()), }; @@ -288,7 +290,7 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Event generated when new price is accepted to contribute to the average. - NewPrice{price: u32, who: T::AccountId}, + NewPrice { price: u32, who: T::AccountId }, } #[pallet::validate_unsigned] @@ -310,7 +312,7 @@ pub mod pallet { let signature_valid = SignedPayload::::verify::(payload, signature.clone()); if !signature_valid { - return InvalidTransaction::BadProof.into() + return InvalidTransaction::BadProof.into(); } Self::validate_transaction_parameters(&payload.block_number, &payload.price) } else if let Call::submit_price_unsigned { block_number, price: new_price } = call { @@ -387,8 +389,9 @@ impl Pallet { match last_send { // If we already have a value in storage and the block number is recent enough // we avoid sending another transaction at this time. - Ok(Some(block)) if block_number < block + T::GracePeriod::get() => - Err(RECENTLY_SENT), + Ok(Some(block)) if block_number < block + T::GracePeriod::get() => { + Err(RECENTLY_SENT) + } // In every other case we attempt to acquire the lock and send a transaction. _ => Ok(block_number), } @@ -421,7 +424,7 @@ impl Pallet { } else { TransactionType::Raw } - }, + } // We are in the grace period, we should not send a transaction this time. Err(MutateStorageError::ValueFunctionFailed(RECENTLY_SENT)) => TransactionType::None, // We wanted to send a transaction, but failed to write the block number (acquire a @@ -439,7 +442,7 @@ impl Pallet { if !signer.can_sign() { return Err( "No local accounts available. Consider adding one via `author_insertKey` RPC.", - )? + )?; } // Make an external HTTP request to fetch the current price. // Note this call will block until response is received. @@ -472,7 +475,7 @@ impl Pallet { // anyway. let next_unsigned_at = >::get(); if next_unsigned_at > block_number { - return Err("Too early to send unsigned transaction") + return Err("Too early to send unsigned transaction"); } // Make an external HTTP request to fetch the current price. @@ -506,7 +509,7 @@ impl Pallet { // anyway. let next_unsigned_at = >::get(); if next_unsigned_at > block_number { - return Err("Too early to send unsigned transaction") + return Err("Too early to send unsigned transaction"); } // Make an external HTTP request to fetch the current price. @@ -536,7 +539,7 @@ impl Pallet { // anyway. let next_unsigned_at = >::get(); if next_unsigned_at > block_number { - return Err("Too early to send unsigned transaction") + return Err("Too early to send unsigned transaction"); } // Make an external HTTP request to fetch the current price. @@ -554,7 +557,7 @@ impl Pallet { ); for (_account_id, result) in transaction_results.into_iter() { if result.is_err() { - return Err("Unable to submit transaction") + return Err("Unable to submit transaction"); } } @@ -590,7 +593,7 @@ impl Pallet { // Let's check the status code before we proceed to reading the response. if response.code != 200 { log::warn!("Unexpected status code: {}", response.code); - return Err(http::Error::Unknown) + return Err(http::Error::Unknown); } // Next we want to fully read the response body and collect it to a vector of bytes. @@ -609,7 +612,7 @@ impl Pallet { None => { log::warn!("Unable to extract price from the response: {:?}", body_str); Err(http::Error::Unknown) - }, + } }?; log::warn!("Got price: {} cents", price); @@ -629,7 +632,7 @@ impl Pallet { JsonValue::Number(number) => number, _ => return None, } - }, + } _ => return None, }; @@ -654,7 +657,7 @@ impl Pallet { .expect("The average is not empty, because it was just mutated; qed"); log::info!("Current average price is: {}", average); // here we are raising the NewPrice event - Self::deposit_event(Event::NewPrice{price, who}); + Self::deposit_event(Event::NewPrice { price, who }); } /// Calculate current average price. @@ -674,12 +677,12 @@ impl Pallet { // Now let's check if the transaction has any chance to succeed. let next_unsigned_at = >::get(); if &next_unsigned_at > block_number { - return InvalidTransaction::Stale.into() + return InvalidTransaction::Stale.into(); } // Let's make sure to reject transactions from the future. let current_block = >::block_number(); if ¤t_block < block_number { - return InvalidTransaction::Future.into() + return InvalidTransaction::Future.into(); } // We prioritize transactions that are more far away from current average. diff --git a/frame/example-parallel/src/lib.rs b/frame/example-parallel/src/lib.rs index c86cac4295684..676f52578c795 100644 --- a/frame/example-parallel/src/lib.rs +++ b/frame/example-parallel/src/lib.rs @@ -111,7 +111,7 @@ impl EnlistedParticipant { Ok(signature) => { let public = sp_core::sr25519::Public::from_slice(self.account.as_ref()); signature.verify(event_id, &public) - }, + } _ => false, } } @@ -125,7 +125,7 @@ fn validate_participants_parallel(event_id: &[u8], participants: &[EnlistedParti for participant in participants { if !participant.verify(&event_id) { - return false.encode() + return false.encode(); } } true.encode() @@ -141,7 +141,7 @@ fn validate_participants_parallel(event_id: &[u8], participants: &[EnlistedParti for participant in &participants[participants.len() / 2 + 1..] { if !participant.verify(event_id) { result = false; - break + break; } } diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index ec09930f676ef..0b10c9851c316 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -523,7 +523,7 @@ pub mod pallet { }); // Let's deposit an event to let the outside world know this happened. - Self::deposit_event(Event::AccumulateDummy{balance: increase_by}); + Self::deposit_event(Event::AccumulateDummy { balance: increase_by }); // All good, no refund. Ok(()) @@ -555,7 +555,7 @@ pub mod pallet { // Put the new value into storage. >::put(new_value); - Self::deposit_event(Event::SetDummy{balance: new_value}); + Self::deposit_event(Event::SetDummy { balance: new_value }); // All good, no refund. Ok(()) @@ -572,9 +572,16 @@ pub mod pallet { pub enum Event { // Just a normal `enum`, here's a dummy event to ensure it compiles. /// Dummy event, just here so there's a generic type that's used. - AccumulateDummy{balance: BalanceOf}, - SetDummy{balance: BalanceOf}, - SetBar{account: T::AccountId, balance: BalanceOf}, + AccumulateDummy { + balance: BalanceOf, + }, + SetDummy { + balance: BalanceOf, + }, + SetBar { + account: T::AccountId, + balance: BalanceOf, + }, } // pallet::storage attributes allow for type-safe usage of the Substrate storage database, @@ -731,7 +738,7 @@ where ) -> TransactionValidity { // if the transaction is too big, just drop it. if len > 200 { - return InvalidTransaction::ExhaustsResources.into() + return InvalidTransaction::ExhaustsResources.into(); } // check for `set_dummy` @@ -742,7 +749,7 @@ where let mut valid_tx = ValidTransaction::default(); valid_tx.priority = Bounded::max_value(); Ok(valid_tx) - }, + } _ => Ok(Default::default()), } } diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index b1bdf357ec07d..d5569d3af3081 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -345,9 +345,9 @@ where // Check that `parent_hash` is correct. let n = header.number().clone(); assert!( - n > System::BlockNumber::zero() && - >::block_hash(n - System::BlockNumber::one()) == - *header.parent_hash(), + n > System::BlockNumber::zero() + && >::block_hash(n - System::BlockNumber::one()) + == *header.parent_hash(), "Parent hash should be valid.", ); @@ -878,8 +878,8 @@ mod tests { .assimilate_storage(&mut t) .unwrap(); let xt = TestXt::new(call_transfer(2, 69), sign_extra(1, 0, 0)); - let weight = xt.get_dispatch_info().weight + - ::BlockWeights::get() + let weight = xt.get_dispatch_info().weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; let fee: Balance = @@ -1078,8 +1078,8 @@ mod tests { assert!(Executive::apply_extrinsic(x2.clone()).unwrap().is_ok()); // default weight for `TestXt` == encoded length. - let extrinsic_weight = len as Weight + - ::BlockWeights::get() + let extrinsic_weight = len as Weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; assert_eq!( @@ -1150,8 +1150,8 @@ mod tests { Call::System(SystemCall::remark { remark: vec![1u8] }), sign_extra(1, 0, 0), ); - let weight = xt.get_dispatch_info().weight + - ::BlockWeights::get() + let weight = xt.get_dispatch_info().weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; let fee: Balance = @@ -1374,11 +1374,12 @@ mod tests { // Weights are recorded correctly assert_eq!( frame_system::Pallet::::block_weight().total(), - frame_system_upgrade_weight + - custom_runtime_upgrade_weight + - runtime_upgrade_weight + - frame_system_on_initialize_weight + - on_initialize_weight + base_block_weight, + frame_system_upgrade_weight + + custom_runtime_upgrade_weight + + runtime_upgrade_weight + + frame_system_on_initialize_weight + + on_initialize_weight + + base_block_weight, ); }); } diff --git a/frame/gilt/src/lib.rs b/frame/gilt/src/lib.rs index bf932a06b996d..41b2e7356f4a2 100644 --- a/frame/gilt/src/lib.rs +++ b/frame/gilt/src/lib.rs @@ -273,13 +273,23 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A bid was successfully placed. - BidPlaced{who: T::AccountId, amount: BalanceOf, duration: u32}, + BidPlaced { who: T::AccountId, amount: BalanceOf, duration: u32 }, /// A bid was successfully removed (before being accepted as a gilt). - BidRetracted{who: T::AccountId, amount: BalanceOf, duration: u32}, + BidRetracted { who: T::AccountId, amount: BalanceOf, duration: u32 }, /// A bid was accepted as a gilt. The balance may not be released until expiry. - GiltIssued{index: ActiveIndex, expiry: T::BlockNumber, who: T::AccountId, amount: BalanceOf}, + GiltIssued { + index: ActiveIndex, + expiry: T::BlockNumber, + who: T::AccountId, + amount: BalanceOf, + }, /// An expired gilt has been thawed. - GiltThawed{index: ActiveIndex, who: T::AccountId, original_amount: BalanceOf, additional_amount: BalanceOf}, + GiltThawed { + index: ActiveIndex, + who: T::AccountId, + original_amount: BalanceOf, + additional_amount: BalanceOf, + }, } #[pallet::error] @@ -373,7 +383,7 @@ pub mod pallet { qs[queue_index].0 += net.0; qs[queue_index].1 = qs[queue_index].1.saturating_add(net.1); }); - Self::deposit_event(Event::BidPlaced{who: who.clone(), amount, duration}); + Self::deposit_event(Event::BidPlaced { who: who.clone(), amount, duration }); Ok(().into()) } @@ -411,7 +421,7 @@ pub mod pallet { }); T::Currency::unreserve(&bid.who, bid.amount); - Self::deposit_event(Event::BidRetracted{who: bid.who, amount: bid.amount, duration}); + Self::deposit_event(Event::BidRetracted { who: bid.who, amount: bid.amount, duration }); Ok(().into()) } @@ -490,7 +500,12 @@ pub mod pallet { debug_assert!(err_amt.is_zero()); } - let e = Event::GiltThawed{index, who: gilt.who, original_amount: gilt.amount, additional_amount: gilt_value}; + let e = Event::GiltThawed { + index, + who: gilt.who, + original_amount: gilt.amount, + additional_amount: gilt_value, + }; Self::deposit_event(e); }); @@ -567,7 +582,7 @@ pub mod pallet { QueueTotals::::mutate(|qs| { for duration in (1..=T::QueueCount::get()).rev() { if qs[duration as usize - 1].0 == 0 { - continue + continue; } let queue_index = duration as usize - 1; let expiry = @@ -600,7 +615,8 @@ pub mod pallet { totals.frozen += bid.amount; totals.proportion = totals.proportion.saturating_add(proportion); totals.index += 1; - let e = Event::GiltIssued{index, expiry, who: who.clone(), amount}; + let e = + Event::GiltIssued { index, expiry, who: who.clone(), amount }; Self::deposit_event(e); let gilt = ActiveGilt { amount, proportion, who, expiry }; Active::::insert(index, gilt); @@ -608,14 +624,14 @@ pub mod pallet { bids_taken += 1; if remaining.is_zero() || bids_taken == max_bids { - break + break; } } queues_hit += 1; qs[queue_index].0 = q.len() as u32; }); if remaining.is_zero() || bids_taken == max_bids { - break + break; } } }); diff --git a/frame/grandpa/src/equivocation.rs b/frame/grandpa/src/equivocation.rs index 8a23ce6e1ef1e..277e88c89af0b 100644 --- a/frame/grandpa/src/equivocation.rs +++ b/frame/grandpa/src/equivocation.rs @@ -208,15 +208,15 @@ impl Pallet { if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call { // discard equivocation report not coming from the local node match source { - TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ }, + TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ } _ => { log::warn!( target: "runtime::afg", "rejecting unsigned report equivocation transaction because it is not local/in-block." ); - return InvalidTransaction::Call.into() - }, + return InvalidTransaction::Call.into(); + } } // check report staleness diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 89e66f125f98b..894e6edc65e81 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -154,7 +154,7 @@ pub mod pallet { // enact the change if we've reached the enacting block if block_number == pending_change.scheduled_at + pending_change.delay { Self::set_grandpa_authorities(&pending_change.next_authorities); - Self::deposit_event(Event::NewAuthorities{ + Self::deposit_event(Event::NewAuthorities { authority_set: pending_change.next_authorities.to_vec(), }); >::kill(); @@ -174,7 +174,7 @@ pub mod pallet { >::put(StoredState::Paused); Self::deposit_event(Event::Paused); } - }, + } StoredState::PendingResume { scheduled_at, delay } => { // signal change to resume if block_number == scheduled_at { @@ -186,8 +186,8 @@ pub mod pallet { >::put(StoredState::Live); Self::deposit_event(Event::Resumed); } - }, - _ => {}, + } + _ => {} } } } @@ -256,7 +256,7 @@ pub mod pallet { #[pallet::generate_deposit(fn deposit_event)] pub enum Event { /// New authority set has been applied. - NewAuthorities{authority_set: AuthorityList}, + NewAuthorities { authority_set: AuthorityList }, /// Current authority set has been paused. Paused, /// Current authority set has been resumed. @@ -550,7 +550,7 @@ impl Pallet { // validate equivocation proof (check votes are different and // signatures are valid). if !sp_finality_grandpa::check_equivocation_proof(equivocation_proof) { - return Err(Error::::InvalidEquivocationProof.into()) + return Err(Error::::InvalidEquivocationProof.into()); } // fetch the current and previous sets last session index. on the @@ -569,12 +569,12 @@ impl Pallet { // check that the session id for the membership proof is within the // bounds of the set id reported in the equivocation. - if session_index > set_id_session_index || - previous_set_id_session_index + if session_index > set_id_session_index + || previous_set_id_session_index .map(|previous_index| session_index <= previous_index) .unwrap_or(false) { - return Err(Error::::InvalidEquivocationProof.into()) + return Err(Error::::InvalidEquivocationProof.into()); } // report to the offences module rewarding the sender. diff --git a/frame/grandpa/src/migrations/v4.rs b/frame/grandpa/src/migrations/v4.rs index 094f276efef31..ad2b346727e02 100644 --- a/frame/grandpa/src/migrations/v4.rs +++ b/frame/grandpa/src/migrations/v4.rs @@ -37,7 +37,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { target: "runtime::afg", "New pallet name is equal to the old prefix. No migration needs to be done.", ); - return 0 + return 0; } let storage_version = StorageVersion::get::>(); log::info!( diff --git a/frame/grandpa/src/tests.rs b/frame/grandpa/src/tests.rs index 591faf7fe393a..2a20d723fa147 100644 --- a/frame/grandpa/src/tests.rs +++ b/frame/grandpa/src/tests.rs @@ -57,7 +57,10 @@ fn authorities_change_logged() { System::events(), vec![EventRecord { phase: Phase::Finalization, - event: Event::NewAuthorities{authority_set: to_authorities(vec![(4, 1), (5, 1), (6, 1)])}.into(), + event: Event::NewAuthorities { + authority_set: to_authorities(vec![(4, 1), (5, 1), (6, 1)]) + } + .into(), topics: vec![], },] ); @@ -93,7 +96,10 @@ fn authorities_change_logged_after_delay() { System::events(), vec![EventRecord { phase: Phase::Finalization, - event: Event::NewAuthorities{authority_set: to_authorities(vec![(4, 1), (5, 1), (6, 1)])}.into(), + event: Event::NewAuthorities { + authority_set: to_authorities(vec![(4, 1), (5, 1), (6, 1)]) + } + .into(), topics: vec![], },] ); @@ -373,7 +379,7 @@ fn report_equivocation_current_set_works() { // check that the balances of all other validators are left intact. for validator in &validators { if *validator == equivocation_validator_id { - continue + continue; } assert_eq!(Balances::total_balance(validator), 10_000_000); @@ -452,7 +458,7 @@ fn report_equivocation_old_set_works() { // check that the balances of all other validators are left intact. for validator in &validators { if *validator == equivocation_validator_id { - continue + continue; } assert_eq!(Balances::total_balance(validator), 10_000_000); diff --git a/frame/identity/src/benchmarking.rs b/frame/identity/src/benchmarking.rs index df7aba72fd958..da2c4cae50cda 100644 --- a/frame/identity/src/benchmarking.rs +++ b/frame/identity/src/benchmarking.rs @@ -44,14 +44,16 @@ fn add_registrars(r: u32) -> Result<(), &'static str> { i.into(), 10u32.into(), )?; - let fields = - IdentityFields( - IdentityField::Display | - IdentityField::Legal | IdentityField::Web | - IdentityField::Riot | IdentityField::Email | - IdentityField::PgpFingerprint | - IdentityField::Image | IdentityField::Twitter, - ); + let fields = IdentityFields( + IdentityField::Display + | IdentityField::Legal + | IdentityField::Web + | IdentityField::Riot + | IdentityField::Email + | IdentityField::PgpFingerprint + | IdentityField::Image + | IdentityField::Twitter, + ); Identity::::set_fields(RawOrigin::Signed(registrar.clone()).into(), i.into(), fields)?; } @@ -113,7 +115,7 @@ fn create_identity_info(num_fields: u32) -> IdentityInfo { /// A name was set or reset (which will remove all judgements). - IdentitySet{who: T::AccountId}, + IdentitySet { who: T::AccountId }, /// A name was cleared, and the given balance returned. - IdentityCleared{who: T::AccountId, deposit: BalanceOf}, + IdentityCleared { who: T::AccountId, deposit: BalanceOf }, /// A name was removed and the given balance slashed. - IdentityKilled{who: T::AccountId, deposit: BalanceOf}, + IdentityKilled { who: T::AccountId, deposit: BalanceOf }, /// A judgement was asked from a registrar. - JudgementRequested{who: T::AccountId, registrar_index: RegistrarIndex}, + JudgementRequested { who: T::AccountId, registrar_index: RegistrarIndex }, /// A judgement request was retracted. - JudgementUnrequested{who: T::AccountId, registrar_index: RegistrarIndex}, + JudgementUnrequested { who: T::AccountId, registrar_index: RegistrarIndex }, /// A judgement was given by a registrar. - JudgementGiven{target: T::AccountId, registrar_index: RegistrarIndex}, + JudgementGiven { target: T::AccountId, registrar_index: RegistrarIndex }, /// A registrar was added. - RegistrarAdded{registrar_index: RegistrarIndex}, + RegistrarAdded { registrar_index: RegistrarIndex }, /// A sub-identity was added to an identity and the deposit paid. - SubIdentityAdded{sub: T::AccountId, main: T::AccountId, deposit: BalanceOf}, + SubIdentityAdded { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf }, /// A sub-identity was removed from an identity and the deposit freed. - SubIdentityRemoved{sub: T::AccountId, main: T::AccountId, deposit: BalanceOf}, + SubIdentityRemoved { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf }, /// A sub-identity was cleared, and the given deposit repatriated from the /// main identity account to the sub-identity account. - SubIdentityRevoked{sub: T::AccountId, main: T::AccountId, deposit: BalanceOf}, + SubIdentityRevoked { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf }, } #[pallet::call] @@ -300,7 +300,7 @@ pub mod pallet { }, )?; - Self::deposit_event(Event::RegistrarAdded{registrar_index: i}); + Self::deposit_event(Event::RegistrarAdded { registrar_index: i }); Ok(Some(T::WeightInfo::add_registrar(registrar_count as u32)).into()) } @@ -343,7 +343,7 @@ pub mod pallet { id.judgements.retain(|j| j.1.is_sticky()); id.info = *info; id - }, + } None => Registration { info: *info, judgements: BoundedVec::default(), @@ -363,7 +363,7 @@ pub mod pallet { let judgements = id.judgements.len(); >::insert(&sender, id); - Self::deposit_event(Event::IdentitySet{who: sender}); + Self::deposit_event(Event::IdentitySet { who: sender }); Ok(Some(T::WeightInfo::set_identity( judgements as u32, // R @@ -488,7 +488,7 @@ pub mod pallet { let err_amount = T::Currency::unreserve(&sender, deposit.clone()); debug_assert!(err_amount.is_zero()); - Self::deposit_event(Event::IdentityCleared{who: sender, deposit}); + Self::deposit_event(Event::IdentityCleared { who: sender, deposit }); Ok(Some(T::WeightInfo::clear_identity( id.judgements.len() as u32, // R @@ -541,14 +541,16 @@ pub mod pallet { let item = (reg_index, Judgement::FeePaid(registrar.fee)); match id.judgements.binary_search_by_key(®_index, |x| x.0) { - Ok(i) => + Ok(i) => { if id.judgements[i].1.is_sticky() { Err(Error::::StickyJudgement)? } else { id.judgements[i] = item - }, - Err(i) => - id.judgements.try_insert(i, item).map_err(|_| Error::::TooManyRegistrars)?, + } + } + Err(i) => { + id.judgements.try_insert(i, item).map_err(|_| Error::::TooManyRegistrars)? + } } T::Currency::reserve(&sender, registrar.fee)?; @@ -557,7 +559,10 @@ pub mod pallet { let extra_fields = id.info.additional.len(); >::insert(&sender, id); - Self::deposit_event(Event::JudgementRequested{who: sender, registrar_index: reg_index}); + Self::deposit_event(Event::JudgementRequested { + who: sender, + registrar_index: reg_index, + }); Ok(Some(T::WeightInfo::request_judgement(judgements as u32, extra_fields as u32)) .into()) @@ -607,7 +612,10 @@ pub mod pallet { let extra_fields = id.info.additional.len(); >::insert(&sender, id); - Self::deposit_event(Event::JudgementUnrequested{who: sender, registrar_index: reg_index}); + Self::deposit_event(Event::JudgementUnrequested { + who: sender, + registrar_index: reg_index, + }); Ok(Some(T::WeightInfo::cancel_request(judgements as u32, extra_fields as u32)).into()) } @@ -780,7 +788,7 @@ pub mod pallet { ); } id.judgements[position] = item - }, + } Err(position) => id .judgements .try_insert(position, item) @@ -790,7 +798,7 @@ pub mod pallet { let judgements = id.judgements.len(); let extra_fields = id.info.additional.len(); >::insert(&target, id); - Self::deposit_event(Event::JudgementGiven{target, registrar_index: reg_index}); + Self::deposit_event(Event::JudgementGiven { target, registrar_index: reg_index }); Ok(Some(T::WeightInfo::provide_judgement(judgements as u32, extra_fields as u32)) .into()) @@ -838,7 +846,7 @@ pub mod pallet { // Slash their deposit from them. T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0); - Self::deposit_event(Event::IdentityKilled{who: target, deposit}); + Self::deposit_event(Event::IdentityKilled { who: target, deposit }); Ok(Some(T::WeightInfo::kill_identity( id.judgements.len() as u32, // R @@ -881,7 +889,7 @@ pub mod pallet { sub_ids.try_push(sub.clone()).expect("sub ids length checked above; qed"); *subs_deposit = subs_deposit.saturating_add(deposit); - Self::deposit_event(Event::SubIdentityAdded{sub, main: sender.clone(), deposit}); + Self::deposit_event(Event::SubIdentityAdded { sub, main: sender.clone(), deposit }); Ok(()) }) } @@ -928,7 +936,7 @@ pub mod pallet { *subs_deposit -= deposit; let err_amount = T::Currency::unreserve(&sender, deposit); debug_assert!(err_amount.is_zero()); - Self::deposit_event(Event::SubIdentityRemoved{sub: sub, main: sender, deposit}); + Self::deposit_event(Event::SubIdentityRemoved { sub, main: sender, deposit }); }); Ok(()) } @@ -953,7 +961,11 @@ pub mod pallet { *subs_deposit -= deposit; let _ = T::Currency::repatriate_reserved(&sup, &sender, deposit, BalanceStatus::Free); - Self::deposit_event(Event::SubIdentityRevoked{sub: sender, main: sup.clone(), deposit}); + Self::deposit_event(Event::SubIdentityRevoked { + sub: sender, + main: sup.clone(), + deposit, + }); }); Ok(()) } diff --git a/frame/identity/src/types.rs b/frame/identity/src/types.rs index ed6aeb18e96a1..9be05c3b832f6 100644 --- a/frame/identity/src/types.rs +++ b/frame/identity/src/types.rs @@ -64,7 +64,7 @@ impl Decode for Data { .expect("bound checked in match arm condition; qed"); input.read(&mut r[..])?; Data::Raw(r) - }, + } 34 => Data::BlakeTwo256(<[u8; 32]>::decode(input)?), 35 => Data::Sha256(<[u8; 32]>::decode(input)?), 36 => Data::Keccak256(<[u8; 32]>::decode(input)?), @@ -83,7 +83,7 @@ impl Encode for Data { let mut r = vec![l as u8 + 1; l + 1]; r[1..].copy_from_slice(&x[..l as usize]); r - }, + } Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(), Data::Sha256(ref h) => once(35u8).chain(h.iter().cloned()).collect(), Data::Keccak256(ref h) => once(36u8).chain(h.iter().cloned()).collect(), @@ -368,8 +368,9 @@ impl< > Registration { pub(crate) fn total_deposit(&self) -> Balance { - self.deposit + - self.judgements + self.deposit + + self + .judgements .iter() .map(|(_, ref j)| if let Judgement::FeePaid(fee) = j { *fee } else { Zero::zero() }) .fold(Zero::zero(), |a, i| a + i) diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index 51babc9150a10..f18c072ca3aed 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -193,10 +193,10 @@ impl sp_std::fmt::Debug for OffchainErr write!(fmt, "Too early to send heartbeat."), OffchainErr::WaitingForInclusion(ref block) => { write!(fmt, "Heartbeat already sent at {:?}. Waiting for inclusion.", block) - }, + } OffchainErr::AlreadyOnline(auth_idx) => { write!(fmt, "Authority {} is already online", auth_idx) - }, + } OffchainErr::FailedSigning => write!(fmt, "Failed to sign heartbeat"), OffchainErr::FailedToAcquireLock => write!(fmt, "Failed to acquire lock"), OffchainErr::NetworkState => write!(fmt, "Failed to fetch network state"), @@ -376,11 +376,11 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A new heartbeat was received from `AuthorityId`. - HeartbeatReceived{authority_id: T::AuthorityId}, + HeartbeatReceived { authority_id: T::AuthorityId }, /// At the end of the session, no offence was committed. AllGood, /// At the end of the session, at least one validator was found to be offline. - SomeOffline{offline: Vec>}, + SomeOffline { offline: Vec> }, } #[pallet::error] @@ -496,7 +496,7 @@ pub mod pallet { let keys = Keys::::get(); let public = keys.get(heartbeat.authority_index as usize); if let (false, Some(public)) = (exists, public) { - Self::deposit_event(Event::::HeartbeatReceived{authority_id: public.clone()}); + Self::deposit_event(Event::::HeartbeatReceived { authority_id: public.clone() }); let network_state_bounded = BoundedOpaqueNetworkState::< T::MaxPeerDataEncodingSize, @@ -555,19 +555,19 @@ pub mod pallet { if let Call::heartbeat { heartbeat, signature } = call { if >::is_online(heartbeat.authority_index) { // we already received a heartbeat for this authority - return InvalidTransaction::Stale.into() + return InvalidTransaction::Stale.into(); } // check if session index from heartbeat is recent let current_session = T::ValidatorSet::session_index(); if heartbeat.session_index != current_session { - return InvalidTransaction::Stale.into() + return InvalidTransaction::Stale.into(); } // verify that the incoming (unverified) pubkey is actually an authority id let keys = Keys::::get(); if keys.len() as u32 != heartbeat.validators_len { - return InvalidTransaction::Custom(INVALID_VALIDATORS_LEN).into() + return InvalidTransaction::Custom(INVALID_VALIDATORS_LEN).into(); } let authority_id = match keys.get(heartbeat.authority_index as usize) { Some(id) => id, @@ -580,7 +580,7 @@ pub mod pallet { }); if !signature_valid { - return InvalidTransaction::BadProof.into() + return InvalidTransaction::BadProof.into(); } ValidTransaction::with_tag_prefix("ImOnline") @@ -624,7 +624,7 @@ impl Pallet { let current_validators = T::ValidatorSet::validators(); if authority_index >= current_validators.len() as u32 { - return false + return false; } let authority = ¤t_validators[authority_index as usize]; @@ -635,8 +635,8 @@ impl Pallet { fn is_online_aux(authority_index: AuthIndex, authority: &ValidatorId) -> bool { let current_session = T::ValidatorSet::session_index(); - ReceivedHeartbeats::::contains_key(¤t_session, &authority_index) || - AuthoredBlocks::::get(¤t_session, authority) != 0 + ReceivedHeartbeats::::contains_key(¤t_session, &authority_index) + || AuthoredBlocks::::get(¤t_session, authority) != 0 } /// Returns `true` if a heartbeat has been received for the authority at `authority_index` in @@ -686,8 +686,8 @@ impl Pallet { // haven't sent an heartbeat yet we'll send one unconditionally. the idea is to prevent // all nodes from sending the heartbeats at the same block and causing a temporary (but // deterministic) spike in transactions. - progress >= START_HEARTBEAT_FINAL_PERIOD || - progress >= START_HEARTBEAT_RANDOM_PERIOD && random_choice(progress) + progress >= START_HEARTBEAT_FINAL_PERIOD + || progress >= START_HEARTBEAT_RANDOM_PERIOD && random_choice(progress) } else { // otherwise we fallback to using the block number calculated at the beginning // of the session that should roughly correspond to the middle of the session @@ -696,7 +696,7 @@ impl Pallet { }; if !should_heartbeat { - return Err(OffchainErr::TooEarly) + return Err(OffchainErr::TooEarly); } let session_index = T::ValidatorSet::session_index(); @@ -738,7 +738,7 @@ impl Pallet { }; if Self::is_online(authority_index) { - return Err(OffchainErr::AlreadyOnline(authority_index)) + return Err(OffchainErr::AlreadyOnline(authority_index)); } // acquire lock for that authority at current heartbeat to make sure we don't @@ -804,15 +804,16 @@ impl Pallet { // we will re-send it. match status { // we are still waiting for inclusion. - Ok(Some(status)) if status.is_recent(session_index, now) => - Err(OffchainErr::WaitingForInclusion(status.sent_at)), + Ok(Some(status)) if status.is_recent(session_index, now) => { + Err(OffchainErr::WaitingForInclusion(status.sent_at)) + } // attempt to set new status _ => Ok(HeartbeatStatus { session_index, sent_at: now }), } }, ); if let Err(MutateStorageError::ValueFunctionFailed(err)) = res { - return Err(err) + return Err(err); } let mut new_status = res.map_err(|_| OffchainErr::FailedToAcquireLock)?; @@ -909,7 +910,7 @@ impl OneSessionHandler for Pallet { if offenders.is_empty() { Self::deposit_event(Event::::AllGood); } else { - Self::deposit_event(Event::::SomeOffline{offline: offenders.clone()}); + Self::deposit_event(Event::::SomeOffline { offline: offenders.clone() }); let validator_set_count = keys.len() as u32; let offence = UnresponsivenessOffence { session_index, validator_set_count, offenders }; diff --git a/frame/im-online/src/tests.rs b/frame/im-online/src/tests.rs index bb2c4c7cae548..d1dd29abf0890 100644 --- a/frame/im-online/src/tests.rs +++ b/frame/im-online/src/tests.rs @@ -135,8 +135,9 @@ fn heartbeat( signature: signature.clone(), }) .map_err(|e| match e { - TransactionValidityError::Invalid(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN)) => - "invalid validators len", + TransactionValidityError::Invalid(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN)) => { + "invalid validators len" + } e @ _ => <&'static str>::from(e), })?; ImOnline::heartbeat(Origin::none(), heartbeat, signature) diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index 8b71a4ac13c6f..d8051bac0a3cd 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -105,7 +105,7 @@ pub mod pallet { *maybe_value = Some((who.clone(), T::Deposit::get(), false)); T::Currency::reserve(&who, T::Deposit::get()) })?; - Self::deposit_event(Event::IndexAssigned{who, index}); + Self::deposit_event(Event::IndexAssigned { who, index }); Ok(()) } @@ -146,7 +146,7 @@ pub mod pallet { *maybe_value = Some((new.clone(), amount.saturating_sub(lost), false)); Ok(()) })?; - Self::deposit_event(Event::IndexAssigned{who: new, index}); + Self::deposit_event(Event::IndexAssigned { who: new, index }); Ok(()) } @@ -179,7 +179,7 @@ pub mod pallet { T::Currency::unreserve(&who, amount); Ok(()) })?; - Self::deposit_event(Event::IndexFreed{index}); + Self::deposit_event(Event::IndexFreed { index }); Ok(()) } @@ -219,7 +219,7 @@ pub mod pallet { } *maybe_value = Some((new.clone(), Zero::zero(), freeze)); }); - Self::deposit_event(Event::IndexAssigned{who: new, index}); + Self::deposit_event(Event::IndexAssigned { who: new, index }); Ok(()) } @@ -253,7 +253,7 @@ pub mod pallet { *maybe_value = Some((account, Zero::zero(), true)); Ok(()) })?; - Self::deposit_event(Event::IndexFrozen{index, who}); + Self::deposit_event(Event::IndexFrozen { index, who }); Ok(()) } } @@ -262,11 +262,11 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A account index was assigned. - IndexAssigned{who: T::AccountId, index: T::AccountIndex}, + IndexAssigned { who: T::AccountId, index: T::AccountIndex }, /// A account index has been freed up (unassigned). - IndexFreed{index: T::AccountIndex}, + IndexFreed { index: T::AccountIndex }, /// A account index has been frozen to its current account ID. - IndexFrozen{index: T::AccountIndex, who: T::AccountId}, + IndexFrozen { index: T::AccountIndex, who: T::AccountId }, } /// Old name generated by `decl_event`. diff --git a/frame/lottery/src/lib.rs b/frame/lottery/src/lib.rs index dbf7bf96868e4..364a484a3abc9 100644 --- a/frame/lottery/src/lib.rs +++ b/frame/lottery/src/lib.rs @@ -176,9 +176,9 @@ pub mod pallet { /// A new set of calls have been set! CallsUpdated, /// A winner has been chosen! - Winner{winner: T::AccountId, lottery_balance: BalanceOf}, + Winner { winner: T::AccountId, lottery_balance: BalanceOf }, /// A ticket has been bought! - TicketBought{who: T::AccountId, call_index: CallIndex}, + TicketBought { who: T::AccountId, call_index: CallIndex }, } #[pallet::error] @@ -250,7 +250,7 @@ pub mod pallet { ); debug_assert!(res.is_ok()); - Self::deposit_event(Event::::Winner{winner, lottery_balance}); + Self::deposit_event(Event::::Winner { winner, lottery_balance }); TicketsCount::::kill(); @@ -259,18 +259,18 @@ pub mod pallet { LotteryIndex::::mutate(|index| *index = index.saturating_add(1)); // Set a new start with the current block. config.start = n; - return T::WeightInfo::on_initialize_repeat() + return T::WeightInfo::on_initialize_repeat(); } else { // Else, kill the lottery storage. *lottery = None; - return T::WeightInfo::on_initialize_end() + return T::WeightInfo::on_initialize_end(); } // We choose not need to kill Participants and Tickets to avoid a large // number of writes at one time. Instead, data persists between lotteries, // but is not used if it is not relevant. } } - return T::DbWeight::get().reads(1) + return T::DbWeight::get().reads(1); }) } } @@ -410,7 +410,7 @@ impl Pallet { if encoded_call.len() < 2 { Err(Error::::EncodingFailed)? } - return Ok((encoded_call[0], encoded_call[1])) + return Ok((encoded_call[0], encoded_call[1])); } // Logic for buying a ticket. @@ -452,7 +452,7 @@ impl Pallet { }, )?; - Self::deposit_event(Event::::TicketBought{who: caller.clone(), call_index}); + Self::deposit_event(Event::::TicketBought { who: caller.clone(), call_index }); Ok(()) } @@ -464,7 +464,7 @@ impl Pallet { // Best effort attempt to remove bias from modulus operator. for i in 1..T::MaxGenerateRandom::get() { if random_number < u32::MAX - u32::MAX % total { - break + break; } random_number = Self::generate_random_number(i); diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 021633e185e03..7d001240cd417 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -143,7 +143,7 @@ pub mod pallet { /// One of the members' keys changed. KeyChanged, /// Phantom member, never used. - Dummy{_phantom_data: PhantomData<(T::AccountId, >::Event)>}, + Dummy { _phantom_data: PhantomData<(T::AccountId, >::Event)> }, } /// Old name generated by `decl_event`. @@ -215,7 +215,7 @@ pub mod pallet { T::SwapOrigin::ensure_origin(origin)?; if remove == add { - return Ok(()) + return Ok(()); } let mut members = >::get(); diff --git a/frame/membership/src/migrations/v4.rs b/frame/membership/src/migrations/v4.rs index c1c944be1fd4f..a0601b4027864 100644 --- a/frame/membership/src/migrations/v4.rs +++ b/frame/membership/src/migrations/v4.rs @@ -46,7 +46,7 @@ pub fn migrate::on_chain_storage_version(); @@ -85,7 +85,7 @@ pub fn pre_migrate>(old_pallet_name: N, new_ log_migration("pre-migration", old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return + return; } let new_pallet_prefix = twox_128(new_pallet_name.as_bytes()); @@ -113,7 +113,7 @@ pub fn post_migrate>(old_pallet_name: N, new log_migration("post-migration", old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return + return; } // Assert that nothing remains at the old prefix. diff --git a/frame/merkle-mountain-range/src/lib.rs b/frame/merkle-mountain-range/src/lib.rs index 01bf1b2254f09..227cde08c889d 100644 --- a/frame/merkle-mountain-range/src/lib.rs +++ b/frame/merkle-mountain-range/src/lib.rs @@ -255,12 +255,12 @@ impl, I: 'static> Pallet { leaf: LeafOf, proof: primitives::Proof<>::Hash>, ) -> Result<(), primitives::Error> { - if proof.leaf_count > Self::mmr_leaves() || - proof.leaf_count == 0 || - proof.items.len() as u32 > mmr::utils::NodesUtils::new(proof.leaf_count).depth() + if proof.leaf_count > Self::mmr_leaves() + || proof.leaf_count == 0 + || proof.items.len() as u32 > mmr::utils::NodesUtils::new(proof.leaf_count).depth() { return Err(primitives::Error::Verify - .log_debug("The proof has incorrect number of leaves or proof items.")) + .log_debug("The proof has incorrect number of leaves or proof items.")); } let mmr: ModuleMmr = mmr::Mmr::new(proof.leaf_count); diff --git a/frame/merkle-mountain-range/src/mmr/storage.rs b/frame/merkle-mountain-range/src/mmr/storage.rs index 09e24017816ec..c895a5e8799d1 100644 --- a/frame/merkle-mountain-range/src/mmr/storage.rs +++ b/frame/merkle-mountain-range/src/mmr/storage.rs @@ -86,7 +86,7 @@ where let mut leaves = crate::NumberOfLeaves::::get(); let mut size = crate::mmr::utils::NodesUtils::new(leaves).size(); if pos != size { - return Err(mmr_lib::Error::InconsistentStore) + return Err(mmr_lib::Error::InconsistentStore); } for elem in elems { diff --git a/frame/merkle-mountain-range/src/mmr/utils.rs b/frame/merkle-mountain-range/src/mmr/utils.rs index 8fc725f11e72f..233a0da474f80 100644 --- a/frame/merkle-mountain-range/src/mmr/utils.rs +++ b/frame/merkle-mountain-range/src/mmr/utils.rs @@ -46,7 +46,7 @@ impl NodesUtils { /// Calculate maximal depth of the MMR. pub fn depth(&self) -> u32 { if self.no_of_leaves == 0 { - return 0 + return 0; } 64 - self.no_of_leaves.next_power_of_two().leading_zeros() diff --git a/frame/multisig/src/lib.rs b/frame/multisig/src/lib.rs index 62b58f8ddf428..28fbc575392e8 100644 --- a/frame/multisig/src/lib.rs +++ b/frame/multisig/src/lib.rs @@ -206,12 +206,17 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A new multisig operation has begun. \[approving, multisig, call_hash\] - NewMultisig{approving: T::AccountId, multisig: T::AccountId, call_hash: CallHash}, + NewMultisig { approving: T::AccountId, multisig: T::AccountId, call_hash: CallHash }, /// A multisig operation has been approved by someone. /// \[approving, timepoint, multisig, call_hash\] - MultisigApproval{approving: T::AccountId, timepoint: Timepoint, multisig: T::AccountId, call_hash: CallHash}, + MultisigApproval { + approving: T::AccountId, + timepoint: Timepoint, + multisig: T::AccountId, + call_hash: CallHash, + }, /// A multisig operation has been executed. \[approving, timepoint, multisig, call_hash\] - MultisigExecuted{ + MultisigExecuted { approving: T::AccountId, timepoint: Timepoint, multisig: T::AccountId, @@ -219,7 +224,12 @@ pub mod pallet { result: DispatchResult, }, /// A multisig operation has been cancelled. \[cancelling, timepoint, multisig, call_hash\] - MultisigCancelled{cancelling: T::AccountId, timepoint: Timepoint, multisig: T::AccountId, call_hash: CallHash}, + MultisigCancelled { + cancelling: T::AccountId, + timepoint: Timepoint, + multisig: T::AccountId, + call_hash: CallHash, + }, } #[pallet::hooks] @@ -287,7 +297,7 @@ pub mod pallet { let post_info = Some(weight_used).into(); let error = err.error.into(); DispatchErrorWithPostInfo { post_info, error } - }, + } None => err, }) } @@ -481,7 +491,12 @@ pub mod pallet { >::remove(&id, &call_hash); Self::clear_call(&call_hash); - Self::deposit_event(Event::MultisigCancelled{cancelling: who, timepoint, multisig: id, call_hash: call_hash}); + Self::deposit_event(Event::MultisigCancelled { + cancelling: who, + timepoint, + multisig: id, + call_hash, + }); Ok(()) } } @@ -520,7 +535,7 @@ impl Pallet { let call_hash = blake2_256(call.encoded()); let call_len = call.encoded_len(); (call_hash, call_len, Some(call), should_store) - }, + } CallOrHash::Hash(h) => (h, 0, None, false), }; @@ -557,7 +572,7 @@ impl Pallet { T::Currency::unreserve(&m.depositor, m.deposit); let result = call.dispatch(RawOrigin::Signed(id.clone()).into()); - Self::deposit_event(Event::MultisigExecuted{ + Self::deposit_event(Event::MultisigExecuted { approving: who, timepoint, multisig: id, @@ -594,7 +609,12 @@ impl Pallet { // Record approval. m.approvals.insert(pos, who.clone()); >::insert(&id, call_hash, m); - Self::deposit_event(Event::MultisigApproval{approving: who, timepoint, multisig: id, call_hash}); + Self::deposit_event(Event::MultisigApproval { + approving: who, + timepoint, + multisig: id, + call_hash, + }); } else { // If we already approved and didn't store the Call, then this was useless and // we report an error. @@ -638,7 +658,7 @@ impl Pallet { approvals: vec![who.clone()], }, ); - Self::deposit_event(Event::NewMultisig{approving: who, multisig: id, call_hash}); + Self::deposit_event(Event::NewMultisig { approving: who, multisig: id, call_hash }); let final_weight = if stored { T::WeightInfo::as_multi_create_store(other_signatories_len as u32, call_len as u32) diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index 57a6791684d5d..0145513f52ad7 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -706,7 +706,14 @@ fn multisig_2_of_3_cannot_reissue_same_call() { let err = DispatchError::from(BalancesError::::InsufficientBalance).stripped(); System::assert_last_event( - pallet_multisig::Event::MultisigExecuted{approving: 3, timepoint: now(), multisig: multi, call_hash: hash, result: Err(err)}.into(), + pallet_multisig::Event::MultisigExecuted { + approving: 3, + timepoint: now(), + multisig: multi, + call_hash: hash, + result: Err(err), + } + .into(), ); }); } diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index 712d6baad7c51..438929576269c 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -90,15 +90,15 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// A name was set. - NameSet{who: T::AccountId}, + NameSet { who: T::AccountId }, /// A name was forcibly set. - NameForced{target: T::AccountId}, + NameForced { target: T::AccountId }, /// A name was changed. - NameChanged{who: T::AccountId}, + NameChanged { who: T::AccountId }, /// A name was cleared, and the given balance returned. - NameCleared{who: T::AccountId, deposit: BalanceOf}, + NameCleared { who: T::AccountId, deposit: BalanceOf }, /// A name was removed and the given balance slashed. - NameKilled{target: T::AccountId, deposit: BalanceOf}, + NameKilled { target: T::AccountId, deposit: BalanceOf }, } /// Error for the nicks pallet. @@ -147,12 +147,12 @@ pub mod pallet { ensure!(name.len() <= T::MaxLength::get() as usize, Error::::TooLong); let deposit = if let Some((_, deposit)) = >::get(&sender) { - Self::deposit_event(Event::::NameChanged{who: sender.clone()}); + Self::deposit_event(Event::::NameChanged { who: sender.clone() }); deposit } else { let deposit = T::ReservationFee::get(); T::Currency::reserve(&sender, deposit.clone())?; - Self::deposit_event(Event::::NameSet{who: sender.clone()}); + Self::deposit_event(Event::::NameSet { who: sender.clone() }); deposit }; @@ -179,7 +179,7 @@ pub mod pallet { let err_amount = T::Currency::unreserve(&sender, deposit.clone()); debug_assert!(err_amount.is_zero()); - Self::deposit_event(Event::::NameCleared{who: sender, deposit}); + Self::deposit_event(Event::::NameCleared { who: sender, deposit }); Ok(()) } @@ -210,7 +210,7 @@ pub mod pallet { // Slash their deposit from them. T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit.clone()).0); - Self::deposit_event(Event::::NameKilled{target, deposit}); + Self::deposit_event(Event::::NameKilled { target, deposit }); Ok(()) } @@ -238,7 +238,7 @@ pub mod pallet { let deposit = >::get(&target).map(|x| x.1).unwrap_or_else(Zero::zero); >::insert(&target, (name, deposit)); - Self::deposit_event(Event::::NameForced{target}); + Self::deposit_event(Event::::NameForced { target }); Ok(()) } } diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index ab8e9844e93e3..8259d7d1773e0 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -128,24 +128,24 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// The given well known node was added. - NodeAdded{peer_id: PeerId, who: T::AccountId}, + NodeAdded { peer_id: PeerId, who: T::AccountId }, /// The given well known node was removed. - NodeRemoved{peer_id: PeerId}, + NodeRemoved { peer_id: PeerId }, /// The given well known node was swapped; first item was removed, /// the latter was added. - NodeSwapped{removed: PeerId, added: PeerId}, + NodeSwapped { removed: PeerId, added: PeerId }, /// The given well known nodes were reset. - NodesReset{nodes: Vec<(PeerId, T::AccountId)>}, + NodesReset { nodes: Vec<(PeerId, T::AccountId)> }, /// The given node was claimed by a user. - NodeClaimed{peer_id: PeerId, who: T::AccountId}, + NodeClaimed { peer_id: PeerId, who: T::AccountId }, /// The given claim was removed by its owner. - ClaimRemoved{peer_id: PeerId, who: T::AccountId}, + ClaimRemoved { peer_id: PeerId, who: T::AccountId }, /// The node was transferred to another account. - NodeTransferred{peer_id: PeerId, target: T::AccountId}, + NodeTransferred { peer_id: PeerId, target: T::AccountId }, /// The allowed connections were added to a node. - ConnectionsAdded{peer_id: PeerId, allowed_connections: Vec}, + ConnectionsAdded { peer_id: PeerId, allowed_connections: Vec }, /// The allowed connections were removed from a node. - ConnectionsRemoved{peer_id: PeerId, allowed_connections: Vec}, + ConnectionsRemoved { peer_id: PeerId, allowed_connections: Vec }, } #[pallet::error] @@ -193,7 +193,7 @@ pub mod pallet { true, ), } - }, + } } } } @@ -224,7 +224,7 @@ pub mod pallet { WellKnownNodes::::put(&nodes); >::insert(&node, &owner); - Self::deposit_event(Event::NodeAdded{peer_id: node, who: owner}); + Self::deposit_event(Event::NodeAdded { peer_id: node, who: owner }); Ok(()) } @@ -248,7 +248,7 @@ pub mod pallet { >::remove(&node); AdditionalConnections::::remove(&node); - Self::deposit_event(Event::NodeRemoved{peer_id: node}); + Self::deposit_event(Event::NodeRemoved { peer_id: node }); Ok(()) } @@ -270,7 +270,7 @@ pub mod pallet { ensure!(add.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); if remove == add { - return Ok(()) + return Ok(()); } let mut nodes = WellKnownNodes::::get(); @@ -284,7 +284,7 @@ pub mod pallet { Owners::::swap(&remove, &add); AdditionalConnections::::swap(&remove, &add); - Self::deposit_event(Event::NodeSwapped{removed: remove, added: add}); + Self::deposit_event(Event::NodeSwapped { removed: remove, added: add }); Ok(()) } @@ -305,7 +305,7 @@ pub mod pallet { Self::initialize_nodes(&nodes); - Self::deposit_event(Event::NodesReset{nodes}); + Self::deposit_event(Event::NodesReset { nodes }); Ok(()) } @@ -321,7 +321,7 @@ pub mod pallet { ensure!(!Owners::::contains_key(&node), Error::::AlreadyClaimed); Owners::::insert(&node, &sender); - Self::deposit_event(Event::NodeClaimed{peer_id: node, who: sender}); + Self::deposit_event(Event::NodeClaimed { peer_id: node, who: sender }); Ok(()) } @@ -342,7 +342,7 @@ pub mod pallet { Owners::::remove(&node); AdditionalConnections::::remove(&node); - Self::deposit_event(Event::ClaimRemoved{peer_id: node, who: sender}); + Self::deposit_event(Event::ClaimRemoved { peer_id: node, who: sender }); Ok(()) } @@ -364,7 +364,7 @@ pub mod pallet { Owners::::insert(&node, &owner); - Self::deposit_event(Event::NodeTransferred{peer_id: node, target: owner}); + Self::deposit_event(Event::NodeTransferred { peer_id: node, target: owner }); Ok(()) } @@ -388,14 +388,17 @@ pub mod pallet { for add_node in connections.iter() { if *add_node == node { - continue + continue; } nodes.insert(add_node.clone()); } AdditionalConnections::::insert(&node, nodes); - Self::deposit_event(Event::ConnectionsAdded{peer_id: node, allowed_connections: connections}); + Self::deposit_event(Event::ConnectionsAdded { + peer_id: node, + allowed_connections: connections, + }); Ok(()) } @@ -423,7 +426,10 @@ pub mod pallet { AdditionalConnections::::insert(&node, nodes); - Self::deposit_event(Event::ConnectionsRemoved{peer_id: node, allowed_connections: connections}); + Self::deposit_event(Event::ConnectionsRemoved { + peer_id: node, + allowed_connections: connections, + }); Ok(()) } } diff --git a/frame/offences/src/lib.rs b/frame/offences/src/lib.rs index 3392cd6e4a884..305c05a75cbca 100644 --- a/frame/offences/src/lib.rs +++ b/frame/offences/src/lib.rs @@ -130,7 +130,7 @@ pub mod pallet { /// There is an offence reported of the given `kind` happened at the `session_index` and /// (kind-specific) time slot. This event is not deposited for duplicate slashes. /// \[kind, timeslot\]. - Offence(Kind, OpaqueTimeSlot), + Offence { kind: Kind, timeslot: OpaqueTimeSlot }, } #[pallet::hooks] @@ -175,7 +175,7 @@ where ); // Deposit the event. - Self::deposit_event(Event::Offence(O::ID, time_slot.encode())); + Self::deposit_event(Event::Offence { kind: O::ID, timeslot: time_slot.encode() }); Ok(()) } diff --git a/frame/offences/src/tests.rs b/frame/offences/src/tests.rs index 18cfa9410a6c6..8c4fdcc08f995 100644 --- a/frame/offences/src/tests.rs +++ b/frame/offences/src/tests.rs @@ -114,7 +114,10 @@ fn should_deposit_event() { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Offences(crate::Event::Offence(KIND, time_slot.encode())), + event: Event::Offences(crate::Event::Offence { + kind: KIND, + timeslot: time_slot.encode() + }), topics: vec![], }] ); @@ -145,7 +148,10 @@ fn doesnt_deposit_event_for_dups() { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Offences(crate::Event::Offence(KIND, time_slot.encode())), + event: Event::Offences(crate::Event::Offence { + kind: KIND, + timeslot: time_slot.encode() + }), topics: vec![], }] ); diff --git a/frame/proxy/src/benchmarking.rs b/frame/proxy/src/benchmarking.rs index 1eb3ec5770544..4a0b55b211d35 100644 --- a/frame/proxy/src/benchmarking.rs +++ b/frame/proxy/src/benchmarking.rs @@ -86,7 +86,7 @@ benchmarks! { let call: ::Call = frame_system::Call::::remark { remark: vec![] }.into(); }: _(RawOrigin::Signed(caller), real, Some(T::ProxyType::default()), Box::new(call)) verify { - assert_last_event::(Event::ProxyExecuted(Ok(())).into()) + assert_last_event::(Event::ProxyExecuted{result: Ok(())}.into()) } proxy_announced { @@ -107,7 +107,7 @@ benchmarks! { add_announcements::(a, Some(delegate.clone()), None)?; }: _(RawOrigin::Signed(caller), delegate, real, Some(T::ProxyType::default()), Box::new(call)) verify { - assert_last_event::(Event::ProxyExecuted(Ok(())).into()) + assert_last_event::(Event::ProxyExecuted{result: Ok(())}.into()) } remove_announcement { @@ -165,7 +165,7 @@ benchmarks! { let call_hash = T::CallHasher::hash_of(&call); }: _(RawOrigin::Signed(caller.clone()), real.clone(), call_hash) verify { - assert_last_event::(Event::Announced(real, caller, call_hash).into()); + assert_last_event::(Event::Announced{real, proxy: caller, call_hash}.into()); } add_proxy { @@ -216,12 +216,12 @@ benchmarks! { ) verify { let anon_account = Pallet::::anonymous_account(&caller, &T::ProxyType::default(), 0, None); - assert_last_event::(Event::AnonymousCreated( - anon_account, - caller, - T::ProxyType::default(), - 0, - ).into()); + assert_last_event::(Event::AnonymousCreated{ + anonymous: anon_account, + who: caller, + proxy_type: T::ProxyType::default(), + disambiguation_index: 0, + }.into()); } kill_anonymous { diff --git a/frame/proxy/src/lib.rs b/frame/proxy/src/lib.rs index b73101fa73486..cfebb60cd7119 100644 --- a/frame/proxy/src/lib.rs +++ b/frame/proxy/src/lib.rs @@ -327,7 +327,12 @@ pub mod pallet { T::Currency::reserve(&who, deposit)?; Proxies::::insert(&anonymous, (bounded_proxies, deposit)); - Self::deposit_event(Event::AnonymousCreated(anonymous, who, proxy_type, index)); + Self::deposit_event(Event::AnonymousCreated { + anonymous, + who, + proxy_type, + disambiguation_index: index, + }); Ok(()) } @@ -427,7 +432,7 @@ pub mod pallet { }) .map(|d| *deposit = d) })?; - Self::deposit_event(Event::Announced(real, who, call_hash)); + Self::deposit_event(Event::Announced { real, proxy: who, call_hash }); Ok(()) } @@ -532,9 +537,9 @@ pub mod pallet { let call_hash = T::CallHasher::hash_of(&call); let now = system::Pallet::::block_number(); Self::edit_announcements(&delegate, |ann| { - ann.real != real || - ann.call_hash != call_hash || - now.saturating_sub(ann.height) < def.delay + ann.real != real + || ann.call_hash != call_hash + || now.saturating_sub(ann.height) < def.delay }) .map_err(|_| Error::::Unannounced)?; @@ -547,16 +552,25 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// A proxy was executed correctly, with the given \[result\]. - ProxyExecuted(DispatchResult), + /// A proxy was executed correctly, with the given. + ProxyExecuted { result: DispatchResult }, /// Anonymous account has been created by new proxy with given - /// disambiguation index and proxy type. \[anonymous, who, proxy_type, - /// disambiguation_index\] - AnonymousCreated(T::AccountId, T::AccountId, T::ProxyType, u16), - /// An announcement was placed to make a call in the future. \[real, proxy, call_hash\] - Announced(T::AccountId, T::AccountId, CallHashOf), - /// A proxy was added. \[delegator, delegatee, proxy_type, delay\] - ProxyAdded(T::AccountId, T::AccountId, T::ProxyType, T::BlockNumber), + /// disambiguation index and proxy type. + AnonymousCreated { + anonymous: T::AccountId, + who: T::AccountId, + proxy_type: T::ProxyType, + disambiguation_index: u16, + }, + /// An announcement was placed to make a call in the future. + Announced { real: T::AccountId, proxy: T::AccountId, call_hash: CallHashOf }, + /// A proxy was added. + ProxyAdded { + delegator: T::AccountId, + delegatee: T::AccountId, + proxy_type: T::ProxyType, + delay: T::BlockNumber, + }, } /// Old name generated by `decl_event`. @@ -672,12 +686,12 @@ impl Pallet { T::Currency::unreserve(delegator, *deposit - new_deposit); } *deposit = new_deposit; - Self::deposit_event(Event::::ProxyAdded( - delegator.clone(), + Self::deposit_event(Event::::ProxyAdded { + delegator: delegator.clone(), delegatee, proxy_type, delay, - )); + }); Ok(()) }) } @@ -768,8 +782,8 @@ impl Pallet { force_proxy_type: Option, ) -> Result, DispatchError> { let f = |x: &ProxyDefinition| -> bool { - &x.delegate == delegate && - force_proxy_type.as_ref().map_or(true, |y| &x.proxy_type == y) + &x.delegate == delegate + && force_proxy_type.as_ref().map_or(true, |y| &x.proxy_type == y) }; Ok(Proxies::::get(real).0.into_iter().find(f).ok_or(Error::::NotProxy)?) } @@ -787,19 +801,23 @@ impl Pallet { match c.is_sub_type() { // Proxy call cannot add or remove a proxy with more permissions than it already // has. - Some(Call::add_proxy { ref proxy_type, .. }) | - Some(Call::remove_proxy { ref proxy_type, .. }) + Some(Call::add_proxy { ref proxy_type, .. }) + | Some(Call::remove_proxy { ref proxy_type, .. }) if !def.proxy_type.is_superset(&proxy_type) => - false, + { + false + } // Proxy call cannot remove all proxies or kill anonymous proxies unless it has full // permissions. Some(Call::remove_proxies { .. }) | Some(Call::kill_anonymous { .. }) if def.proxy_type != T::ProxyType::default() => - false, + { + false + } _ => def.proxy_type.filter(c), } }); let e = call.dispatch(origin); - Self::deposit_event(Event::ProxyExecuted(e.map(|_| ()).map_err(|e| e.error))); + Self::deposit_event(Event::ProxyExecuted { result: e.map(|_| ()).map_err(|e| e.error) }); } } diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index d319ebb1a5ab0..d143094cc97e0 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -135,7 +135,7 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::JustTransfer => { matches!(c, Call::Balances(pallet_balances::Call::transfer { .. })) - }, + } ProxyType::JustUtility => matches!(c, Call::Utility { .. }), } } @@ -208,7 +208,15 @@ fn call_transfer(dest: u64, value: u64) -> Call { fn announcement_works() { new_test_ext().execute_with(|| { assert_ok!(Proxy::add_proxy(Origin::signed(1), 3, ProxyType::Any, 1)); - System::assert_last_event(ProxyEvent::ProxyAdded(1, 3, ProxyType::Any, 1).into()); + System::assert_last_event( + ProxyEvent::ProxyAdded { + delegator: 1, + delegatee: 3, + proxy_type: ProxyType::Any, + delay: 1, + } + .into(), + ); assert_ok!(Proxy::add_proxy(Origin::signed(2), 3, ProxyType::Any, 1)); assert_eq!(Balances::reserved_balance(3), 0); @@ -329,11 +337,13 @@ fn filtering_works() { let call = Box::new(call_transfer(6, 1)); assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Ok(())).into()); + System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Ok(())).into()); + System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(DispatchError::BadOrigin)).into()); + System::assert_last_event( + ProxyEvent::ProxyExecuted { result: Err(DispatchError::BadOrigin) }.into(), + ); let derivative_id = Utility::derivative_account_id(1, 0); assert!(Balances::mutate_account(&derivative_id, |a| a.free = 1000).is_ok()); @@ -342,24 +352,30 @@ fn filtering_works() { let call = Box::new(Call::Utility(UtilityCall::as_derivative { index: 0, call: inner.clone() })); assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Ok(())).into()); + System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(DispatchError::BadOrigin)).into()); + System::assert_last_event( + ProxyEvent::ProxyExecuted { result: Err(DispatchError::BadOrigin) }.into(), + ); assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(DispatchError::BadOrigin)).into()); + System::assert_last_event( + ProxyEvent::ProxyExecuted { result: Err(DispatchError::BadOrigin) }.into(), + ); let call = Box::new(Call::Utility(UtilityCall::batch { calls: vec![*inner] })); assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); expect_events(vec![ UtilityEvent::BatchCompleted.into(), - ProxyEvent::ProxyExecuted(Ok(())).into(), + ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(DispatchError::BadOrigin)).into()); + System::assert_last_event( + ProxyEvent::ProxyExecuted { result: Err(DispatchError::BadOrigin) }.into(), + ); assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); expect_events(vec![ UtilityEvent::BatchInterrupted(0, DispatchError::BadOrigin).into(), - ProxyEvent::ProxyExecuted(Ok(())).into(), + ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); let inner = @@ -368,25 +384,31 @@ fn filtering_works() { assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); expect_events(vec![ UtilityEvent::BatchCompleted.into(), - ProxyEvent::ProxyExecuted(Ok(())).into(), + ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(DispatchError::BadOrigin)).into()); + System::assert_last_event( + ProxyEvent::ProxyExecuted { result: Err(DispatchError::BadOrigin) }.into(), + ); assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); expect_events(vec![ UtilityEvent::BatchInterrupted(0, DispatchError::BadOrigin).into(), - ProxyEvent::ProxyExecuted(Ok(())).into(), + ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); let call = Box::new(Call::Proxy(ProxyCall::remove_proxies {})); assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(DispatchError::BadOrigin)).into()); + System::assert_last_event( + ProxyEvent::ProxyExecuted { result: Err(DispatchError::BadOrigin) }.into(), + ); assert_ok!(Proxy::proxy(Origin::signed(4), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(DispatchError::BadOrigin)).into()); + System::assert_last_event( + ProxyEvent::ProxyExecuted { result: Err(DispatchError::BadOrigin) }.into(), + ); assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); expect_events(vec![ BalancesEvent::::Unreserved(1, 5).into(), - ProxyEvent::ProxyExecuted(Ok(())).into(), + ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); }); } @@ -457,20 +479,24 @@ fn proxying_works() { Error::::NotProxy ); assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Ok(())).into()); + System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); assert_eq!(Balances::free_balance(6), 1); let call = Box::new(Call::System(SystemCall::set_code { code: vec![] })); assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(DispatchError::BadOrigin)).into()); + System::assert_last_event( + ProxyEvent::ProxyExecuted { result: Err(DispatchError::BadOrigin) }.into(), + ); let call = Box::new(Call::Balances(BalancesCall::transfer_keep_alive { dest: 6, value: 1 })); assert_ok!(Call::Proxy(super::Call::new_call_variant_proxy(1, None, call.clone())) .dispatch(Origin::signed(2))); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(DispatchError::BadOrigin)).into()); + System::assert_last_event( + ProxyEvent::ProxyExecuted { result: Err(DispatchError::BadOrigin) }.into(), + ); assert_ok!(Proxy::proxy(Origin::signed(3), 1, None, call.clone())); - System::assert_last_event(ProxyEvent::ProxyExecuted(Ok(())).into()); + System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); assert_eq!(Balances::free_balance(6), 2); }); } @@ -481,7 +507,13 @@ fn anonymous_works() { assert_ok!(Proxy::anonymous(Origin::signed(1), ProxyType::Any, 0, 0)); let anon = Proxy::anonymous_account(&1, &ProxyType::Any, 0, None); System::assert_last_event( - ProxyEvent::AnonymousCreated(anon.clone(), 1, ProxyType::Any, 0).into(), + ProxyEvent::AnonymousCreated { + anonymous: anon.clone(), + who: 1, + proxy_type: ProxyType::Any, + disambiguation_index: 0, + } + .into(), ); // other calls to anonymous allowed as long as they're not exactly the same. @@ -502,7 +534,7 @@ fn anonymous_works() { let call = Box::new(call_transfer(6, 1)); assert_ok!(Balances::transfer(Origin::signed(3), anon, 5)); assert_ok!(Proxy::proxy(Origin::signed(1), anon, None, call)); - System::assert_last_event(ProxyEvent::ProxyExecuted(Ok(())).into()); + System::assert_last_event(ProxyEvent::ProxyExecuted { result: Ok(()) }.into()); assert_eq!(Balances::free_balance(6), 1); let call = Box::new(Call::Proxy(ProxyCall::new_call_variant_kill_anonymous( @@ -514,7 +546,7 @@ fn anonymous_works() { ))); assert_ok!(Proxy::proxy(Origin::signed(2), anon2, None, call.clone())); let de = DispatchError::from(Error::::NoPermission).stripped(); - System::assert_last_event(ProxyEvent::ProxyExecuted(Err(de)).into()); + System::assert_last_event(ProxyEvent::ProxyExecuted { result: Err(de) }.into()); assert_noop!( Proxy::kill_anonymous(Origin::signed(1), 1, ProxyType::Any, 0, 1, 0), Error::::NoPermission diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index ca9e15812a76d..590b50cedf7c8 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -296,9 +296,9 @@ pub mod pallet { // - It's priority is `HARD_DEADLINE` // - It does not push the weight past the limit. // - It is the first item in the schedule - if s.priority <= schedule::HARD_DEADLINE || - cumulative_weight <= limit || - order == 0 + if s.priority <= schedule::HARD_DEADLINE + || cumulative_weight <= limit + || order == 0 { let r = s.call.clone().dispatch(s.origin.clone().into()); let maybe_id = s.maybe_id.clone(); @@ -563,7 +563,7 @@ impl Pallet { }; if when <= now { - return Err(Error::::TargetBlockNumberInPast.into()) + return Err(Error::::TargetBlockNumberInPast.into()); } Ok(when) @@ -615,7 +615,7 @@ impl Pallet { |s| -> Result>, DispatchError> { if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) { if *o != s.origin { - return Err(BadOrigin.into()) + return Err(BadOrigin.into()); } }; Ok(s.take()) @@ -640,7 +640,7 @@ impl Pallet { let new_time = Self::resolve_time(new_time)?; if new_time == when { - return Err(Error::::RescheduleNoChange.into()) + return Err(Error::::RescheduleNoChange.into()); } Agenda::::try_mutate(when, |agenda| -> DispatchResult { @@ -667,7 +667,7 @@ impl Pallet { ) -> Result, DispatchError> { // ensure id it is unique if Lookup::::contains_key(&id) { - return Err(Error::::FailedToSchedule)? + return Err(Error::::FailedToSchedule)?; } let when = Self::resolve_time(when)?; @@ -710,7 +710,7 @@ impl Pallet { if let Some(s) = agenda.get_mut(i) { if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) { if *o != s.origin { - return Err(BadOrigin.into()) + return Err(BadOrigin.into()); } } *s = None; @@ -737,7 +737,7 @@ impl Pallet { let (when, index) = lookup.ok_or(Error::::NotFound)?; if new_time == when { - return Err(Error::::RescheduleNoChange.into()) + return Err(Error::::RescheduleNoChange.into()); } Agenda::::try_mutate(when, |agenda| -> DispatchResult { @@ -1439,9 +1439,9 @@ mod tests { let call_weight = MaximumSchedulerWeight::get() / 2; assert_eq!( actual_weight, - call_weight + - base_weight + base_multiplier + - named_multiplier + periodic_multiplier + call_weight + + base_weight + base_multiplier + + named_multiplier + periodic_multiplier ); assert_eq!(logger::log(), vec![(root(), 2600u32)]); diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index a5cdb6274f995..7397496114778 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -428,10 +428,12 @@ impl, I: 'static> Pallet { >::put(&new_members); match notify { - ChangeReceiver::MembershipInitialized => - T::MembershipInitialized::initialize_members(&new_members), - ChangeReceiver::MembershipChanged => - T::MembershipChanged::set_members_sorted(&new_members[..], &old_members[..]), + ChangeReceiver::MembershipInitialized => { + T::MembershipInitialized::initialize_members(&new_members) + } + ChangeReceiver::MembershipChanged => { + T::MembershipChanged::set_members_sorted(&new_members[..], &old_members[..]) + } } } diff --git a/frame/session/src/historical/mod.rs b/frame/session/src/historical/mod.rs index 0801b2aca1701..48aac50e40259 100644 --- a/frame/session/src/historical/mod.rs +++ b/frame/session/src/historical/mod.rs @@ -94,7 +94,7 @@ impl Module { let up_to = sp_std::cmp::min(up_to, end); if up_to < start { - return // out of bounds. harmless. + return; // out of bounds. harmless. } (start..up_to).for_each(::HistoricalSessions::remove); @@ -170,7 +170,7 @@ impl> NoteHi Err(reason) => { print("Failed to generate historical ancestry-inclusion proof."); print(reason); - }, + } }; } else { let previous_index = new_index.saturating_sub(1); @@ -341,7 +341,7 @@ impl> frame_support::traits::KeyOwnerProofSystem<(KeyT let count = >::validators().len() as ValidatorCount; if count != proof.validator_count { - return None + return None; } Some((owner, id)) @@ -351,7 +351,7 @@ impl> frame_support::traits::KeyOwnerProofSystem<(KeyT let (root, count) = >::get(&proof.session)?; if count != proof.validator_count { - return None + return None; } let trie = ProvingTrie::::from_nodes(root, &proof.trie_nodes); diff --git a/frame/session/src/historical/offchain.rs b/frame/session/src/historical/offchain.rs index b646ecc2764f7..f5fb921663dad 100644 --- a/frame/session/src/historical/offchain.rs +++ b/frame/session/src/historical/offchain.rs @@ -121,9 +121,9 @@ pub fn prune_older_than(first_to_keep: SessionIndex) { let _ = StorageValueRef::persistent(derived_key.as_ref()).clear(); } } - }, - Err(MutateStorageError::ConcurrentModification(_)) => {}, - Err(MutateStorageError::ValueFunctionFailed(_)) => {}, + } + Err(MutateStorageError::ConcurrentModification(_)) => {} + Err(MutateStorageError::ValueFunctionFailed(_)) => {} } } diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 7fe163e0dfeac..3321da359f1c1 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -675,7 +675,7 @@ impl Pallet { let mut now_session_keys = session_keys.iter(); let mut check_next_changed = |keys: &T::Keys| { if changed { - return + return; } // since a new validator set always leads to `changed` starting // as true, we can ensure that `now_session_keys` and `next_validators` @@ -683,7 +683,7 @@ impl Pallet { if let Some(&(_, ref old_keys)) = now_session_keys.next() { if old_keys != keys { changed = true; - return + return; } } }; @@ -712,14 +712,14 @@ impl Pallet { /// Disable the validator of index `i`, returns `false` if the validator was already disabled. pub fn disable_index(i: u32) -> bool { if i >= Validators::::decode_len().unwrap_or(0) as u32 { - return false + return false; } >::mutate(|disabled| { if let Err(index) = disabled.binary_search(&i) { disabled.insert(index, i); T::SessionHandler::on_disabled(i); - return true + return true; } false @@ -834,7 +834,7 @@ impl Pallet { if let Some(old) = old_keys.as_ref().map(|k| k.get_raw(*id)) { if key == old { - continue + continue; } Self::clear_key_owner(*id, old); diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index 6db7727fa5391..b611089373637 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -118,8 +118,8 @@ pub struct TestShouldEndSession; impl ShouldEndSession for TestShouldEndSession { fn should_end_session(now: u64) -> bool { let l = SESSION_LENGTH.with(|l| *l.borrow()); - now % l == 0 || - FORCE_SESSION_END.with(|l| { + now % l == 0 + || FORCE_SESSION_END.with(|l| { let r = *l.borrow(); *l.borrow_mut() = false; r diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 83b1c4203722b..92390a7cb180c 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -766,10 +766,10 @@ pub mod pallet { BidKind::Deposit(deposit) => { let err_amount = T::Currency::unreserve(&who, deposit); debug_assert!(err_amount.is_zero()); - }, + } BidKind::Vouch(voucher, _) => { >::remove(&voucher); - }, + } } Self::deposit_event(Event::::Unbid(who)); Ok(()) @@ -998,7 +998,7 @@ pub mod pallet { } else { >::insert(&who, payouts); } - return Ok(()) + return Ok(()); } } Err(Error::::NoPayout)? @@ -1195,10 +1195,10 @@ pub mod pallet { // Reduce next pot by payout >::put(pot - value); // Add payout for new candidate - let maturity = >::block_number() + - Self::lock_duration(Self::members().len() as u32); + let maturity = >::block_number() + + Self::lock_duration(Self::members().len() as u32); Self::pay_accepted_candidate(&who, value, kind, maturity); - }, + } Judgement::Reject => { // Founder has rejected this candidate match kind { @@ -1211,19 +1211,19 @@ pub mod pallet { BalanceStatus::Free, ); debug_assert!(res.is_ok()); - }, + } BidKind::Vouch(voucher, _) => { // Ban the voucher from vouching again >::insert(&voucher, VouchingStatus::Banned); - }, + } } - }, + } Judgement::Rebid => { // Founder has taken no judgement, and candidate is placed back into the // pool. let bids = >::get(); Self::put_bid(bids, &who, value, kind); - }, + } } // Remove suspended candidate @@ -1324,7 +1324,7 @@ impl, I: 'static> Pallet { } else { bids.push(Bid { value, who: who.clone(), kind: bid_kind }); } - }, + } Err(pos) => bids.insert(pos, Bid { value, who: who.clone(), kind: bid_kind }), } // Keep it reasonably small. @@ -1334,10 +1334,10 @@ impl, I: 'static> Pallet { BidKind::Deposit(deposit) => { let err_amount = T::Currency::unreserve(&popped, deposit); debug_assert!(err_amount.is_zero()); - }, + } BidKind::Vouch(voucher, _) => { >::remove(&voucher); - }, + } } Self::deposit_event(Event::::AutoUnbid(popped)); } @@ -1377,7 +1377,7 @@ impl, I: 'static> Pallet { T::MembershipChanged::change_members_sorted(&[who.clone()], &[], &members); >::put(members); Ok(()) - }, + } // User is already a member, do nothing. Ok(_) => Ok(()), } @@ -1399,7 +1399,7 @@ impl, I: 'static> Pallet { T::MembershipChanged::change_members_sorted(&[], &[m.clone()], &members[..]); >::put(members); Ok(()) - }, + } } } @@ -1426,8 +1426,8 @@ impl, I: 'static> Pallet { // out of society. members.reserve(candidates.len()); - let maturity = >::block_number() + - Self::lock_duration(members.len() as u32); + let maturity = >::block_number() + + Self::lock_duration(members.len() as u32); let mut rewardees = Vec::new(); let mut total_approvals = 0; @@ -1613,7 +1613,7 @@ impl, I: 'static> Pallet { // whole slash is accounted for. *amount -= rest; rest = Zero::zero(); - break + break; } } >::insert(who, &payouts[dropped..]); @@ -1656,7 +1656,7 @@ impl, I: 'static> Pallet { let err_amount = T::Currency::unreserve(candidate, deposit); debug_assert!(err_amount.is_zero()); value - }, + } BidKind::Vouch(voucher, tip) => { // Check that the voucher is still vouching, else some other logic may have removed // their status. @@ -1668,7 +1668,7 @@ impl, I: 'static> Pallet { } else { value } - }, + } }; Self::bump_payout(candidate, maturity, value); @@ -1786,7 +1786,7 @@ impl, I: 'static> Pallet { selected.push(bid.clone()); zero_selected = true; count += 1; - return false + return false; } } else { total_cost += bid.value; @@ -1794,7 +1794,7 @@ impl, I: 'static> Pallet { if total_cost <= pot { selected.push(bid.clone()); count += 1; - return false + return false; } } } diff --git a/frame/staking/reward-curve/src/lib.rs b/frame/staking/reward-curve/src/lib.rs index 06e35d11350e0..d46ede184fffb 100644 --- a/frame/staking/reward-curve/src/lib.rs +++ b/frame/staking/reward-curve/src/lib.rs @@ -87,7 +87,7 @@ pub fn build(input: TokenStream) -> TokenStream { Ok(FoundCrate::Name(sp_runtime)) => { let ident = syn::Ident::new(&sp_runtime, Span::call_site()); quote!( extern crate #ident as _sp_runtime; ) - }, + } Err(e) => syn::Error::new(Span::call_site(), e).to_compile_error(), }; @@ -136,10 +136,10 @@ struct Bounds { impl Bounds { fn check(&self, value: u32) -> bool { - let wrong = (self.min_strict && value <= self.min) || - (!self.min_strict && value < self.min) || - (self.max_strict && value >= self.max) || - (!self.max_strict && value > self.max); + let wrong = (self.min_strict && value <= self.min) + || (!self.min_strict && value < self.min) + || (self.max_strict && value >= self.max) + || (!self.max_strict && value > self.max); !wrong } @@ -175,7 +175,7 @@ fn parse_field( value, bounds, ), - )) + )); } Ok(value) @@ -196,7 +196,7 @@ impl Parse for INposInput { ::parse(input)?; if !input.is_empty() { - return Err(input.error("expected end of input stream, no token expected")) + return Err(input.error("expected end of input stream, no token expected")); } let min_inflation = parse_field::( @@ -231,7 +231,7 @@ impl Parse for INposInput { >::parse(&args_input)?; if !args_input.is_empty() { - return Err(args_input.error("expected end of input stream, no token expected")) + return Err(args_input.error("expected end of input stream, no token expected")); } Ok(Self { @@ -273,7 +273,7 @@ impl INPoS { // See web3 docs for the details fn compute_opposite_after_x_ideal(&self, y: u32) -> u32 { if y == self.i_0 { - return u32::MAX + return u32::MAX; } // Note: the log term calculated here represents a per_million value let log = log2(self.i_ideal_times_x_ideal - self.i_0, y - self.i_0); @@ -291,8 +291,8 @@ fn compute_points(input: &INposInput) -> Vec<(u32, u32)> { // For each point p: (next_p.0 - p.0) < segment_length && (next_p.1 - p.1) < segment_length. // This ensures that the total number of segment doesn't overflow max_piece_count. - let max_length = (input.max_inflation - input.min_inflation + 1_000_000 - inpos.x_ideal) / - (input.max_piece_count - 1); + let max_length = (input.max_inflation - input.min_inflation + 1_000_000 - inpos.x_ideal) + / (input.max_piece_count - 1); let mut delta_y = max_length; let mut y = input.max_inflation; @@ -304,29 +304,29 @@ fn compute_points(input: &INposInput) -> Vec<(u32, u32)> { if next_y <= input.min_inflation { delta_y = delta_y.saturating_sub(1); - continue + continue; } let next_x = inpos.compute_opposite_after_x_ideal(next_y); if (next_x - points.last().unwrap().0) > max_length { delta_y = delta_y.saturating_sub(1); - continue + continue; } if next_x >= 1_000_000 { let prev = points.last().unwrap(); // Compute the y corresponding to x=1_000_000 using the this point and the previous one. - let delta_y: u32 = ((next_x - 1_000_000) as u64 * (prev.1 - next_y) as u64 / - (next_x - prev.0) as u64) + let delta_y: u32 = ((next_x - 1_000_000) as u64 * (prev.1 - next_y) as u64 + / (next_x - prev.0) as u64) .try_into() .unwrap(); let y = next_y + delta_y; points.push((1_000_000, y)); - return points + return points; } points.push((next_x, next_y)); y = next_y; diff --git a/frame/staking/reward-curve/src/log.rs b/frame/staking/reward-curve/src/log.rs index c196aaaa31a93..8e71056b86e6b 100644 --- a/frame/staking/reward-curve/src/log.rs +++ b/frame/staking/reward-curve/src/log.rs @@ -41,7 +41,7 @@ pub fn log2(p: u32, q: u32) -> u32 { // log2(1) = 0 if p == q { - return 0 + return 0; } // find the power of 2 where q * 2^n <= p < q * 2^(n+1) @@ -61,7 +61,7 @@ pub fn log2(p: u32, q: u32) -> u32 { loop { let term = taylor_term(k, y_num.into(), y_den.into()); if term == 0 { - break + break; } res += term; diff --git a/frame/staking/reward-fn/src/lib.rs b/frame/staking/reward-fn/src/lib.rs index dd5e629b3984c..845b16702f011 100644 --- a/frame/staking/reward-fn/src/lib.rs +++ b/frame/staking/reward-fn/src/lib.rs @@ -55,12 +55,12 @@ use sp_arithmetic::{ pub fn compute_inflation(stake: P, ideal_stake: P, falloff: P) -> P { if stake < ideal_stake { // ideal_stake is more than 0 because it is strictly more than stake - return stake / ideal_stake + return stake / ideal_stake; } if falloff < P::from_percent(1.into()) { log::error!("Invalid inflation computation: falloff less than 1% is not supported"); - return PerThing::zero() + return PerThing::zero(); } let accuracy = { @@ -97,7 +97,7 @@ pub fn compute_inflation(stake: P, ideal_stake: P, falloff: P) -> P _ => { log::error!("Invalid inflation computation: unexpected result {:?}", res); P::zero() - }, + } } } @@ -131,7 +131,7 @@ fn compute_taylor_serie_part(p: &INPoSParam) -> BigUint { last_taylor_term = compute_taylor_term(k, &last_taylor_term, p); if last_taylor_term.is_zero() { - break + break; } let last_taylor_term_positive = k % 2 == 0; @@ -156,7 +156,7 @@ fn compute_taylor_serie_part(p: &INPoSParam) -> BigUint { } if !taylor_sum_positive { - return BigUint::zero() + return BigUint::zero(); } taylor_sum.lstrip(); @@ -198,15 +198,15 @@ fn div_by_stripped(mut a: BigUint, b: &BigUint) -> BigUint { if b.len() == 0 { log::error!("Computation error: Invalid division"); - return BigUint::zero() + return BigUint::zero(); } if b.len() == 1 { - return a.div_unit(b.checked_get(0).unwrap_or(1)) + return a.div_unit(b.checked_get(0).unwrap_or(1)); } if b.len() > a.len() { - return BigUint::zero() + return BigUint::zero(); } if b.len() == a.len() { @@ -220,7 +220,7 @@ fn div_by_stripped(mut a: BigUint, b: &BigUint) -> BigUint { .map(|res| res.0) .unwrap_or_else(|| BigUint::zero()) .div_unit(100_000) - .div_unit(100_000) + .div_unit(100_000); } a.div(b, false).map(|res| res.0).unwrap_or_else(|| BigUint::zero()) diff --git a/frame/staking/src/benchmarking.rs b/frame/staking/src/benchmarking.rs index 220e8f1e6a24c..ec91cf785bf72 100644 --- a/frame/staking/src/benchmarking.rs +++ b/frame/staking/src/benchmarking.rs @@ -50,7 +50,7 @@ const MAX_SLASHES: u32 = 1000; // read and write operations. fn add_slashing_spans(who: &T::AccountId, spans: u32) { if spans == 0 { - return + return; } // For the first slashing span, we initialize diff --git a/frame/staking/src/inflation.rs b/frame/staking/src/inflation.rs index 8e44a8c5482e5..8811f3514e57a 100644 --- a/frame/staking/src/inflation.rs +++ b/frame/staking/src/inflation.rs @@ -42,8 +42,8 @@ where const MILLISECONDS_PER_YEAR: u64 = 1000 * 3600 * 24 * 36525 / 100; let portion = Perbill::from_rational(era_duration as u64, MILLISECONDS_PER_YEAR); - let payout = portion * - yearly_inflation + let payout = portion + * yearly_inflation .calculate_for_fraction_times_denominator(npos_token_staked, total_tokens.clone()); let maximum = portion * (yearly_inflation.maximum * total_tokens); (payout, maximum) diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index be02e8d91d326..61aef8bf93638 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -498,7 +498,7 @@ impl } if unlocking_balance >= value { - break + break; } } diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 95d397359f8d6..a6137bd7b9614 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -585,7 +585,7 @@ fn check_nominators() { e.others.iter().filter(|e| e.who == nominator).collect::>(); let len = individual.len(); match len { - 0 => { /* not supporting this validator at all. */ }, + 0 => { /* not supporting this validator at all. */ } 1 => sum += individual[0].value, _ => panic!("nominator cannot back a validator more than once."), }; @@ -769,9 +769,9 @@ pub(crate) fn on_offence_in_era( for &(bonded_era, start_session) in bonded_eras.iter() { if bonded_era == era { let _ = Staking::on_offence(offenders, slash_fraction, start_session); - return + return; } else if bonded_era > era { - break + break; } } diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index 02099d8543d4c..2958d07ca8bcb 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -143,7 +143,7 @@ impl Pallet { // Nothing to do if they have no reward points. if validator_reward_points.is_zero() { - return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into()) + return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into()); } // This is the fraction of the total reward that the validator and the @@ -235,8 +235,9 @@ impl Pallet { Self::update_ledger(&controller, &l); r }), - RewardDestination::Account(dest_account) => - Some(T::Currency::deposit_creating(&dest_account, amount)), + RewardDestination::Account(dest_account) => { + Some(T::Currency::deposit_creating(&dest_account, amount)) + } RewardDestination::None => None, } } @@ -264,14 +265,14 @@ impl Pallet { _ => { // Either `Forcing::ForceNone`, // or `Forcing::NotForcing if era_length >= T::SessionsPerEra::get()`. - return None - }, + return None; + } } // New era. let maybe_new_era_validators = Self::try_trigger_new_era(session_index, is_genesis); - if maybe_new_era_validators.is_some() && - matches!(ForceEra::::get(), Forcing::ForceNew) + if maybe_new_era_validators.is_some() + && matches!(ForceEra::::get(), Forcing::ForceNew) { ForceEra::::put(Forcing::NotForcing); } @@ -457,12 +458,12 @@ impl Pallet { // TODO: this should be simplified #8911 CurrentEra::::put(0); ErasStartSessionIndex::::insert(&0, &start_session_index); - }, + } _ => (), } Self::deposit_event(Event::StakingElectionFailed); - return None + return None; } Self::deposit_event(Event::StakersElected); @@ -698,7 +699,7 @@ impl Pallet { Some(nominator) => { nominators_seen.saturating_inc(); nominator - }, + } None => break, }; @@ -876,7 +877,7 @@ impl ElectionDataProvider> for Pallet // We can't handle this case yet -- return an error. if maybe_max_len.map_or(false, |max_len| target_count > max_len as u32) { - return Err("Target snapshot too big") + return Err("Target snapshot too big"); } Ok(Self::get_npos_targets()) @@ -1142,7 +1143,7 @@ where add_db_reads_writes(1, 0); if active_era.is_none() { // This offence need not be re-submitted. - return consumed_weight + return consumed_weight; } active_era.expect("value checked not to be `None`; qed").index }; @@ -1188,7 +1189,7 @@ where // Skip if the validator is invulnerable. if invulnerables.contains(stash) { - continue + continue; } let unapplied = slashing::compute_slash::(slashing::SlashParams { diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index 8e97a90e07544..3ecae1a80f9a7 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -907,24 +907,23 @@ pub mod pallet { ledger = ledger.consolidate_unlocked(current_era) } - let post_info_weight = if ledger.unlocking.is_empty() && - ledger.active < T::Currency::minimum_balance() - { - // This account must have called `unbond()` with some value that caused the active - // portion to fall below existential deposit + will have no more unlocking chunks - // left. We can now safely remove all staking-related information. - Self::kill_stash(&stash, num_slashing_spans)?; - // Remove the lock. - T::Currency::remove_lock(STAKING_ID, &stash); - // This is worst case scenario, so we use the full weight and return None - None - } else { - // This was the consequence of a partial unbond. just update the ledger and move on. - Self::update_ledger(&controller, &ledger); + let post_info_weight = + if ledger.unlocking.is_empty() && ledger.active < T::Currency::minimum_balance() { + // This account must have called `unbond()` with some value that caused the active + // portion to fall below existential deposit + will have no more unlocking chunks + // left. We can now safely remove all staking-related information. + Self::kill_stash(&stash, num_slashing_spans)?; + // Remove the lock. + T::Currency::remove_lock(STAKING_ID, &stash); + // This is worst case scenario, so we use the full weight and return None + None + } else { + // This was the consequence of a partial unbond. just update the ledger and move on. + Self::update_ledger(&controller, &ledger); - // This is only an update, so we use less overall weight. - Some(T::WeightInfo::withdraw_unbonded_update(num_slashing_spans)) - }; + // This is only an update, so we use less overall weight. + Some(T::WeightInfo::withdraw_unbonded_update(num_slashing_spans)) + }; // `old_total` should never be less than the new total because // `consolidate_unlocked` strictly subtracts balance. diff --git a/frame/staking/src/slashing.rs b/frame/staking/src/slashing.rs index 68088d0e0d777..6fccf91fe3947 100644 --- a/frame/staking/src/slashing.rs +++ b/frame/staking/src/slashing.rs @@ -123,7 +123,7 @@ impl SlashingSpans { pub(crate) fn end_span(&mut self, now: EraIndex) -> bool { let next_start = now + 1; if next_start <= self.last_start { - return false + return false; } let last_length = next_start - self.last_start; @@ -170,7 +170,7 @@ impl SlashingSpans { self.prior.truncate(o); let new_earliest = self.span_index - self.prior.len() as SpanIndex; Some((earliest_span_index, new_earliest)) - }, + } None => None, }; @@ -236,7 +236,7 @@ pub(crate) fn compute_slash( // kick out the validator even if they won't be slashed, // as long as the misbehavior is from their most recent slashing span. kick_out_if_recent::(params); - return None + return None; } let (prior_slash_p, _era_slash) = @@ -255,7 +255,7 @@ pub(crate) fn compute_slash( // pays out some reward even if the latest report is not max-in-era. // we opt to avoid the nominator lookups and edits and leave more rewards // for more drastic misbehavior. - return None + return None; } // apply slash to validator. @@ -350,7 +350,7 @@ fn add_offending_validator(stash: &T::AccountId, disable: bool) { if disable { T::SessionInterface::disable_validator(validator_index_u32); } - }, + } Ok(index) => { if disable && !offending[index].1 { // the validator had previously offended without being disabled, @@ -358,7 +358,7 @@ fn add_offending_validator(stash: &T::AccountId, disable: bool) { offending[index].1 = true; T::SessionInterface::disable_validator(validator_index_u32); } - }, + } } }); } @@ -542,7 +542,7 @@ impl<'a, T: 'a + Config> Drop for InspectingSpans<'a, T> { fn drop(&mut self) { // only update on disk if we slashed this account. if !self.dirty { - return + return; } if let Some((start, end)) = self.spans.prune(self.window_start) { @@ -656,7 +656,7 @@ fn pay_reporters( // nobody to pay out to or nothing to pay; // just treat the whole value as slashed. T::Slash::on_unbalanced(slashed_imbalance); - return + return; } // take rewards out of the slashed imbalance. diff --git a/frame/staking/src/testing_utils.rs b/frame/staking/src/testing_utils.rs index 13762cf5886db..7ed7d97ebe4d9 100644 --- a/frame/staking/src/testing_utils.rs +++ b/frame/staking/src/testing_utils.rs @@ -85,7 +85,7 @@ pub fn create_stash_controller( amount, destination, )?; - return Ok((stash, controller)) + return Ok((stash, controller)); } /// Create a stash and controller pair with fixed balance. @@ -127,7 +127,7 @@ pub fn create_stash_and_dead_controller( amount, destination, )?; - return Ok((stash, controller)) + return Ok((stash, controller)); } /// create `max` validators. diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index d6d92d5bd57fc..0c71c6394a2d6 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -275,9 +275,9 @@ fn rewards_should_work() { assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2); assert_eq_error_rate!( Balances::total_balance(&100), - init_balance_100 + - part_for_100_from_10 * total_payout_0 * 2 / 3 + - part_for_100_from_20 * total_payout_0 * 1 / 3, + init_balance_100 + + part_for_100_from_10 * total_payout_0 * 2 / 3 + + part_for_100_from_20 * total_payout_0 * 1 / 3, 2 ); assert_eq_error_rate!(Balances::total_balance(&101), init_balance_101, 2); @@ -313,9 +313,9 @@ fn rewards_should_work() { assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2); assert_eq_error_rate!( Balances::total_balance(&100), - init_balance_100 + - part_for_100_from_10 * (total_payout_0 * 2 / 3 + total_payout_1) + - part_for_100_from_20 * total_payout_0 * 1 / 3, + init_balance_100 + + part_for_100_from_10 * (total_payout_0 * 2 / 3 + total_payout_1) + + part_for_100_from_20 * total_payout_0 * 1 / 3, 2 ); assert_eq_error_rate!(Balances::total_balance(&101), init_balance_101, 2); @@ -3985,8 +3985,8 @@ mod election_data_provider { #[test] fn targets_2sec_block() { let mut validators = 1000; - while ::WeightInfo::get_npos_targets(validators) < - 2 * frame_support::weights::constants::WEIGHT_PER_SECOND + while ::WeightInfo::get_npos_targets(validators) + < 2 * frame_support::weights::constants::WEIGHT_PER_SECOND { validators += 1; } @@ -4003,8 +4003,8 @@ mod election_data_provider { let slashing_spans = validators; let mut nominators = 1000; - while ::WeightInfo::get_npos_voters(validators, nominators, slashing_spans) < - 2 * frame_support::weights::constants::WEIGHT_PER_SECOND + while ::WeightInfo::get_npos_voters(validators, nominators, slashing_spans) + < 2 * frame_support::weights::constants::WEIGHT_PER_SECOND { nominators += 1; } @@ -4076,8 +4076,8 @@ mod election_data_provider { .build_and_execute(|| { // sum of all nominators who'd be voters (1), plus the self-votes (4). assert_eq!( - ::SortedListProvider::count() + - >::iter().count() as u32, + ::SortedListProvider::count() + + >::iter().count() as u32, 5 ); @@ -4116,8 +4116,8 @@ mod election_data_provider { // and total voters assert_eq!( - ::SortedListProvider::count() + - >::iter().count() as u32, + ::SortedListProvider::count() + + >::iter().count() as u32, 7 ); @@ -4161,8 +4161,8 @@ mod election_data_provider { // and total voters assert_eq!( - ::SortedListProvider::count() + - >::iter().count() as u32, + ::SortedListProvider::count() + + >::iter().count() as u32, 6 ); diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index 427455849bb00..fc6187bde7682 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -52,7 +52,7 @@ //! This is an example of a pallet that exposes a privileged function: //! //! ``` -//! +//! //! #[frame_support::pallet] //! pub mod logger { //! use frame_support::pallet_prelude::*; diff --git a/frame/support/procedural/src/clone_no_bound.rs b/frame/support/procedural/src/clone_no_bound.rs index 747900fd023f6..8810bd4fcc029 100644 --- a/frame/support/procedural/src/clone_no_bound.rs +++ b/frame/support/procedural/src/clone_no_bound.rs @@ -37,7 +37,7 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke }); quote::quote!( Self { #( #fields, )* } ) - }, + } syn::Fields::Unnamed(unnamed) => { let fields = unnamed.unnamed.iter().enumerate().map(|(i, _)| syn::Index::from(i)).map(|i| { @@ -47,10 +47,10 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke }); quote::quote!( Self ( #( #fields, )* ) ) - }, + } syn::Fields::Unit => { quote::quote!(Self) - }, + } }, syn::Data::Enum(enum_) => { let variants = enum_.variants.iter().map(|variant| { @@ -66,7 +66,7 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke quote::quote!( Self::#ident { #( ref #captured, )* } => Self::#ident { #( #cloned, )*} ) - }, + } syn::Fields::Unnamed(unnamed) => { let captured = unnamed .unnamed @@ -81,7 +81,7 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke quote::quote!( Self::#ident ( #( ref #captured, )* ) => Self::#ident ( #( #cloned, )*) ) - }, + } syn::Fields::Unit => quote::quote!( Self::#ident => Self::#ident ), } }); @@ -89,11 +89,11 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke quote::quote!(match self { #( #variants, )* }) - }, + } syn::Data::Union(_) => { let msg = "Union type not supported by `derive(CloneNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into() - }, + return syn::Error::new(input.span(), msg).to_compile_error().into(); + } }; quote::quote!( diff --git a/frame/support/procedural/src/construct_runtime/expand/event.rs b/frame/support/procedural/src/construct_runtime/expand/event.rs index 798646bf27334..4a62ab372f4b4 100644 --- a/frame/support/procedural/src/construct_runtime/expand/event.rs +++ b/frame/support/procedural/src/construct_runtime/expand/event.rs @@ -43,7 +43,7 @@ pub fn expand_outer_event( be constructed: pallet `{}` must have generic `Event`", pallet_name, ); - return Err(syn::Error::new(pallet_name.span(), msg)) + return Err(syn::Error::new(pallet_name.span(), msg)); } let part_is_generic = !generics.params.is_empty(); @@ -101,16 +101,16 @@ fn expand_event_variant( match instance { Some(inst) if part_is_generic => { quote!(#[codec(index = #index)] #variant_name(#path::Event<#runtime, #path::#inst>),) - }, + } Some(inst) => { quote!(#[codec(index = #index)] #variant_name(#path::Event<#path::#inst>),) - }, + } None if part_is_generic => { quote!(#[codec(index = #index)] #variant_name(#path::Event<#runtime>),) - }, + } None => { quote!(#[codec(index = #index)] #variant_name(#path::Event),) - }, + } } } diff --git a/frame/support/procedural/src/construct_runtime/expand/origin.rs b/frame/support/procedural/src/construct_runtime/expand/origin.rs index 57adf86a9fe18..fd822fcb55755 100644 --- a/frame/support/procedural/src/construct_runtime/expand/origin.rs +++ b/frame/support/procedural/src/construct_runtime/expand/origin.rs @@ -53,7 +53,7 @@ pub fn expand_outer_origin( be constructed: pallet `{}` must have generic `Origin`", name ); - return Err(syn::Error::new(name.span(), msg)) + return Err(syn::Error::new(name.span(), msg)); } caller_variants.extend(expand_origin_caller_variant( @@ -281,16 +281,16 @@ fn expand_origin_caller_variant( match instance { Some(inst) if part_is_generic => { quote!(#[codec(index = #index)] #variant_name(#path::Origin<#runtime, #path::#inst>),) - }, + } Some(inst) => { quote!(#[codec(index = #index)] #variant_name(#path::Origin<#path::#inst>),) - }, + } None if part_is_generic => { quote!(#[codec(index = #index)] #variant_name(#path::Origin<#runtime>),) - }, + } None => { quote!(#[codec(index = #index)] #variant_name(#path::Origin),) - }, + } } } diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index 863df34266591..d318955aa6535 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -84,7 +84,7 @@ fn complete_pallets(decl: impl Iterator) -> syn::Resul ); let mut err = syn::Error::new(used_pallet.span(), &msg); err.combine(syn::Error::new(pallet.name.span(), msg)); - return Err(err) + return Err(err); } if let Some(used_pallet) = names.insert(pallet.name.clone(), pallet.name.span()) { @@ -92,7 +92,7 @@ fn complete_pallets(decl: impl Iterator) -> syn::Resul let mut err = syn::Error::new(used_pallet, &msg); err.combine(syn::Error::new(pallet.name.span(), &msg)); - return Err(err) + return Err(err); } Ok(Pallet { diff --git a/frame/support/procedural/src/construct_runtime/parse.rs b/frame/support/procedural/src/construct_runtime/parse.rs index a0ec6dfa5803e..e68966aeb6d38 100644 --- a/frame/support/procedural/src/construct_runtime/parse.rs +++ b/frame/support/procedural/src/construct_runtime/parse.rs @@ -77,9 +77,9 @@ impl Parse for WhereSection { definitions.push(definition); if !input.peek(Token![,]) { if !input.peek(token::Brace) { - return Err(input.error("Expected `,` or `{`")) + return Err(input.error("Expected `,` or `{`")); } - break + break; } input.parse::()?; } @@ -92,7 +92,7 @@ impl Parse for WhereSection { "`{:?}` was declared above. Please use exactly one declaration for `{:?}`.", kind, kind ); - return Err(Error::new(*kind_span, msg)) + return Err(Error::new(*kind_span, msg)); } Ok(Self { block, node_block, unchecked_extrinsic }) } @@ -122,7 +122,7 @@ impl Parse for WhereDefinition { } else if lookahead.peek(keyword::UncheckedExtrinsic) { (input.parse::()?.span(), WhereKind::UncheckedExtrinsic) } else { - return Err(lookahead.error()) + return Err(lookahead.error()); }; Ok(Self { @@ -205,17 +205,17 @@ impl Parse for PalletPath { let mut lookahead = input.lookahead1(); let mut segments = Punctuated::new(); - if lookahead.peek(Token![crate]) || - lookahead.peek(Token![self]) || - lookahead.peek(Token![super]) || - lookahead.peek(Ident) + if lookahead.peek(Token![crate]) + || lookahead.peek(Token![self]) + || lookahead.peek(Token![super]) + || lookahead.peek(Ident) { let ident = input.call(Ident::parse_any)?; segments.push(PathSegment { ident, arguments: PathArguments::None }); let _: Token![::] = input.parse()?; lookahead = input.lookahead1(); } else { - return Err(lookahead.error()) + return Err(lookahead.error()); } while lookahead.peek(Ident) { @@ -226,7 +226,7 @@ impl Parse for PalletPath { } if !lookahead.peek(token::Brace) && !lookahead.peek(Token![<]) { - return Err(lookahead.error()) + return Err(lookahead.error()); } Ok(Self { inner: Path { leading_colon: None, segments } }) @@ -252,7 +252,7 @@ fn parse_pallet_parts(input: ParseStream) -> Result> { "`{}` was already declared before. Please remove the duplicate declaration", part.name(), ); - return Err(Error::new(part.keyword.span(), msg)) + return Err(Error::new(part.keyword.span(), msg)); } } @@ -357,7 +357,7 @@ impl Parse for PalletPart { keyword.name(), valid_generics, ); - return Err(syn::Error::new(keyword.span(), msg)) + return Err(syn::Error::new(keyword.span(), msg)); } Ok(Self { keyword, generics }) diff --git a/frame/support/procedural/src/crate_version.rs b/frame/support/procedural/src/crate_version.rs index cfa35c6190e15..02d54b8b5aca2 100644 --- a/frame/support/procedural/src/crate_version.rs +++ b/frame/support/procedural/src/crate_version.rs @@ -30,7 +30,7 @@ fn create_error(message: &str) -> Error { /// Implementation of the `crate_to_crate_version!` macro. pub fn crate_to_crate_version(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(create_error("No arguments expected!")) + return Err(create_error("No arguments expected!")); } let major_version = get_cargo_env_var::("CARGO_PKG_VERSION_MAJOR") diff --git a/frame/support/procedural/src/debug_no_bound.rs b/frame/support/procedural/src/debug_no_bound.rs index acfd8d0cabc8a..ad6753ebf48f8 100644 --- a/frame/support/procedural/src/debug_no_bound.rs +++ b/frame/support/procedural/src/debug_no_bound.rs @@ -40,7 +40,7 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke #( #fields )* .finish() ) - }, + } syn::Fields::Unnamed(unnamed) => { let fields = unnamed .unnamed @@ -54,7 +54,7 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke #( #fields )* .finish() ) - }, + } syn::Fields::Unit => quote::quote!(fmt.write_str(stringify!(#input_ident))), }, syn::Data::Enum(enum_) => { @@ -76,7 +76,7 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke .finish() } ) - }, + } syn::Fields::Unnamed(unnamed) => { let captured = unnamed .unnamed @@ -93,7 +93,7 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke .finish() } ) - }, + } syn::Fields::Unit => quote::quote!( Self::#ident => fmt.write_str(#full_variant_str) ), @@ -103,11 +103,11 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke quote::quote!(match *self { #( #variants, )* }) - }, + } syn::Data::Union(_) => { let msg = "Union type not supported by `derive(DebugNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into() - }, + return syn::Error::new(input.span(), msg).to_compile_error().into(); + } }; quote::quote!( diff --git a/frame/support/procedural/src/default_no_bound.rs b/frame/support/procedural/src/default_no_bound.rs index 38d6e19b1732f..2550326671b5f 100644 --- a/frame/support/procedural/src/default_no_bound.rs +++ b/frame/support/procedural/src/default_no_bound.rs @@ -37,7 +37,7 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To }); quote::quote!( Self { #( #fields, )* } ) - }, + } syn::Fields::Unnamed(unnamed) => { let fields = unnamed.unnamed.iter().enumerate().map(|(i, _)| syn::Index::from(i)).map(|i| { @@ -47,12 +47,12 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To }); quote::quote!( Self ( #( #fields, )* ) ) - }, + } syn::Fields::Unit => { quote::quote!(Self) - }, + } }, - syn::Data::Enum(enum_) => + syn::Data::Enum(enum_) => { if let Some(first_variant) = enum_.variants.first() { let variant_ident = &first_variant.ident; match &first_variant.fields { @@ -64,7 +64,7 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To }); quote::quote!( #name :: #ty_generics :: #variant_ident { #( #fields, )* } ) - }, + } syn::Fields::Unnamed(unnamed) => { let fields = unnamed .unnamed @@ -78,16 +78,17 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To }); quote::quote!( #name :: #ty_generics :: #variant_ident ( #( #fields, )* ) ) - }, + } syn::Fields::Unit => quote::quote!( #name :: #ty_generics :: #variant_ident ), } } else { quote::quote!(Self) - }, + } + } syn::Data::Union(_) => { let msg = "Union type not supported by `derive(CloneNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into() - }, + return syn::Error::new(input.span(), msg).to_compile_error().into(); + } }; quote::quote!( diff --git a/frame/support/procedural/src/dummy_part_checker.rs b/frame/support/procedural/src/dummy_part_checker.rs index 792b17a8f7758..0377fb04e778d 100644 --- a/frame/support/procedural/src/dummy_part_checker.rs +++ b/frame/support/procedural/src/dummy_part_checker.rs @@ -5,7 +5,7 @@ pub fn generate_dummy_part_checker(input: TokenStream) -> TokenStream { if !input.is_empty() { return syn::Error::new(proc_macro2::Span::call_site(), "No arguments expected") .to_compile_error() - .into() + .into(); } let count = COUNTER.with(|counter| counter.borrow_mut().inc()); diff --git a/frame/support/procedural/src/key_prefix.rs b/frame/support/procedural/src/key_prefix.rs index 3f424e8b8b8dd..53305e396f375 100644 --- a/frame/support/procedural/src/key_prefix.rs +++ b/frame/support/procedural/src/key_prefix.rs @@ -23,7 +23,7 @@ const MAX_IDENTS: usize = 18; pub fn impl_key_prefix_for_tuples(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + return Err(syn::Error::new(Span::call_site(), "No arguments expected")); } let mut all_trait_impls = TokenStream::new(); diff --git a/frame/support/procedural/src/pallet/expand/call.rs b/frame/support/procedural/src/pallet/expand/call.rs index 8f7bcdccaf22d..6baa5694b51ef 100644 --- a/frame/support/procedural/src/pallet/expand/call.rs +++ b/frame/support/procedural/src/pallet/expand/call.rs @@ -30,7 +30,7 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { let docs = call.docs.clone(); (span, where_clause, methods, docs) - }, + } None => (def.item.span(), None, Vec::new(), Vec::new()), }; let frame_support = &def.frame_support; diff --git a/frame/support/procedural/src/pallet/expand/event.rs b/frame/support/procedural/src/pallet/expand/event.rs index 625c2d98baac5..ac915817b8d79 100644 --- a/frame/support/procedural/src/pallet/expand/event.rs +++ b/frame/support/procedural/src/pallet/expand/event.rs @@ -55,7 +55,7 @@ pub fn expand_event(def: &mut Def) -> proc_macro2::TokenStream { #[doc(hidden)] pub use #macro_ident as is_event_part_defined; } - } + }; }; let event_where_clause = &event.where_clause; diff --git a/frame/support/procedural/src/pallet/expand/genesis_build.rs b/frame/support/procedural/src/pallet/expand/genesis_build.rs index 06acaf324254c..fce251948ecad 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_build.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_build.rs @@ -24,7 +24,7 @@ pub fn expand_genesis_build(def: &mut Def) -> proc_macro2::TokenStream { let genesis_config = if let Some(genesis_config) = &def.genesis_config { genesis_config } else { - return Default::default() + return Default::default(); }; let genesis_build = def.genesis_build.as_ref().expect("Checked by def parser"); diff --git a/frame/support/procedural/src/pallet/expand/genesis_config.rs b/frame/support/procedural/src/pallet/expand/genesis_config.rs index b2eb2166165cb..6562add2a51db 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_config.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_config.rs @@ -71,7 +71,7 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { #[doc(hidden)] pub use #std_macro_ident as is_std_enabled_for_genesis; } - } + }; }; let frame_support = &def.frame_support; @@ -82,9 +82,9 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { let serde_crate = format!("{}::serde", frame_support); match genesis_config_item { - syn::Item::Enum(syn::ItemEnum { attrs, .. }) | - syn::Item::Struct(syn::ItemStruct { attrs, .. }) | - syn::Item::Type(syn::ItemType { attrs, .. }) => { + syn::Item::Enum(syn::ItemEnum { attrs, .. }) + | syn::Item::Struct(syn::ItemStruct { attrs, .. }) + | syn::Item::Type(syn::ItemType { attrs, .. }) => { if get_doc_literals(&attrs).is_empty() { attrs.push(syn::parse_quote!( #[doc = r" @@ -103,7 +103,7 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { attrs.push(syn::parse_quote!( #[serde(bound(serialize = ""))] )); attrs.push(syn::parse_quote!( #[serde(bound(deserialize = ""))] )); attrs.push(syn::parse_quote!( #[serde(crate = #serde_crate)] )); - }, + } _ => unreachable!("Checked by genesis_config parser"), } diff --git a/frame/support/procedural/src/pallet/expand/hooks.rs b/frame/support/procedural/src/pallet/expand/hooks.rs index e0b7e3669da43..99a51387c13be 100644 --- a/frame/support/procedural/src/pallet/expand/hooks.rs +++ b/frame/support/procedural/src/pallet/expand/hooks.rs @@ -26,7 +26,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { let span = hooks.attr_span; let has_runtime_upgrade = hooks.has_runtime_upgrade; (where_clause, span, has_runtime_upgrade) - }, + } None => (None, def.pallet_struct.attr_span, false), }; diff --git a/frame/support/procedural/src/pallet/expand/storage.rs b/frame/support/procedural/src/pallet/expand/storage.rs index a4f030722f1c1..d3402de5301c3 100644 --- a/frame/support/procedural/src/pallet/expand/storage.rs +++ b/frame/support/procedural/src/pallet/expand/storage.rs @@ -60,7 +60,7 @@ fn check_prefix_duplicates( if let Some(other_dup_err) = used_prefixes.insert(prefix.clone(), dup_err.clone()) { let mut err = dup_err; err.combine(other_dup_err); - return Err(err) + return Err(err); } if let Metadata::CountedMap { .. } = storage_def.metadata { @@ -79,7 +79,7 @@ fn check_prefix_duplicates( { let mut err = counter_dup_err; err.combine(other_dup_err); - return Err(err) + return Err(err); } } @@ -135,7 +135,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(query_kind)); let on_empty = on_empty.unwrap_or_else(|| default_on_empty.clone()); args.args.push(syn::GenericArgument::Type(on_empty)); - }, + } StorageGenerics::Map { hasher, key, value, query_kind, on_empty, max_values } => { args.args.push(syn::GenericArgument::Type(hasher)); args.args.push(syn::GenericArgument::Type(key)); @@ -146,7 +146,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(on_empty)); let max_values = max_values.unwrap_or_else(|| default_max_values.clone()); args.args.push(syn::GenericArgument::Type(max_values)); - }, + } StorageGenerics::CountedMap { hasher, key, @@ -164,7 +164,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(on_empty)); let max_values = max_values.unwrap_or_else(|| default_max_values.clone()); args.args.push(syn::GenericArgument::Type(max_values)); - }, + } StorageGenerics::DoubleMap { hasher1, key1, @@ -186,7 +186,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(on_empty)); let max_values = max_values.unwrap_or_else(|| default_max_values.clone()); args.args.push(syn::GenericArgument::Type(max_values)); - }, + } StorageGenerics::NMap { keygen, value, query_kind, on_empty, max_values } => { args.args.push(syn::GenericArgument::Type(keygen)); args.args.push(syn::GenericArgument::Type(value)); @@ -196,7 +196,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(on_empty)); let max_values = max_values.unwrap_or_else(|| default_max_values.clone()); args.args.push(syn::GenericArgument::Type(max_values)); - }, + } } } else { args.args[0] = syn::parse_quote!( #prefix_ident<#type_use_gen> ); @@ -215,7 +215,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { /// * generate metadatas pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { if let Err(e) = process_generics(def) { - return e.into_compile_error().into() + return e.into_compile_error().into(); } // Check for duplicate prefixes @@ -226,7 +226,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { .filter_map(|storage_def| check_prefix_duplicates(storage_def, &mut prefix_set).err()); if let Some(mut final_error) = errors.next() { errors.for_each(|error| final_error.combine(error)); - return final_error.into_compile_error() + return final_error.into_compile_error(); } let frame_support = &def.frame_support; @@ -291,7 +291,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - }, + } Metadata::Map { key, value } => { let query = match storage.query_kind.as_ref().expect("Checked by def") { QueryKind::OptionQuery => quote::quote_spanned!(storage.attr_span => @@ -312,7 +312,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - }, + } Metadata::CountedMap { key, value } => { let query = match storage.query_kind.as_ref().expect("Checked by def") { QueryKind::OptionQuery => quote::quote_spanned!(storage.attr_span => @@ -333,7 +333,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - }, + } Metadata::DoubleMap { key1, key2, value } => { let query = match storage.query_kind.as_ref().expect("Checked by def") { QueryKind::OptionQuery => quote::quote_spanned!(storage.attr_span => @@ -356,7 +356,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - }, + } Metadata::NMap { keygen, value, .. } => { let query = match storage.query_kind.as_ref().expect("Checked by def") { QueryKind::OptionQuery => quote::quote_spanned!(storage.attr_span => @@ -382,7 +382,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - }, + } } } else { Default::default() diff --git a/frame/support/procedural/src/pallet/mod.rs b/frame/support/procedural/src/pallet/mod.rs index 93797906d04d9..2e2e7e8476160 100644 --- a/frame/support/procedural/src/pallet/mod.rs +++ b/frame/support/procedural/src/pallet/mod.rs @@ -40,7 +40,7 @@ pub fn pallet( "Invalid pallet macro call: expected no attributes, e.g. macro call must be just \ `#[frame_support::pallet]` or `#[pallet]`"; let span = proc_macro2::TokenStream::from(attr).span(); - return syn::Error::new(span, msg).to_compile_error().into() + return syn::Error::new(span, msg).to_compile_error().into(); } let item = syn::parse_macro_input!(item as syn::ItemMod); diff --git a/frame/support/procedural/src/pallet/parse/call.rs b/frame/support/procedural/src/pallet/parse/call.rs index 0563568f33311..e0ba5a8c3dd9a 100644 --- a/frame/support/procedural/src/pallet/parse/call.rs +++ b/frame/support/procedural/src/pallet/parse/call.rs @@ -130,7 +130,7 @@ impl CallDef { let item = if let syn::Item::Impl(item) = item { item } else { - return Err(syn::Error::new(item.span(), "Invalid pallet::call, expected item impl")) + return Err(syn::Error::new(item.span(), "Invalid pallet::call, expected item impl")); }; let mut instances = vec![]; @@ -140,7 +140,7 @@ impl CallDef { if let Some((_, _, for_)) = item.trait_ { let msg = "Invalid pallet::call, expected no trait ident as in \ `impl<..> Pallet<..> { .. }`"; - return Err(syn::Error::new(for_.span(), msg)) + return Err(syn::Error::new(for_.span(), msg)); } let mut methods = vec![]; @@ -155,22 +155,22 @@ impl CallDef { _ => method.vis.span(), }; - return Err(syn::Error::new(span, msg)) + return Err(syn::Error::new(span, msg)); } match method.sig.inputs.first() { None => { let msg = "Invalid pallet::call, must have at least origin arg"; - return Err(syn::Error::new(method.sig.span(), msg)) - }, + return Err(syn::Error::new(method.sig.span(), msg)); + } Some(syn::FnArg::Receiver(_)) => { let msg = "Invalid pallet::call, first argument must be a typed argument, \ e.g. `origin: OriginFor`"; - return Err(syn::Error::new(method.sig.span(), msg)) - }, + return Err(syn::Error::new(method.sig.span(), msg)); + } Some(syn::FnArg::Typed(arg)) => { check_dispatchable_first_arg_type(&*arg.ty)?; - }, + } } if let syn::ReturnType::Type(_, type_) = &method.sig.output { @@ -178,7 +178,7 @@ impl CallDef { } else { let msg = "Invalid pallet::call, require return type \ DispatchResultWithPostInfo"; - return Err(syn::Error::new(method.sig.span(), msg)) + return Err(syn::Error::new(method.sig.span(), msg)); } let mut call_var_attrs: Vec = @@ -190,7 +190,7 @@ impl CallDef { } else { "Invalid pallet::call, too many weight attributes given" }; - return Err(syn::Error::new(method.sig.span(), msg)) + return Err(syn::Error::new(method.sig.span(), msg)); } let weight = call_var_attrs.pop().unwrap().weight; @@ -207,14 +207,14 @@ impl CallDef { if arg_attrs.len() > 1 { let msg = "Invalid pallet::call, argument has too many attributes"; - return Err(syn::Error::new(arg.span(), msg)) + return Err(syn::Error::new(arg.span(), msg)); } let arg_ident = if let syn::Pat::Ident(pat) = &*arg.pat { pat.ident.clone() } else { let msg = "Invalid pallet::call, argument must be ident"; - return Err(syn::Error::new(arg.pat.span(), msg)) + return Err(syn::Error::new(arg.pat.span(), msg)); }; args.push((!arg_attrs.is_empty(), arg_ident, arg.ty.clone())); @@ -225,7 +225,7 @@ impl CallDef { methods.push(CallVariantDef { name: method.sig.ident.clone(), weight, args, docs }); } else { let msg = "Invalid pallet::call, only method accepted"; - return Err(syn::Error::new(impl_item.span(), msg)) + return Err(syn::Error::new(impl_item.span(), msg)); } } diff --git a/frame/support/procedural/src/pallet/parse/config.rs b/frame/support/procedural/src/pallet/parse/config.rs index 712c20ffc7b4c..b07c2ae602f84 100644 --- a/frame/support/procedural/src/pallet/parse/config.rs +++ b/frame/support/procedural/src/pallet/parse/config.rs @@ -226,7 +226,7 @@ fn check_event_type( if !type_.generics.params.is_empty() || type_.generics.where_clause.is_some() { let msg = "Invalid `type Event`, associated type `Event` is reserved and must have\ no generics nor where_clause"; - return Err(syn::Error::new(trait_item.span(), msg)) + return Err(syn::Error::new(trait_item.span(), msg)); } // Check bound contains IsType and From @@ -241,7 +241,7 @@ fn check_event_type( bound: `IsType<::Event>`", frame_system, ); - return Err(syn::Error::new(type_.span(), msg)) + return Err(syn::Error::new(type_.span(), msg)); } let from_event_bound = type_ @@ -254,7 +254,7 @@ fn check_event_type( } else { let msg = "Invalid `type Event`, associated type `Event` is reserved and must \ bound: `From` or `From>` or `From>`"; - return Err(syn::Error::new(type_.span(), msg)) + return Err(syn::Error::new(type_.span(), msg)); }; if from_event_bound.is_generic && (from_event_bound.has_instance != trait_has_instance) @@ -262,7 +262,7 @@ fn check_event_type( let msg = "Invalid `type Event`, associated type `Event` bounds inconsistent \ `From`. Config and generic Event must be both with instance or \ without instance"; - return Err(syn::Error::new(type_.span(), msg)) + return Err(syn::Error::new(type_.span(), msg)); } Ok(true) @@ -279,10 +279,12 @@ pub fn replace_self_by_t(input: proc_macro2::TokenStream) -> proc_macro2::TokenS input .into_iter() .map(|token_tree| match token_tree { - proc_macro2::TokenTree::Group(group) => - proc_macro2::Group::new(group.delimiter(), replace_self_by_t(group.stream())).into(), - proc_macro2::TokenTree::Ident(ident) if ident == "Self" => - proc_macro2::Ident::new("T", ident.span()).into(), + proc_macro2::TokenTree::Group(group) => { + proc_macro2::Group::new(group.delimiter(), replace_self_by_t(group.stream())).into() + } + proc_macro2::TokenTree::Ident(ident) if ident == "Self" => { + proc_macro2::Ident::new("T", ident.span()).into() + } other => other, }) .collect() @@ -299,12 +301,12 @@ impl ConfigDef { item } else { let msg = "Invalid pallet::config, expected trait definition"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); }; if !matches!(item.vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::config, trait must be public"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); } syn::parse2::(item.ident.to_token_stream())?; @@ -319,7 +321,7 @@ impl ConfigDef { if item.generics.params.len() > 1 { let msg = "Invalid pallet::config, expected no more than one generic"; - return Err(syn::Error::new(item.generics.params[2].span(), msg)) + return Err(syn::Error::new(item.generics.params[2].span(), msg)); } let has_instance = if item.generics.params.first().is_some() { @@ -341,7 +343,7 @@ impl ConfigDef { if type_attrs_const.len() > 1 { let msg = "Invalid attribute in pallet::config, only one attribute is expected"; - return Err(syn::Error::new(type_attrs_const[1].span(), msg)) + return Err(syn::Error::new(type_attrs_const[1].span(), msg)); } if type_attrs_const.len() == 1 { @@ -349,13 +351,13 @@ impl ConfigDef { syn::TraitItem::Type(ref type_) => { let constant = ConstMetadataDef::try_from(type_)?; consts_metadata.push(constant); - }, + } _ => { let msg = "Invalid pallet::constant in pallet::config, expected type trait \ item"; - return Err(syn::Error::new(trait_item.span(), msg)) - }, + return Err(syn::Error::new(trait_item.span(), msg)); + } } } } @@ -390,7 +392,7 @@ impl ConfigDef { To disable this check, use `#[pallet::disable_frame_system_supertrait_check]`", frame_system, found, ); - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); } Ok(Self { index, has_instance, consts_metadata, has_event_type, where_clause, attr_span }) diff --git a/frame/support/procedural/src/pallet/parse/error.rs b/frame/support/procedural/src/pallet/parse/error.rs index 9c9a95105c53c..3afa0da866f19 100644 --- a/frame/support/procedural/src/pallet/parse/error.rs +++ b/frame/support/procedural/src/pallet/parse/error.rs @@ -49,11 +49,11 @@ impl ErrorDef { let item = if let syn::Item::Enum(item) = item { item } else { - return Err(syn::Error::new(item.span(), "Invalid pallet::error, expected item enum")) + return Err(syn::Error::new(item.span(), "Invalid pallet::error, expected item enum")); }; if !matches!(item.vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::error, `Error` must be public"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); } let mut instances = vec![]; @@ -61,7 +61,7 @@ impl ErrorDef { if item.generics.where_clause.is_some() { let msg = "Invalid pallet::error, where clause is not allowed on pallet error item"; - return Err(syn::Error::new(item.generics.where_clause.as_ref().unwrap().span(), msg)) + return Err(syn::Error::new(item.generics.where_clause.as_ref().unwrap().span(), msg)); } let error = syn::parse2::(item.ident.to_token_stream())?; @@ -72,13 +72,13 @@ impl ErrorDef { .map(|variant| { if !matches!(variant.fields, syn::Fields::Unit) { let msg = "Invalid pallet::error, unexpected fields, must be `Unit`"; - return Err(syn::Error::new(variant.fields.span(), msg)) + return Err(syn::Error::new(variant.fields.span(), msg)); } if variant.discriminant.is_some() { let msg = "Invalid pallet::error, unexpected discriminant, discriminant \ are not supported"; let span = variant.discriminant.as_ref().unwrap().0.span(); - return Err(syn::Error::new(span, msg)) + return Err(syn::Error::new(span, msg)); } Ok((variant.ident.clone(), get_doc_literals(&variant.attrs))) diff --git a/frame/support/procedural/src/pallet/parse/event.rs b/frame/support/procedural/src/pallet/parse/event.rs index 33de4aca8b599..a728cd00e5242 100644 --- a/frame/support/procedural/src/pallet/parse/event.rs +++ b/frame/support/procedural/src/pallet/parse/event.rs @@ -87,7 +87,7 @@ impl PalletEventAttrInfo { if deposit_event.is_none() { deposit_event = Some(attr) } else { - return Err(syn::Error::new(attr.span, "Duplicate attribute")) + return Err(syn::Error::new(attr.span, "Duplicate attribute")); } } @@ -104,7 +104,7 @@ impl EventDef { let item = if let syn::Item::Enum(item) = item { item } else { - return Err(syn::Error::new(item.span(), "Invalid pallet::event, expected item enum")) + return Err(syn::Error::new(item.span(), "Invalid pallet::event, expected item enum")); }; let event_attrs: Vec = @@ -114,7 +114,7 @@ impl EventDef { if !matches!(item.vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::event, `Event` must be public"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); } let where_clause = item.generics.where_clause.clone(); diff --git a/frame/support/procedural/src/pallet/parse/extra_constants.rs b/frame/support/procedural/src/pallet/parse/extra_constants.rs index a5f3c0a8c2dab..9cf0642464267 100644 --- a/frame/support/procedural/src/pallet/parse/extra_constants.rs +++ b/frame/support/procedural/src/pallet/parse/extra_constants.rs @@ -84,7 +84,7 @@ impl ExtraConstantsDef { return Err(syn::Error::new( item.span(), "Invalid pallet::extra_constants, expected item impl", - )) + )); }; let mut instances = vec![]; @@ -94,7 +94,7 @@ impl ExtraConstantsDef { if let Some((_, _, for_)) = item.trait_ { let msg = "Invalid pallet::call, expected no trait ident as in \ `impl<..> Pallet<..> { .. }`"; - return Err(syn::Error::new(for_.span(), msg)) + return Err(syn::Error::new(for_.span(), msg)); } let mut extra_constants = vec![]; @@ -103,29 +103,29 @@ impl ExtraConstantsDef { method } else { let msg = "Invalid pallet::call, only method accepted"; - return Err(syn::Error::new(impl_item.span(), msg)) + return Err(syn::Error::new(impl_item.span(), msg)); }; if !method.sig.inputs.is_empty() { let msg = "Invalid pallet::extra_constants, method must have 0 args"; - return Err(syn::Error::new(method.sig.span(), msg)) + return Err(syn::Error::new(method.sig.span(), msg)); } if !method.sig.generics.params.is_empty() { let msg = "Invalid pallet::extra_constants, method must have 0 generics"; - return Err(syn::Error::new(method.sig.generics.params[0].span(), msg)) + return Err(syn::Error::new(method.sig.generics.params[0].span(), msg)); } if method.sig.generics.where_clause.is_some() { let msg = "Invalid pallet::extra_constants, method must have no where clause"; - return Err(syn::Error::new(method.sig.generics.where_clause.span(), msg)) + return Err(syn::Error::new(method.sig.generics.where_clause.span(), msg)); } let type_ = match &method.sig.output { syn::ReturnType::Default => { let msg = "Invalid pallet::extra_constants, method must have a return type"; - return Err(syn::Error::new(method.span(), msg)) - }, + return Err(syn::Error::new(method.span(), msg)); + } syn::ReturnType::Type(_, type_) => *type_.clone(), }; @@ -136,7 +136,7 @@ impl ExtraConstantsDef { if extra_constant_attrs.len() > 1 { let msg = "Invalid attribute in pallet::constant_name, only one attribute is expected"; - return Err(syn::Error::new(extra_constant_attrs[1].metadata_name.span(), msg)) + return Err(syn::Error::new(extra_constant_attrs[1].metadata_name.span(), msg)); } let metadata_name = extra_constant_attrs.pop().map(|attr| attr.metadata_name); diff --git a/frame/support/procedural/src/pallet/parse/genesis_build.rs b/frame/support/procedural/src/pallet/parse/genesis_build.rs index 82e297b4e26e8..80a41c3dcdd1c 100644 --- a/frame/support/procedural/src/pallet/parse/genesis_build.rs +++ b/frame/support/procedural/src/pallet/parse/genesis_build.rs @@ -40,7 +40,7 @@ impl GenesisBuildDef { item } else { let msg = "Invalid pallet::genesis_build, expected item impl"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); }; let item_trait = &item diff --git a/frame/support/procedural/src/pallet/parse/genesis_config.rs b/frame/support/procedural/src/pallet/parse/genesis_config.rs index a0cf7de1a846b..adcec0c625358 100644 --- a/frame/support/procedural/src/pallet/parse/genesis_config.rs +++ b/frame/support/procedural/src/pallet/parse/genesis_config.rs @@ -42,8 +42,8 @@ impl GenesisConfigDef { syn::Item::Struct(item) => (&item.vis, &item.ident, &item.generics), _ => { let msg = "Invalid pallet::genesis_config, expected enum or struct"; - return Err(syn::Error::new(item.span(), msg)) - }, + return Err(syn::Error::new(item.span(), msg)); + } }; let mut instances = vec![]; @@ -60,12 +60,12 @@ impl GenesisConfigDef { if !matches!(vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::genesis_config, GenesisConfig must be public"; - return Err(syn::Error::new(item_span, msg)) + return Err(syn::Error::new(item_span, msg)); } if ident != "GenesisConfig" { let msg = "Invalid pallet::genesis_config, ident must `GenesisConfig`"; - return Err(syn::Error::new(ident.span(), msg)) + return Err(syn::Error::new(ident.span(), msg)); } Ok(GenesisConfigDef { index, genesis_config: ident.clone(), instances, gen_kind }) diff --git a/frame/support/procedural/src/pallet/parse/helper.rs b/frame/support/procedural/src/pallet/parse/helper.rs index f5a7dc233cacb..4043302437cac 100644 --- a/frame/support/procedural/src/pallet/parse/helper.rs +++ b/frame/support/procedural/src/pallet/parse/helper.rs @@ -153,7 +153,7 @@ impl syn::parse::Parse for Unit { syn::parenthesized!(content in input); if !content.is_empty() { let msg = "unexpected tokens, expected nothing inside parenthesis as `()`"; - return Err(syn::Error::new(content.span(), msg)) + return Err(syn::Error::new(content.span(), msg)); } Ok(Self) } @@ -166,7 +166,7 @@ impl syn::parse::Parse for StaticLifetime { let lifetime = input.parse::()?; if lifetime.ident != "static" { let msg = "unexpected tokens, expected `static`"; - return Err(syn::Error::new(lifetime.ident.span(), msg)) + return Err(syn::Error::new(lifetime.ident.span(), msg)); } Ok(Self) } @@ -264,7 +264,7 @@ pub fn check_type_def_optional_gen( impl syn::parse::Parse for Checker { fn parse(input: syn::parse::ParseStream) -> syn::Result { if input.is_empty() { - return Ok(Self(None)) + return Ok(Self(None)); } let mut instance_usage = InstanceUsage { span: input.span(), has_instance: false }; @@ -272,7 +272,7 @@ pub fn check_type_def_optional_gen( input.parse::()?; if input.is_empty() { - return Ok(Self(Some(instance_usage))) + return Ok(Self(Some(instance_usage))); } let lookahead = input.lookahead1(); @@ -289,7 +289,7 @@ pub fn check_type_def_optional_gen( input.parse::()?; if input.is_empty() { - return Ok(Self(Some(instance_usage))) + return Ok(Self(Some(instance_usage))); } instance_usage.has_instance = true; @@ -431,7 +431,7 @@ pub fn check_type_def_gen( input.parse::()?; if input.is_empty() { - return Ok(Self(instance_usage)) + return Ok(Self(instance_usage)); } let lookahead = input.lookahead1(); @@ -448,7 +448,7 @@ pub fn check_type_def_gen( input.parse::()?; if input.is_empty() { - return Ok(Self(instance_usage)) + return Ok(Self(instance_usage)); } instance_usage.has_instance = true; @@ -539,7 +539,7 @@ pub fn check_type_value_gen( impl syn::parse::Parse for Checker { fn parse(input: syn::parse::ParseStream) -> syn::Result { if input.is_empty() { - return Ok(Self(None)) + return Ok(Self(None)); } input.parse::()?; @@ -549,7 +549,7 @@ pub fn check_type_value_gen( let mut instance_usage = InstanceUsage { span: input.span(), has_instance: false }; if input.is_empty() { - return Ok(Self(Some(instance_usage))) + return Ok(Self(Some(instance_usage))); } instance_usage.has_instance = true; diff --git a/frame/support/procedural/src/pallet/parse/hooks.rs b/frame/support/procedural/src/pallet/parse/hooks.rs index 1dd86498f22d5..0c9032d5dba65 100644 --- a/frame/support/procedural/src/pallet/parse/hooks.rs +++ b/frame/support/procedural/src/pallet/parse/hooks.rs @@ -42,7 +42,7 @@ impl HooksDef { item } else { let msg = "Invalid pallet::hooks, expected item impl"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); }; let mut instances = vec![]; @@ -66,7 +66,7 @@ impl HooksDef { quote::quote!(#item_trait) ); - return Err(syn::Error::new(item_trait.span(), msg)) + return Err(syn::Error::new(item_trait.span(), msg)); } let has_runtime_upgrade = item.items.iter().any(|i| match i { diff --git a/frame/support/procedural/src/pallet/parse/inherent.rs b/frame/support/procedural/src/pallet/parse/inherent.rs index de5ad8f795db5..02415afb57737 100644 --- a/frame/support/procedural/src/pallet/parse/inherent.rs +++ b/frame/support/procedural/src/pallet/parse/inherent.rs @@ -32,22 +32,22 @@ impl InherentDef { item } else { let msg = "Invalid pallet::inherent, expected item impl"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); }; if item.trait_.is_none() { let msg = "Invalid pallet::inherent, expected impl<..> ProvideInherent for Pallet<..>"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); } if let Some(last) = item.trait_.as_ref().unwrap().1.segments.last() { if last.ident != "ProvideInherent" { let msg = "Invalid pallet::inherent, expected trait ProvideInherent"; - return Err(syn::Error::new(last.span(), msg)) + return Err(syn::Error::new(last.span(), msg)); } } else { let msg = "Invalid pallet::inherent, expected impl<..> ProvideInherent for Pallet<..>"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); } let mut instances = vec![]; diff --git a/frame/support/procedural/src/pallet/parse/mod.rs b/frame/support/procedural/src/pallet/parse/mod.rs index 96d4776e805bc..da6af5e78f65a 100644 --- a/frame/support/procedural/src/pallet/parse/mod.rs +++ b/frame/support/procedural/src/pallet/parse/mod.rs @@ -95,49 +95,58 @@ impl Def { let pallet_attr: Option = helper::take_first_item_pallet_attr(item)?; match pallet_attr { - Some(PalletAttr::Config(span)) if config.is_none() => - config = Some(config::ConfigDef::try_from(&frame_system, span, index, item)?), + Some(PalletAttr::Config(span)) if config.is_none() => { + config = Some(config::ConfigDef::try_from(&frame_system, span, index, item)?) + } Some(PalletAttr::Pallet(span)) if pallet_struct.is_none() => { let p = pallet_struct::PalletStructDef::try_from(span, index, item)?; pallet_struct = Some(p); - }, + } Some(PalletAttr::Hooks(span)) if hooks.is_none() => { let m = hooks::HooksDef::try_from(span, index, item)?; hooks = Some(m); - }, - Some(PalletAttr::Call(span)) if call.is_none() => - call = Some(call::CallDef::try_from(span, index, item)?), - Some(PalletAttr::Error(span)) if error.is_none() => - error = Some(error::ErrorDef::try_from(span, index, item)?), - Some(PalletAttr::Event(span)) if event.is_none() => - event = Some(event::EventDef::try_from(span, index, item)?), + } + Some(PalletAttr::Call(span)) if call.is_none() => { + call = Some(call::CallDef::try_from(span, index, item)?) + } + Some(PalletAttr::Error(span)) if error.is_none() => { + error = Some(error::ErrorDef::try_from(span, index, item)?) + } + Some(PalletAttr::Event(span)) if event.is_none() => { + event = Some(event::EventDef::try_from(span, index, item)?) + } Some(PalletAttr::GenesisConfig(_)) if genesis_config.is_none() => { let g = genesis_config::GenesisConfigDef::try_from(index, item)?; genesis_config = Some(g); - }, + } Some(PalletAttr::GenesisBuild(span)) if genesis_build.is_none() => { let g = genesis_build::GenesisBuildDef::try_from(span, index, item)?; genesis_build = Some(g); - }, - Some(PalletAttr::Origin(_)) if origin.is_none() => - origin = Some(origin::OriginDef::try_from(index, item)?), - Some(PalletAttr::Inherent(_)) if inherent.is_none() => - inherent = Some(inherent::InherentDef::try_from(index, item)?), - Some(PalletAttr::Storage(span)) => - storages.push(storage::StorageDef::try_from(span, index, item)?), + } + Some(PalletAttr::Origin(_)) if origin.is_none() => { + origin = Some(origin::OriginDef::try_from(index, item)?) + } + Some(PalletAttr::Inherent(_)) if inherent.is_none() => { + inherent = Some(inherent::InherentDef::try_from(index, item)?) + } + Some(PalletAttr::Storage(span)) => { + storages.push(storage::StorageDef::try_from(span, index, item)?) + } Some(PalletAttr::ValidateUnsigned(_)) if validate_unsigned.is_none() => { let v = validate_unsigned::ValidateUnsignedDef::try_from(index, item)?; validate_unsigned = Some(v); - }, - Some(PalletAttr::TypeValue(span)) => - type_values.push(type_value::TypeValueDef::try_from(span, index, item)?), - Some(PalletAttr::ExtraConstants(_)) => + } + Some(PalletAttr::TypeValue(span)) => { + type_values.push(type_value::TypeValueDef::try_from(span, index, item)?) + } + Some(PalletAttr::ExtraConstants(_)) => { extra_constants = - Some(extra_constants::ExtraConstantsDef::try_from(index, item)?), + Some(extra_constants::ExtraConstantsDef::try_from(index, item)?) + } Some(attr) => { let msg = "Invalid duplicated attribute"; - return Err(syn::Error::new(attr.span(), msg)) - }, + return Err(syn::Error::new(attr.span(), msg)); + } None => (), } } @@ -150,7 +159,7 @@ impl Def { genesis_config.as_ref().map_or("unused", |_| "used"), genesis_build.as_ref().map_or("unused", |_| "used"), ); - return Err(syn::Error::new(item_span, msg)) + return Err(syn::Error::new(item_span, msg)); } let def = Def { @@ -190,13 +199,13 @@ impl Def { but enum `Event` is not declared (i.e. no use of `#[pallet::event]`). \ Note that type `Event` in trait is reserved to work alongside pallet event."; Err(syn::Error::new(proc_macro2::Span::call_site(), msg)) - }, + } (false, true) => { let msg = "Invalid usage of Event, `Config` contains no associated type \ `Event`, but enum `Event` is declared (in use of `#[pallet::event]`). \ An Event associated type must be declare on trait `Config`."; Err(syn::Error::new(proc_macro2::Span::call_site(), msg)) - }, + } _ => Ok(()), } } @@ -237,7 +246,7 @@ impl Def { let mut errors = instances.into_iter().filter_map(|instances| { if instances.has_instance == self.config.has_instance { - return None + return None; } let msg = if self.config.has_instance { "Invalid generic declaration, trait is defined with instance but generic use none" @@ -352,7 +361,7 @@ impl GenericKind { GenericKind::Config => quote::quote_spanned!(span => T: Config), GenericKind::ConfigAndInstance => { quote::quote_spanned!(span => T: Config, I: 'static) - }, + } } } diff --git a/frame/support/procedural/src/pallet/parse/origin.rs b/frame/support/procedural/src/pallet/parse/origin.rs index c4e1197ac511c..1135da4dbdd5c 100644 --- a/frame/support/procedural/src/pallet/parse/origin.rs +++ b/frame/support/procedural/src/pallet/parse/origin.rs @@ -42,8 +42,8 @@ impl OriginDef { syn::Item::Type(item) => (&item.vis, &item.ident, &item.generics), _ => { let msg = "Invalid pallet::origin, expected enum or struct or type"; - return Err(syn::Error::new(item.span(), msg)) - }, + return Err(syn::Error::new(item.span(), msg)); + } }; let has_instance = generics.params.len() == 2; @@ -59,12 +59,12 @@ impl OriginDef { if !matches!(vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::origin, Origin must be public"; - return Err(syn::Error::new(item_span, msg)) + return Err(syn::Error::new(item_span, msg)); } if ident != "Origin" { let msg = "Invalid pallet::origin, ident must `Origin`"; - return Err(syn::Error::new(ident.span(), msg)) + return Err(syn::Error::new(ident.span(), msg)); } Ok(OriginDef { index, has_instance, is_generic, instances }) diff --git a/frame/support/procedural/src/pallet/parse/pallet_struct.rs b/frame/support/procedural/src/pallet/parse/pallet_struct.rs index 278f46e13818e..6a7e8de314096 100644 --- a/frame/support/procedural/src/pallet/parse/pallet_struct.rs +++ b/frame/support/procedural/src/pallet/parse/pallet_struct.rs @@ -113,7 +113,7 @@ impl PalletStructDef { item } else { let msg = "Invalid pallet::pallet, expected struct definition"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); }; let mut store = None; @@ -125,7 +125,7 @@ impl PalletStructDef { match attr { PalletStructAttr::GenerateStore { vis, keyword, .. } if store.is_none() => { store = Some((vis, keyword)); - }, + } PalletStructAttr::GenerateStorageInfoTrait(span) if generate_storage_info.is_none() => { @@ -138,8 +138,8 @@ impl PalletStructDef { } attr => { let msg = "Unexpected duplicated attribute"; - return Err(syn::Error::new(attr.span(), msg)) - }, + return Err(syn::Error::new(attr.span(), msg)); + } } } @@ -147,12 +147,12 @@ impl PalletStructDef { if !matches!(item.vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::pallet, Pallet must be public"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); } if item.generics.where_clause.is_some() { let msg = "Invalid pallet::pallet, where clause not supported on Pallet declaration"; - return Err(syn::Error::new(item.generics.where_clause.span(), msg)) + return Err(syn::Error::new(item.generics.where_clause.span(), msg)); } let mut instances = vec![]; diff --git a/frame/support/procedural/src/pallet/parse/storage.rs b/frame/support/procedural/src/pallet/parse/storage.rs index cd29baf93d849..0d67cc5da2af3 100644 --- a/frame/support/procedural/src/pallet/parse/storage.rs +++ b/frame/support/procedural/src/pallet/parse/storage.rs @@ -103,14 +103,16 @@ impl PalletStorageAttrInfo { for attr in attrs { match attr { PalletStorageAttr::Getter(ident, ..) if getter.is_none() => getter = Some(ident), - PalletStorageAttr::StorageName(name, ..) if rename_as.is_none() => - rename_as = Some(name), + PalletStorageAttr::StorageName(name, ..) if rename_as.is_none() => { + rename_as = Some(name) + } PalletStorageAttr::Unbounded(..) if !unbounded => unbounded = true, - attr => + attr => { return Err(syn::Error::new( attr.attr_span(), "Invalid attribute: Duplicate attribute", - )), + )) + } } } @@ -222,8 +224,9 @@ impl StorageGenerics { Self::Map { value, key, .. } => Metadata::Map { value, key }, Self::CountedMap { value, key, .. } => Metadata::CountedMap { value, key }, Self::Value { value, .. } => Metadata::Value { value }, - Self::NMap { keygen, value, .. } => - Metadata::NMap { keys: collect_keys(&keygen)?, keygen, value }, + Self::NMap { keygen, value, .. } => { + Metadata::NMap { keys: collect_keys(&keygen)?, keygen, value } + } }; Ok(res) @@ -232,11 +235,11 @@ impl StorageGenerics { /// Return the query kind from the defined generics fn query_kind(&self) -> Option { match &self { - Self::DoubleMap { query_kind, .. } | - Self::Map { query_kind, .. } | - Self::CountedMap { query_kind, .. } | - Self::Value { query_kind, .. } | - Self::NMap { query_kind, .. } => query_kind.clone(), + Self::DoubleMap { query_kind, .. } + | Self::Map { query_kind, .. } + | Self::CountedMap { query_kind, .. } + | Self::Value { query_kind, .. } + | Self::NMap { query_kind, .. } => query_kind.clone(), } } } @@ -277,8 +280,8 @@ fn check_generics( }; for (gen_name, gen_binding) in map { - if !mandatory_generics.contains(&gen_name.as_str()) && - !optional_generics.contains(&gen_name.as_str()) + if !mandatory_generics.contains(&gen_name.as_str()) + && !optional_generics.contains(&gen_name.as_str()) { let msg = format!( "Invalid pallet::storage, Unexpected generic `{}` for `{}`. {}", @@ -323,7 +326,7 @@ fn process_named_generics( let msg = "Invalid pallet::storage, Duplicated named generic"; let mut err = syn::Error::new(arg.ident.span(), msg); err.combine(syn::Error::new(other.ident.span(), msg)); - return Err(err) + return Err(err); } parsed.insert(arg.ident.to_string(), arg.clone()); } @@ -346,7 +349,7 @@ fn process_named_generics( query_kind: parsed.remove("QueryKind").map(|binding| binding.ty), on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), } - }, + } StorageKind::Map => { check_generics( &parsed, @@ -373,7 +376,7 @@ fn process_named_generics( on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), max_values: parsed.remove("MaxValues").map(|binding| binding.ty), } - }, + } StorageKind::CountedMap => { check_generics( &parsed, @@ -400,7 +403,7 @@ fn process_named_generics( on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), max_values: parsed.remove("MaxValues").map(|binding| binding.ty), } - }, + } StorageKind::DoubleMap => { check_generics( &parsed, @@ -435,7 +438,7 @@ fn process_named_generics( on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), max_values: parsed.remove("MaxValues").map(|binding| binding.ty), } - }, + } StorageKind::NMap => { check_generics( &parsed, @@ -458,7 +461,7 @@ fn process_named_generics( on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), max_values: parsed.remove("MaxValues").map(|binding| binding.ty), } - }, + } }; let metadata = generics.metadata()?; @@ -495,8 +498,9 @@ fn process_unnamed_generics( })?; let res = match storage { - StorageKind::Value => - (None, Metadata::Value { value: retrieve_arg(1)? }, retrieve_arg(2).ok()), + StorageKind::Value => { + (None, Metadata::Value { value: retrieve_arg(1)? }, retrieve_arg(2).ok()) + } StorageKind::Map => ( None, Metadata::Map { key: retrieve_arg(2)?, value: retrieve_arg(3)? }, @@ -520,7 +524,7 @@ fn process_unnamed_generics( let keygen = retrieve_arg(1)?; let keys = collect_keys(&keygen)?; (None, Metadata::NMap { keys, keygen, value: retrieve_arg(2)? }, retrieve_arg(3).ok()) - }, + } }; Ok(res) @@ -543,8 +547,8 @@ fn process_generics( found `{}`.", found, ); - return Err(syn::Error::new(segment.ident.span(), msg)) - }, + return Err(syn::Error::new(segment.ident.span(), msg)); + } }; let args_span = segment.arguments.span(); @@ -554,8 +558,8 @@ fn process_generics( _ => { let msg = "Invalid pallet::storage, invalid number of generic generic arguments, \ expect more that 0 generic arguments."; - return Err(syn::Error::new(segment.span(), msg)) - }, + return Err(syn::Error::new(segment.span(), msg)); + } }; if args.args.iter().all(|gen| matches!(gen, syn::GenericArgument::Type(_))) { @@ -601,7 +605,7 @@ fn extract_key(ty: &syn::Type) -> syn::Result { typ } else { let msg = "Invalid pallet::storage, expected type path"; - return Err(syn::Error::new(ty.span(), msg)) + return Err(syn::Error::new(ty.span(), msg)); }; let key_struct = typ.path.segments.last().ok_or_else(|| { @@ -610,14 +614,14 @@ fn extract_key(ty: &syn::Type) -> syn::Result { })?; if key_struct.ident != "Key" && key_struct.ident != "NMapKey" { let msg = "Invalid pallet::storage, expected Key or NMapKey struct"; - return Err(syn::Error::new(key_struct.ident.span(), msg)) + return Err(syn::Error::new(key_struct.ident.span(), msg)); } let ty_params = if let syn::PathArguments::AngleBracketed(args) = &key_struct.arguments { args } else { let msg = "Invalid pallet::storage, expected angle bracketed arguments"; - return Err(syn::Error::new(key_struct.arguments.span(), msg)) + return Err(syn::Error::new(key_struct.arguments.span(), msg)); }; if ty_params.args.len() != 2 { @@ -626,15 +630,15 @@ fn extract_key(ty: &syn::Type) -> syn::Result { for Key struct, expected 2 args, found {}", ty_params.args.len() ); - return Err(syn::Error::new(ty_params.span(), msg)) + return Err(syn::Error::new(ty_params.span(), msg)); } let key = match &ty_params.args[1] { syn::GenericArgument::Type(key_ty) => key_ty.clone(), _ => { let msg = "Invalid pallet::storage, expected type"; - return Err(syn::Error::new(ty_params.args[1].span(), msg)) - }, + return Err(syn::Error::new(ty_params.args[1].span(), msg)); + } }; Ok(key) @@ -663,7 +667,7 @@ impl StorageDef { let item = if let syn::Item::Type(item) = item { item } else { - return Err(syn::Error::new(item.span(), "Invalid pallet::storage, expect item type.")) + return Err(syn::Error::new(item.span(), "Invalid pallet::storage, expect item type.")); }; let attrs: Vec = helper::take_item_pallet_attrs(&mut item.attrs)?; @@ -682,12 +686,12 @@ impl StorageDef { typ } else { let msg = "Invalid pallet::storage, expected type path"; - return Err(syn::Error::new(item.ty.span(), msg)) + return Err(syn::Error::new(item.ty.span(), msg)); }; if typ.path.segments.len() != 1 { let msg = "Invalid pallet::storage, expected type path with one segment"; - return Err(syn::Error::new(item.ty.span(), msg)) + return Err(syn::Error::new(item.ty.span(), msg)); } let (named_generics, metadata, query_kind) = process_generics(&typ.path.segments[0])?; @@ -696,10 +700,14 @@ impl StorageDef { .map(|query_kind| match query_kind { syn::Type::Path(path) if path.path.segments.last().map_or(false, |s| s.ident == "OptionQuery") => - Some(QueryKind::OptionQuery), + { + Some(QueryKind::OptionQuery) + } syn::Type::Path(path) if path.path.segments.last().map_or(false, |s| s.ident == "ValueQuery") => - Some(QueryKind::ValueQuery), + { + Some(QueryKind::ValueQuery) + } _ => None, }) .unwrap_or(Some(QueryKind::OptionQuery)); // This value must match the default generic. @@ -708,7 +716,7 @@ impl StorageDef { let msg = "Invalid pallet::storage, cannot generate getter because QueryKind is not \ identifiable. QueryKind must be `OptionQuery`, `ValueQuery`, or default one to be \ identifiable."; - return Err(syn::Error::new(getter.unwrap().span(), msg)) + return Err(syn::Error::new(getter.unwrap().span(), msg)); } Ok(StorageDef { diff --git a/frame/support/procedural/src/pallet/parse/type_value.rs b/frame/support/procedural/src/pallet/parse/type_value.rs index 7b9d57472db4b..1d575abf22b42 100644 --- a/frame/support/procedural/src/pallet/parse/type_value.rs +++ b/frame/support/procedural/src/pallet/parse/type_value.rs @@ -50,12 +50,12 @@ impl TypeValueDef { item } else { let msg = "Invalid pallet::type_value, expected item fn"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); }; if !item.attrs.is_empty() { let msg = "Invalid pallet::type_value, unexpected attribute"; - return Err(syn::Error::new(item.attrs[0].span(), msg)) + return Err(syn::Error::new(item.attrs[0].span(), msg)); } if let Some(span) = item @@ -69,12 +69,12 @@ impl TypeValueDef { .or_else(|| item.sig.variadic.as_ref().map(|t| t.span())) { let msg = "Invalid pallet::type_value, unexpected token"; - return Err(syn::Error::new(span, msg)) + return Err(syn::Error::new(span, msg)); } if !item.sig.inputs.is_empty() { let msg = "Invalid pallet::type_value, unexpected argument"; - return Err(syn::Error::new(item.sig.inputs[0].span(), msg)) + return Err(syn::Error::new(item.sig.inputs[0].span(), msg)); } let vis = item.vis.clone(); @@ -84,8 +84,8 @@ impl TypeValueDef { syn::ReturnType::Type(_, type_) => type_, syn::ReturnType::Default => { let msg = "Invalid pallet::type_value, expected return type"; - return Err(syn::Error::new(item.sig.span(), msg)) - }, + return Err(syn::Error::new(item.sig.span(), msg)); + } }; let mut instances = vec![]; diff --git a/frame/support/procedural/src/pallet/parse/validate_unsigned.rs b/frame/support/procedural/src/pallet/parse/validate_unsigned.rs index 87e2a326f1862..a376bb962e96c 100644 --- a/frame/support/procedural/src/pallet/parse/validate_unsigned.rs +++ b/frame/support/procedural/src/pallet/parse/validate_unsigned.rs @@ -32,24 +32,24 @@ impl ValidateUnsignedDef { item } else { let msg = "Invalid pallet::validate_unsigned, expected item impl"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); }; if item.trait_.is_none() { let msg = "Invalid pallet::validate_unsigned, expected impl<..> ValidateUnsigned for \ Pallet<..>"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); } if let Some(last) = item.trait_.as_ref().unwrap().1.segments.last() { if last.ident != "ValidateUnsigned" { let msg = "Invalid pallet::validate_unsigned, expected trait ValidateUnsigned"; - return Err(syn::Error::new(last.span(), msg)) + return Err(syn::Error::new(last.span(), msg)); } } else { let msg = "Invalid pallet::validate_unsigned, expected impl<..> ValidateUnsigned for \ Pallet<..>"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(item.span(), msg)); } let mut instances = vec![]; diff --git a/frame/support/procedural/src/partial_eq_no_bound.rs b/frame/support/procedural/src/partial_eq_no_bound.rs index 3dbabf3f5d39a..325c8890032d0 100644 --- a/frame/support/procedural/src/partial_eq_no_bound.rs +++ b/frame/support/procedural/src/partial_eq_no_bound.rs @@ -37,7 +37,7 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: .map(|i| quote::quote_spanned!(i.span() => self.#i == other.#i )); quote::quote!( true #( && #fields )* ) - }, + } syn::Fields::Unnamed(unnamed) => { let fields = unnamed .unnamed @@ -47,10 +47,10 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: .map(|i| quote::quote_spanned!(i.span() => self.#i == other.#i )); quote::quote!( true #( && #fields )* ) - }, + } syn::Fields::Unit => { quote::quote!(true) - }, + } }, syn::Data::Enum(enum_) => { let variants = @@ -77,7 +77,7 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: Self::#ident { #( #other_capture, )* }, ) => true #( && #eq )* ) - }, + } syn::Fields::Unnamed(unnamed) => { let names = unnamed .unnamed @@ -97,7 +97,7 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: Self::#ident ( #( #other_names, )* ), ) => true #( && #eq )* ) - }, + } syn::Fields::Unit => quote::quote!( (Self::#ident, Self::#ident) => true ), } }); @@ -119,11 +119,11 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: #( #variants, )* #( #different_variants, )* }) - }, + } syn::Data::Union(_) => { let msg = "Union type not supported by `derive(PartialEqNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into() - }, + return syn::Error::new(input.span(), msg).to_compile_error().into(); + } }; quote::quote!( diff --git a/frame/support/procedural/src/storage/genesis_config/builder_def.rs b/frame/support/procedural/src/storage/genesis_config/builder_def.rs index 001cea0f2b788..31e98f16347d8 100644 --- a/frame/support/procedural/src/storage/genesis_config/builder_def.rs +++ b/frame/support/procedural/src/storage/genesis_config/builder_def.rs @@ -60,7 +60,7 @@ impl BuilderDef { let data = builder(self); let data = Option::as_ref(&data); ) - }, + } _ => quote_spanned!(builder.span() => // NOTE: the type of `data` is specified when used later in the code let builder: fn(&Self) -> _ = #builder; @@ -73,7 +73,7 @@ impl BuilderDef { data = Some(match &line.storage_type { StorageLineTypeDef::Simple(_) if line.is_option => { quote!( let data = Some(&self.#config); ) - }, + } _ => quote!( let data = &self.#config; ), }); }; @@ -88,14 +88,14 @@ impl BuilderDef { <#storage_struct as #scrate::#storage_trait>::put::<&#value_type>(v); } }} - }, + } StorageLineTypeDef::Simple(_) if !line.is_option => { quote! {{ #data let v: &#value_type = data; <#storage_struct as #scrate::#storage_trait>::put::<&#value_type>(v); }} - }, + } StorageLineTypeDef::Simple(_) => unreachable!(), StorageLineTypeDef::Map(map) => { let key = &map.key; @@ -108,7 +108,7 @@ impl BuilderDef { >(k, v); }); }} - }, + } StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; @@ -121,7 +121,7 @@ impl BuilderDef { >(k1, k2, v); }); }} - }, + } StorageLineTypeDef::NMap(map) => { let key_tuple = map.to_key_tuple(); let key_arg = if map.keys.len() == 1 { quote!((k,)) } else { quote!(k) }; @@ -132,7 +132,7 @@ impl BuilderDef { <#storage_struct as #scrate::#storage_trait>::insert(#key_arg, v); }); }} - }, + } }); } } diff --git a/frame/support/procedural/src/storage/genesis_config/genesis_config_def.rs b/frame/support/procedural/src/storage/genesis_config/genesis_config_def.rs index fbdaab06b4895..478da660f2316 100644 --- a/frame/support/procedural/src/storage/genesis_config/genesis_config_def.rs +++ b/frame/support/procedural/src/storage/genesis_config/genesis_config_def.rs @@ -95,17 +95,17 @@ impl GenesisConfigDef { StorageLineTypeDef::Map(map) => { let key = &map.key; parse_quote!( Vec<(#key, #value_type)> ) - }, + } StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; parse_quote!( Vec<(#key1, #key2, #value_type)> ) - }, + } StorageLineTypeDef::NMap(map) => { let key_tuple = map.to_key_tuple(); parse_quote!( Vec<(#key_tuple, #value_type)> ) - }, + } }; let default = @@ -138,7 +138,7 @@ impl GenesisConfigDef { return Err(syn::Error::new( meta.span(), "extra genesis config items do not support `cfg` attribute", - )) + )); } Ok(meta) }) diff --git a/frame/support/procedural/src/storage/getters.rs b/frame/support/procedural/src/storage/getters.rs index 988e6fa096243..cf33165bbcee0 100644 --- a/frame/support/procedural/src/storage/getters.rs +++ b/frame/support/procedural/src/storage/getters.rs @@ -43,7 +43,7 @@ pub fn impl_getters(def: &DeclStorageDefExt) -> TokenStream { <#storage_struct as #scrate::#storage_trait>::get() } } - }, + } StorageLineTypeDef::Map(map) => { let key = &map.key; let value = &map.value; @@ -53,7 +53,7 @@ pub fn impl_getters(def: &DeclStorageDefExt) -> TokenStream { <#storage_struct as #scrate::#storage_trait>::get(key) } } - }, + } StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; @@ -67,7 +67,7 @@ pub fn impl_getters(def: &DeclStorageDefExt) -> TokenStream { <#storage_struct as #scrate::#storage_trait>::get(k1, k2) } } - }, + } StorageLineTypeDef::NMap(map) => { let keygen = map.to_keygen_struct(&def.hidden_crate); let value = &map.value; @@ -82,7 +82,7 @@ pub fn impl_getters(def: &DeclStorageDefExt) -> TokenStream { <#storage_struct as #scrate::#storage_trait>::get(key) } } - }, + } }; getters.extend(getter); } diff --git a/frame/support/procedural/src/storage/metadata.rs b/frame/support/procedural/src/storage/metadata.rs index a90e5051c5b2e..e685d3d095ffc 100644 --- a/frame/support/procedural/src/storage/metadata.rs +++ b/frame/support/procedural/src/storage/metadata.rs @@ -31,7 +31,7 @@ fn storage_line_metadata_type(scrate: &TokenStream, line: &StorageLineDefExt) -> #scrate::scale_info::meta_type::<#value_type>() ) } - }, + } StorageLineTypeDef::Map(map) => { let hasher = map.hasher.into_metadata(); let key = &map.key; @@ -42,7 +42,7 @@ fn storage_line_metadata_type(scrate: &TokenStream, line: &StorageLineDefExt) -> value: #scrate::scale_info::meta_type::<#value_type>(), } } - }, + } StorageLineTypeDef::DoubleMap(map) => { let hasher1 = map.hasher1.into_metadata(); let hasher2 = map.hasher2.into_metadata(); @@ -58,7 +58,7 @@ fn storage_line_metadata_type(scrate: &TokenStream, line: &StorageLineDefExt) -> value: #scrate::scale_info::meta_type::<#value_type>(), } } - }, + } StorageLineTypeDef::NMap(map) => { let key_tuple = &map.to_key_tuple(); let hashers = map @@ -75,7 +75,7 @@ fn storage_line_metadata_type(scrate: &TokenStream, line: &StorageLineDefExt) -> value: #scrate::scale_info::meta_type::<#value_type>(), } } - }, + } } } diff --git a/frame/support/procedural/src/storage/mod.rs b/frame/support/procedural/src/storage/mod.rs index 27964d7012a28..5d5b19b195a18 100644 --- a/frame/support/procedural/src/storage/mod.rs +++ b/frame/support/procedural/src/storage/mod.rs @@ -258,20 +258,24 @@ impl StorageLineDefExt { hidden_crate: &proc_macro2::TokenStream, ) -> Self { let is_generic = match &storage_def.storage_type { - StorageLineTypeDef::Simple(value) => - ext::type_contains_ident(&value, &def.module_runtime_generic), - StorageLineTypeDef::Map(map) => - ext::type_contains_ident(&map.key, &def.module_runtime_generic) || - ext::type_contains_ident(&map.value, &def.module_runtime_generic), - StorageLineTypeDef::DoubleMap(map) => - ext::type_contains_ident(&map.key1, &def.module_runtime_generic) || - ext::type_contains_ident(&map.key2, &def.module_runtime_generic) || - ext::type_contains_ident(&map.value, &def.module_runtime_generic), - StorageLineTypeDef::NMap(map) => + StorageLineTypeDef::Simple(value) => { + ext::type_contains_ident(&value, &def.module_runtime_generic) + } + StorageLineTypeDef::Map(map) => { + ext::type_contains_ident(&map.key, &def.module_runtime_generic) + || ext::type_contains_ident(&map.value, &def.module_runtime_generic) + } + StorageLineTypeDef::DoubleMap(map) => { + ext::type_contains_ident(&map.key1, &def.module_runtime_generic) + || ext::type_contains_ident(&map.key2, &def.module_runtime_generic) + || ext::type_contains_ident(&map.value, &def.module_runtime_generic) + } + StorageLineTypeDef::NMap(map) => { map.keys .iter() - .any(|key| ext::type_contains_ident(key, &def.module_runtime_generic)) || - ext::type_contains_ident(&map.value, &def.module_runtime_generic), + .any(|key| ext::type_contains_ident(key, &def.module_runtime_generic)) + || ext::type_contains_ident(&map.value, &def.module_runtime_generic) + } }; let query_type = match &storage_def.storage_type { @@ -309,20 +313,20 @@ impl StorageLineDefExt { let storage_trait_truncated = match &storage_def.storage_type { StorageLineTypeDef::Simple(_) => { quote!( StorageValue<#value_type> ) - }, + } StorageLineTypeDef::Map(map) => { let key = &map.key; quote!( StorageMap<#key, #value_type> ) - }, + } StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; quote!( StorageDoubleMap<#key1, #key2, #value_type> ) - }, + } StorageLineTypeDef::NMap(map) => { let keygen = map.to_keygen_struct(hidden_crate); quote!( StorageNMap<#keygen, #value_type> ) - }, + } }; let storage_trait = quote!( storage::#storage_trait_truncated ); @@ -394,7 +398,7 @@ impl NMapDef { if self.keys.len() == 1 { let hasher = &self.hashers[0].to_storage_hasher_struct(); let key = &self.keys[0]; - return quote!( #scrate::storage::types::Key<#scrate::#hasher, #key> ) + return quote!( #scrate::storage::types::Key<#scrate::#hasher, #key> ); } let key_hasher = self @@ -412,7 +416,7 @@ impl NMapDef { fn to_key_tuple(&self) -> proc_macro2::TokenStream { if self.keys.len() == 1 { let key = &self.keys[0]; - return quote!(#key) + return quote!(#key); } let tuple = self.keys.iter().map(|key| quote!(#key)).collect::>(); diff --git a/frame/support/procedural/src/storage/parse.rs b/frame/support/procedural/src/storage/parse.rs index 3a11846181a8f..cad5bfec25de1 100644 --- a/frame/support/procedural/src/storage/parse.rs +++ b/frame/support/procedural/src/storage/parse.rs @@ -367,16 +367,17 @@ fn get_module_instance( it is now defined at frame_support::traits::Instance. Expect `Instance` found `{}`", instantiable.as_ref().unwrap(), ); - return Err(syn::Error::new(instantiable.span(), msg)) + return Err(syn::Error::new(instantiable.span(), msg)); } match (instance, instantiable, default_instance) { - (Some(instance), Some(instantiable), default_instance) => + (Some(instance), Some(instantiable), default_instance) => { Ok(Some(super::ModuleInstanceDef { instance_generic: instance, instance_trait: instantiable, instance_default: default_instance, - })), + })) + } (None, None, None) => Ok(None), (Some(instance), None, _) => Err(syn::Error::new( instance.span(), @@ -424,17 +425,17 @@ pub fn parse(input: syn::parse::ParseStream) -> syn::Result { if extra_genesis_build.is_some() { return Err(syn::Error::new( def.span(), "Only one build expression allowed for extra genesis", - )) + )); } extra_genesis_build = Some(def.expr.content); - }, + } } } @@ -476,7 +477,7 @@ fn parse_storage_line_defs( "Invalid storage definition, couldn't find config identifier: storage must \ either have a get identifier `get(fn ident)` or a defined config identifier \ `config(ident)`", - )) + )); } } else { None @@ -498,16 +499,18 @@ fn parse_storage_line_defs( } let max_values = match &line.storage_type { - DeclStorageType::Map(_) | DeclStorageType::DoubleMap(_) | DeclStorageType::NMap(_) => - line.max_values.inner.map(|i| i.expr.content), - DeclStorageType::Simple(_) => + DeclStorageType::Map(_) | DeclStorageType::DoubleMap(_) | DeclStorageType::NMap(_) => { + line.max_values.inner.map(|i| i.expr.content) + } + DeclStorageType::Simple(_) => { if let Some(max_values) = line.max_values.inner { let msg = "unexpected max_values attribute for storage value."; let span = max_values.max_values_keyword.span(); - return Err(syn::Error::new(span, msg)) + return Err(syn::Error::new(span, msg)); } else { Some(syn::parse_quote!(1u32)) - }, + } + } }; let span = line.storage_type.span(); @@ -524,14 +527,15 @@ fn parse_storage_line_defs( key: map.key, value: map.value, }), - DeclStorageType::DoubleMap(map) => + DeclStorageType::DoubleMap(map) => { super::StorageLineTypeDef::DoubleMap(Box::new(super::DoubleMapDef { hasher1: map.hasher1.inner.ok_or_else(no_hasher_error)?.into(), hasher2: map.hasher2.inner.ok_or_else(no_hasher_error)?.into(), key1: map.key1, key2: map.key2, value: map.value, - })), + })) + } DeclStorageType::NMap(map) => super::StorageLineTypeDef::NMap(super::NMapDef { hashers: map .storage_keys diff --git a/frame/support/procedural/src/storage/print_pallet_upgrade.rs b/frame/support/procedural/src/storage/print_pallet_upgrade.rs index 03f09a7edb48e..3361b65f96516 100644 --- a/frame/support/procedural/src/storage/print_pallet_upgrade.rs +++ b/frame/support/procedural/src/storage/print_pallet_upgrade.rs @@ -26,7 +26,7 @@ fn to_cleaned_string(t: impl quote::ToTokens) -> String { /// Print an incomplete upgrade from decl_storage macro to new pallet attribute. pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { if !check_print_pallet_upgrade() { - return + return; } let scrate = "e::quote!(frame_support); @@ -58,8 +58,8 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { Ok(g) => g, Err(err) => { println!("Could not print upgrade due compile error: {:?}", err); - return - }, + return; + } }; let genesis_config_impl_gen = @@ -216,7 +216,7 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { comma_query_kind = comma_query_kind, comma_default_value_getter_name = comma_default_value_getter_name, ) - }, + } StorageLineTypeDef::DoubleMap(double_map) => { format!( "StorageDoubleMap<_, {hasher1}, {key1}, {hasher2}, {key2}, {value_type}\ @@ -229,7 +229,7 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { comma_query_kind = comma_query_kind, comma_default_value_getter_name = comma_default_value_getter_name, ) - }, + } StorageLineTypeDef::NMap(map) => { format!( "StorageNMap<_, {keygen}, {value_type}{comma_query_kind}\ @@ -239,7 +239,7 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { comma_query_kind = comma_query_kind, comma_default_value_getter_name = comma_default_value_getter_name, ) - }, + } StorageLineTypeDef::Simple(_) => { format!( "StorageValue<_, {value_type}{comma_query_kind}\ @@ -248,7 +248,7 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { comma_query_kind = comma_query_kind, comma_default_value_getter_name = comma_default_value_getter_name, ) - }, + } }; let additional_comment = if line.is_option && line.default_value.is_some() { diff --git a/frame/support/procedural/src/storage/storage_struct.rs b/frame/support/procedural/src/storage/storage_struct.rs index b318225681c1d..83d4a8ce55283 100644 --- a/frame/support/procedural/src/storage/storage_struct.rs +++ b/frame/support/procedural/src/storage/storage_struct.rs @@ -120,7 +120,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } StorageLineTypeDef::Map(map) => { let hasher = map.hasher.to_storage_hasher_struct(); quote!( @@ -159,7 +159,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } StorageLineTypeDef::DoubleMap(map) => { let hasher1 = map.hasher1.to_storage_hasher_struct(); let hasher2 = map.hasher2.to_storage_hasher_struct(); @@ -202,7 +202,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } StorageLineTypeDef::NMap(_) => { quote!( impl<#impl_trait> #scrate::storage::StoragePrefixedMap<#value_type> @@ -239,7 +239,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } }; let max_values = if let Some(max_values) = &line.max_values { @@ -286,7 +286,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } StorageLineTypeDef::Map(map) => { let key = &map.key; quote!( @@ -330,7 +330,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; @@ -380,7 +380,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } StorageLineTypeDef::NMap(map) => { let key = &map.to_keygen_struct(scrate); quote!( @@ -423,7 +423,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } } } else { // Implement `__partial_storage_info` which doesn't require MaxEncodedLen on keys and @@ -456,7 +456,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } StorageLineTypeDef::Map(_) => { quote!( impl<#impl_trait> #scrate::traits::PartialStorageInfoTrait @@ -487,7 +487,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } StorageLineTypeDef::DoubleMap(_) => { quote!( impl<#impl_trait> #scrate::traits::PartialStorageInfoTrait @@ -518,7 +518,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } StorageLineTypeDef::NMap(_) => { quote!( impl<#impl_trait> #scrate::traits::PartialStorageInfoTrait @@ -549,7 +549,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - }, + } } }; diff --git a/frame/support/procedural/tools/src/lib.rs b/frame/support/procedural/tools/src/lib.rs index d7aba4c7cbf1c..98e44a7dbe4a8 100644 --- a/frame/support/procedural/tools/src/lib.rs +++ b/frame/support/procedural/tools/src/lib.rs @@ -54,7 +54,7 @@ pub fn generate_crate_access_2018(def_crate: &str) -> Result Ok(FoundCrate::Itself) => { let name = def_crate.to_string().replace("-", "_"); Ok(syn::Ident::new(&name, Span::call_site())) - }, + } Ok(FoundCrate::Name(name)) => Ok(Ident::new(&name, Span::call_site())), Err(e) => Err(Error::new(Span::call_site(), e)), } @@ -74,11 +74,11 @@ pub fn generate_hidden_includes(unique_id: &str, def_crate: &str) -> TokenStream pub extern crate #name as hidden_include; } ) - }, + } Err(e) => { let err = Error::new(Span::call_site(), e).to_compile_error(); quote!( #err ) - }, + } } } diff --git a/frame/support/procedural/tools/src/syn_ext.rs b/frame/support/procedural/tools/src/syn_ext.rs index a9e9ef573985f..b5c9c549f4811 100644 --- a/frame/support/procedural/tools/src/syn_ext.rs +++ b/frame/support/procedural/tools/src/syn_ext.rs @@ -170,7 +170,7 @@ pub fn extract_type_option(typ: &syn::Type) -> Option { // Option has only one type argument in angle bracket. if let syn::PathArguments::AngleBracketed(a) = &v.arguments { if let syn::GenericArgument::Type(typ) = a.args.last()? { - return Some(typ.clone()) + return Some(typ.clone()); } } } @@ -190,7 +190,7 @@ impl<'ast> ContainsIdent<'ast> { stream.into_iter().for_each(|tt| match tt { TokenTree::Ident(id) => self.visit_ident(&id), TokenTree::Group(ref group) => self.visit_tokenstream(group.stream()), - _ => {}, + _ => {} }) } diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index a492bc12f6a38..99fa190d4b11d 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -2648,7 +2648,7 @@ mod tests { fn index() -> Option { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { - return Some(0) + return Some(0); } None @@ -2656,7 +2656,7 @@ mod tests { fn name() -> Option<&'static str> { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { - return Some("Test") + return Some("Test"); } None @@ -2664,7 +2664,7 @@ mod tests { fn module_name() -> Option<&'static str> { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { - return Some("tests") + return Some("tests"); } None @@ -2672,7 +2672,7 @@ mod tests { fn crate_version() -> Option { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { - return Some(frame_support::crate_to_crate_version!()) + return Some(frame_support::crate_to_crate_version!()); } None diff --git a/frame/support/src/hash.rs b/frame/support/src/hash.rs index f943bcf323090..2da6344145cee 100644 --- a/frame/support/src/hash.rs +++ b/frame/support/src/hash.rs @@ -111,7 +111,7 @@ impl ReversibleStorageHasher for Twox64Concat { fn reverse(x: &[u8]) -> &[u8] { if x.len() < 8 { log::error!("Invalid reverse: hash length too short"); - return &[] + return &[]; } &x[8..] } @@ -133,7 +133,7 @@ impl ReversibleStorageHasher for Blake2_128Concat { fn reverse(x: &[u8]) -> &[u8] { if x.len() < 16 { log::error!("Invalid reverse: hash length too short"); - return &[] + return &[]; } &x[16..] } diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 1b93b5fb5975e..34ce21c952eaa 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -723,7 +723,7 @@ pub use frame_support_procedural::crate_to_crate_version; #[macro_export] macro_rules! fail { ( $y:expr ) => {{ - return Err($y.into()) + return Err($y.into()); }}; } diff --git a/frame/support/src/storage/bounded_btree_map.rs b/frame/support/src/storage/bounded_btree_map.rs index 404814cb81693..4e43d36e1f042 100644 --- a/frame/support/src/storage/bounded_btree_map.rs +++ b/frame/support/src/storage/bounded_btree_map.rs @@ -44,7 +44,7 @@ where fn decode(input: &mut I) -> Result { let inner = BTreeMap::::decode(input)?; if inner.len() > S::get() as usize { - return Err("BoundedBTreeMap exceeds its limit".into()) + return Err("BoundedBTreeMap exceeds its limit".into()); } Ok(Self(inner, PhantomData)) } diff --git a/frame/support/src/storage/bounded_btree_set.rs b/frame/support/src/storage/bounded_btree_set.rs index ecfb0bdbd261f..1353c437e9fa7 100644 --- a/frame/support/src/storage/bounded_btree_set.rs +++ b/frame/support/src/storage/bounded_btree_set.rs @@ -43,7 +43,7 @@ where fn decode(input: &mut I) -> Result { let inner = BTreeSet::::decode(input)?; if inner.len() > S::get() as usize { - return Err("BoundedBTreeSet exceeds its limit".into()) + return Err("BoundedBTreeSet exceeds its limit".into()); } Ok(Self(inner, PhantomData)) } diff --git a/frame/support/src/storage/bounded_vec.rs b/frame/support/src/storage/bounded_vec.rs index e51c6cd734113..8e73a90b9718d 100644 --- a/frame/support/src/storage/bounded_vec.rs +++ b/frame/support/src/storage/bounded_vec.rs @@ -78,7 +78,7 @@ impl> Decode for BoundedVec { fn decode(input: &mut I) -> Result { let inner = Vec::::decode(input)?; if inner.len() > S::get() as usize { - return Err("BoundedVec exceeds its limit".into()) + return Err("BoundedVec exceeds its limit".into()); } Ok(Self(inner, PhantomData)) } diff --git a/frame/support/src/storage/child.rs b/frame/support/src/storage/child.rs index 4b237aaa561fd..0b6dc2dc0d740 100644 --- a/frame/support/src/storage/child.rs +++ b/frame/support/src/storage/child.rs @@ -42,7 +42,7 @@ pub fn get(child_info: &ChildInfo, key: &[u8]) -> Option { None }) }) - }, + } } } @@ -111,9 +111,10 @@ pub fn take_or_else T>( /// Check to see if `key` has an explicit entry in storage. pub fn exists(child_info: &ChildInfo, key: &[u8]) -> bool { match child_info.child_type() { - ChildType::ParentKeyId => + ChildType::ParentKeyId => { sp_io::default_child_storage::read(child_info.storage_key(), key, &mut [0; 0][..], 0) - .is_some(), + .is_some() + } } } @@ -138,8 +139,9 @@ pub fn exists(child_info: &ChildInfo, key: &[u8]) -> bool { /// blocks. pub fn kill_storage(child_info: &ChildInfo, limit: Option) -> KillStorageResult { match child_info.child_type() { - ChildType::ParentKeyId => - sp_io::default_child_storage::storage_kill(child_info.storage_key(), limit), + ChildType::ParentKeyId => { + sp_io::default_child_storage::storage_kill(child_info.storage_key(), limit) + } } } @@ -148,7 +150,7 @@ pub fn kill(child_info: &ChildInfo, key: &[u8]) { match child_info.child_type() { ChildType::ParentKeyId => { sp_io::default_child_storage::clear(child_info.storage_key(), key); - }, + } } } @@ -162,8 +164,9 @@ pub fn get_raw(child_info: &ChildInfo, key: &[u8]) -> Option> { /// Put a raw byte slice into storage. pub fn put_raw(child_info: &ChildInfo, key: &[u8], value: &[u8]) { match child_info.child_type() { - ChildType::ParentKeyId => - sp_io::default_child_storage::set(child_info.storage_key(), key, value), + ChildType::ParentKeyId => { + sp_io::default_child_storage::set(child_info.storage_key(), key, value) + } } } @@ -180,6 +183,6 @@ pub fn len(child_info: &ChildInfo, key: &[u8]) -> Option { ChildType::ParentKeyId => { let mut buffer = [0; 0]; sp_io::default_child_storage::read(child_info.storage_key(), key, &mut buffer, 0) - }, + } } } diff --git a/frame/support/src/storage/generator/double_map.rs b/frame/support/src/storage/generator/double_map.rs index 636a10feb1ab3..e12eb953954f9 100644 --- a/frame/support/src/storage/generator/double_map.rs +++ b/frame/support/src/storage/generator/double_map.rs @@ -449,16 +449,16 @@ where Some(value) => value, None => { log::error!("Invalid translate: fail to decode old value"); - continue - }, + continue; + } }; let mut key_material = G::Hasher1::reverse(&previous_key[prefix.len()..]); let key1 = match K1::decode(&mut key_material) { Ok(key1) => key1, Err(_) => { log::error!("Invalid translate: fail to decode key1"); - continue - }, + continue; + } }; let mut key2_material = G::Hasher2::reverse(&key_material); @@ -466,8 +466,8 @@ where Ok(key2) => key2, Err(_) => { log::error!("Invalid translate: fail to decode key2"); - continue - }, + continue; + } }; match f(key1, key2, value) { diff --git a/frame/support/src/storage/generator/map.rs b/frame/support/src/storage/generator/map.rs index 1a4225173c4ae..ce11e00a6423d 100644 --- a/frame/support/src/storage/generator/map.rs +++ b/frame/support/src/storage/generator/map.rs @@ -110,12 +110,12 @@ impl Iter Ok(key) => Some((key, value)), Err(_) => continue, } - }, + } None => continue, } - }, + } None => None, - } + }; } } } @@ -188,8 +188,8 @@ where Some(value) => value, None => { log::error!("Invalid translate: fail to decode old value"); - continue - }, + continue; + } }; let mut key_material = G::Hasher::reverse(&previous_key[prefix.len()..]); @@ -197,8 +197,8 @@ where Ok(key) => key, Err(_) => { log::error!("Invalid translate: fail to decode key"); - continue - }, + continue; + } }; match f(key, value) { diff --git a/frame/support/src/storage/generator/nmap.rs b/frame/support/src/storage/generator/nmap.rs index 4845673d3d8c2..02b82dc2f2a5e 100755 --- a/frame/support/src/storage/generator/nmap.rs +++ b/frame/support/src/storage/generator/nmap.rs @@ -408,16 +408,16 @@ impl> Some(value) => value, None => { log::error!("Invalid translate: fail to decode old value"); - continue - }, + continue; + } }; let final_key = match K::decode_final_key(&previous_key[prefix.len()..]) { Ok((final_key, _)) => final_key, Err(_) => { log::error!("Invalid translate: fail to decode key"); - continue - }, + continue; + } }; match f(final_key, value) { diff --git a/frame/support/src/storage/migration.rs b/frame/support/src/storage/migration.rs index 59422a282aab5..0928c3c6550cb 100644 --- a/frame/support/src/storage/migration.rs +++ b/frame/support/src/storage/migration.rs @@ -82,12 +82,12 @@ impl Iterator for StorageIterator { frame_support::storage::unhashed::kill(&next); } Some((self.previous_key[self.prefix.len()..].to_vec(), value)) - }, + } None => continue, } - }, + } None => None, - } + }; } } } @@ -152,15 +152,15 @@ impl Iterator frame_support::storage::unhashed::kill(&next); } Some((key, value)) - }, + } None => continue, } - }, + } Err(_) => continue, } - }, + } None => None, - } + }; } } } @@ -341,7 +341,7 @@ pub fn move_pallet(old_pallet_name: &[u8], new_pallet_name: &[u8]) { /// NOTE: The value at the key `from_prefix` is not moved. pub fn move_prefix(from_prefix: &[u8], to_prefix: &[u8]) { if from_prefix == to_prefix { - return + return; } let iter = PrefixIterator::<_> { diff --git a/frame/support/src/storage/mod.rs b/frame/support/src/storage/mod.rs index 35552e08fef1e..1118f9b1fe6d3 100644 --- a/frame/support/src/storage/mod.rs +++ b/frame/support/src/storage/mod.rs @@ -114,11 +114,11 @@ pub fn with_transaction(f: impl FnOnce() -> TransactionOutcome) -> R { Commit(res) => { commit_transaction(); res - }, + } Rollback(res) => { rollback_transaction(); res - }, + } } } @@ -875,8 +875,8 @@ impl Iterator for PrefixIterator Iterator for PrefixIterator None, - } + }; } } } @@ -973,12 +973,12 @@ impl Iterator for KeyPrefixIterator { Ok(item) => return Some(item), Err(e) => { log::error!("key failed to decode at {:?}: {:?}", self.previous_key, e); - continue - }, + continue; + } } } - return None + return None; } } } @@ -1088,8 +1088,8 @@ impl Iterator for ChildTriePrefixIterator { "next_key returned a key with no value at {:?}", self.previous_key, ); - continue - }, + continue; + } }; if self.drain { child::kill(&self.child_info, &self.previous_key) @@ -1103,14 +1103,14 @@ impl Iterator for ChildTriePrefixIterator { self.previous_key, e, ); - continue - }, + continue; + } }; Some(item) - }, + } None => None, - } + }; } } } @@ -1180,8 +1180,8 @@ pub trait StoragePrefixedMap { }, None => { log::error!("old key failed to decode at {:?}", previous_key); - continue - }, + continue; + } } } } diff --git a/frame/support/src/traits/members.rs b/frame/support/src/traits/members.rs index a59869c2fc9a3..3dd2dc6af3851 100644 --- a/frame/support/src/traits/members.rs +++ b/frame/support/src/traits/members.rs @@ -213,19 +213,19 @@ pub trait ChangeMembers { (Some(old), Some(new)) if old == new => { old_i = old_iter.next(); new_i = new_iter.next(); - }, + } (Some(old), Some(new)) if old < new => { outgoing.push(old.clone()); old_i = old_iter.next(); - }, + } (Some(old), None) => { outgoing.push(old.clone()); old_i = old_iter.next(); - }, + } (_, Some(new)) => { incoming.push(new.clone()); new_i = new_iter.next(); - }, + } } } (incoming, outgoing) diff --git a/frame/support/src/traits/stored_map.rs b/frame/support/src/traits/stored_map.rs index 715a5211be430..de56377e095d7 100644 --- a/frame/support/src/traits/stored_map.rs +++ b/frame/support/src/traits/stored_map.rs @@ -46,7 +46,7 @@ pub trait StoredMap { let r = f(&mut account); *x = Some(account); r - }, + } }) } diff --git a/frame/support/src/traits/tokens/fungible.rs b/frame/support/src/traits/tokens/fungible.rs index b033236d447bb..effe7ee7dcdd2 100644 --- a/frame/support/src/traits/tokens/fungible.rs +++ b/frame/support/src/traits/tokens/fungible.rs @@ -100,7 +100,7 @@ pub trait Mutate: Inspect { let revert = Self::mint_into(source, actual); debug_assert!(revert.is_ok(), "withdrew funds previously; qed"); Err(err) - }, + } } } } diff --git a/frame/support/src/traits/tokens/fungible/balanced.rs b/frame/support/src/traits/tokens/fungible/balanced.rs index 7b33a595a1b55..e18c0a26611cb 100644 --- a/frame/support/src/traits/tokens/fungible/balanced.rs +++ b/frame/support/src/traits/tokens/fungible/balanced.rs @@ -133,7 +133,7 @@ pub trait Balanced: Inspect { SameOrOther::Other(rest) => { debug_assert!(false, "ok withdraw return must be at least debt value; qed"); Err(rest) - }, + } } } } diff --git a/frame/support/src/traits/tokens/fungibles.rs b/frame/support/src/traits/tokens/fungibles.rs index b164a99671658..76e5cdd94c3a8 100644 --- a/frame/support/src/traits/tokens/fungibles.rs +++ b/frame/support/src/traits/tokens/fungibles.rs @@ -151,7 +151,7 @@ pub trait Mutate: Inspect { let revert = Self::mint_into(asset, source, actual); debug_assert!(revert.is_ok(), "withdrew funds previously; qed"); Err(err) - }, + } } } } diff --git a/frame/support/src/traits/tokens/fungibles/balanced.rs b/frame/support/src/traits/tokens/fungibles/balanced.rs index 40a65305b87da..cbb9446cd8fa4 100644 --- a/frame/support/src/traits/tokens/fungibles/balanced.rs +++ b/frame/support/src/traits/tokens/fungibles/balanced.rs @@ -149,11 +149,11 @@ pub trait Balanced: Inspect { Ok(SameOrOther::Other(rest)) => { debug_assert!(false, "ok withdraw return must be at least debt value; qed"); Err(rest) - }, + } Err(_) => { debug_assert!(false, "debt.asset is credit.asset; qed"); Ok(CreditOf::::zero(asset)) - }, + } } } } diff --git a/frame/support/src/traits/tokens/imbalance.rs b/frame/support/src/traits/tokens/imbalance.rs index 0f7b38a65efc8..cd507942804b0 100644 --- a/frame/support/src/traits/tokens/imbalance.rs +++ b/frame/support/src/traits/tokens/imbalance.rs @@ -83,7 +83,7 @@ pub trait Imbalance: Sized + TryDrop + Default { { let total: u32 = first.saturating_add(second); if total == 0 { - return (Self::zero(), Self::zero()) + return (Self::zero(), Self::zero()); } let amount1 = self.peek().saturating_mul(first.into()) / total.into(); self.split(amount1) diff --git a/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs b/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs index 3e76d069f50e7..83ee04089e684 100644 --- a/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs +++ b/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs @@ -54,17 +54,19 @@ impl< /// both. pub fn merge(self, other: Self) -> Self { match (self, other) { - (SignedImbalance::Positive(one), SignedImbalance::Positive(other)) => - SignedImbalance::Positive(one.merge(other)), - (SignedImbalance::Negative(one), SignedImbalance::Negative(other)) => - SignedImbalance::Negative(one.merge(other)), + (SignedImbalance::Positive(one), SignedImbalance::Positive(other)) => { + SignedImbalance::Positive(one.merge(other)) + } + (SignedImbalance::Negative(one), SignedImbalance::Negative(other)) => { + SignedImbalance::Negative(one.merge(other)) + } (SignedImbalance::Positive(one), SignedImbalance::Negative(other)) => { match one.offset(other) { SameOrOther::Same(positive) => SignedImbalance::Positive(positive), SameOrOther::Other(negative) => SignedImbalance::Negative(negative), SameOrOther::None => SignedImbalance::Positive(P::zero()), } - }, + } (one, other) => other.merge(one), } } diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index ec5f37823ad47..441d90375f5b0 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -433,7 +433,7 @@ where impl WeighData for Weight { fn weigh_data(&self, _: T) -> Weight { - return *self + return *self; } } @@ -451,7 +451,7 @@ impl PaysFee for Weight { impl WeighData for (Weight, DispatchClass, Pays) { fn weigh_data(&self, _: T) -> Weight { - return self.0 + return self.0; } } @@ -469,7 +469,7 @@ impl PaysFee for (Weight, DispatchClass, Pays) { impl WeighData for (Weight, DispatchClass) { fn weigh_data(&self, _: T) -> Weight { - return self.0 + return self.0; } } @@ -487,7 +487,7 @@ impl PaysFee for (Weight, DispatchClass) { impl WeighData for (Weight, Pays) { fn weigh_data(&self, _: T) -> Weight { - return self.0 + return self.0; } } diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index dc72be3ebdd49..16bf623112c8e 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -372,7 +372,7 @@ pub mod pallet { T::AccountId::from(SomeType1); // Test for where clause T::AccountId::from(SomeType5); // Test for where clause if matches!(call, Call::foo_transactional { .. }) { - return Ok(ValidTransaction::default()) + return Ok(ValidTransaction::default()); } Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) } diff --git a/frame/support/test/tests/pallet_compatibility.rs b/frame/support/test/tests/pallet_compatibility.rs index 4523063252ab9..3641cc28e27d1 100644 --- a/frame/support/test/tests/pallet_compatibility.rs +++ b/frame/support/test/tests/pallet_compatibility.rs @@ -285,8 +285,9 @@ mod test { fn metadata() { let metadata = Runtime::metadata(); let (pallets, types) = match metadata.1 { - frame_support::metadata::RuntimeMetadata::V14(metadata) => - (metadata.pallets, metadata.types), + frame_support::metadata::RuntimeMetadata::V14(metadata) => { + (metadata.pallets, metadata.types) + } _ => unreachable!(), }; diff --git a/frame/support/test/tests/pallet_compatibility_instance.rs b/frame/support/test/tests/pallet_compatibility_instance.rs index 768b9f28d35f3..b6c100c5bc193 100644 --- a/frame/support/test/tests/pallet_compatibility_instance.rs +++ b/frame/support/test/tests/pallet_compatibility_instance.rs @@ -288,8 +288,9 @@ mod test { fn metadata() { let metadata = Runtime::metadata(); let (pallets, types) = match metadata.1 { - frame_support::metadata::RuntimeMetadata::V14(metadata) => - (metadata.pallets, metadata.types), + frame_support::metadata::RuntimeMetadata::V14(metadata) => { + (metadata.pallets, metadata.types) + } _ => unreachable!(), }; diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 3a1009402d6f2..da085f962079a 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -747,25 +747,25 @@ fn metadata() { match example_pallet_instance1_metadata.calls { Some(ref mut calls_meta) => { calls_meta.ty = scale_info::meta_type::>(); - }, + } _ => unreachable!(), } match example_pallet_instance1_metadata.event { Some(ref mut event_meta) => { event_meta.ty = scale_info::meta_type::>(); - }, + } _ => unreachable!(), } match example_pallet_instance1_metadata.error { Some(ref mut error_meta) => { error_meta.ty = scale_info::meta_type::>(); - }, + } _ => unreachable!(), } match example_pallet_instance1_metadata.storage { Some(ref mut storage_meta) => { storage_meta.prefix = "Instance1Example"; - }, + } _ => unreachable!(), } diff --git a/frame/system/src/extensions/check_nonce.rs b/frame/system/src/extensions/check_nonce.rs index 3c6f9a1b4dbd1..f7a39866ec7c9 100644 --- a/frame/system/src/extensions/check_nonce.rs +++ b/frame/system/src/extensions/check_nonce.rs @@ -86,7 +86,7 @@ where } else { InvalidTransaction::Future } - .into()) + .into()); } account.nonce += T::Index::one(); crate::Account::::insert(who, account); @@ -103,7 +103,7 @@ where // check index let account = crate::Account::::get(who); if self.0 < account.nonce { - return InvalidTransaction::Stale.into() + return InvalidTransaction::Stale.into(); } let provides = vec![Encode::encode(&(who, self.0))]; diff --git a/frame/system/src/extensions/check_weight.rs b/frame/system/src/extensions/check_weight.rs index ca885accd660f..4a9e137b2051f 100644 --- a/frame/system/src/extensions/check_weight.rs +++ b/frame/system/src/extensions/check_weight.rs @@ -147,7 +147,7 @@ where Some(max) if per_class > max => return Err(InvalidTransaction::ExhaustsResources.into()), // There is no `max_total` limit (`None`), // or we are below the limit. - _ => {}, + _ => {} } // In cases total block weight is exceeded, we need to fall back @@ -155,11 +155,12 @@ where if all_weight.total() > maximum_weight.max_block { match limit_per_class.reserved { // We are over the limit in reserved pool. - Some(reserved) if per_class > reserved => - return Err(InvalidTransaction::ExhaustsResources.into()), + Some(reserved) if per_class > reserved => { + return Err(InvalidTransaction::ExhaustsResources.into()) + } // There is either no limit in reserved pool (`None`), // or we are below the limit. - _ => {}, + _ => {} } } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 2e7f26eef16f4..d15c46fc7f7c3 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -1149,18 +1149,18 @@ impl Pallet { Pallet::::on_killed_account(who.clone()); Ok(DecRefStatus::Reaped) - }, + } (1, c, _) if c > 0 => { // Cannot remove last provider if there are consumers. Err(DispatchError::ConsumerRemaining) - }, + } (x, _, _) => { // Account will continue to exist as there is either > 1 provider or // > 0 sufficients. account.providers = x - 1; *maybe_account = Some(account); Ok(DecRefStatus::Exists) - }, + } } } else { log::error!( @@ -1204,12 +1204,12 @@ impl Pallet { (0, 0) | (1, 0) => { Pallet::::on_killed_account(who.clone()); DecRefStatus::Reaped - }, + } (x, _) => { account.sufficients = x - 1; *maybe_account = Some(account); DecRefStatus::Exists - }, + } } } else { log::error!( @@ -1301,7 +1301,7 @@ impl Pallet { let block_number = Self::block_number(); // Don't populate events on genesis. if block_number.is_zero() { - return + return; } let phase = ExecutionPhase::::get().unwrap_or_default(); @@ -1573,7 +1573,7 @@ impl Pallet { err, ); Event::ExtrinsicFailed(err.error, info) - }, + } }); let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32; @@ -1707,10 +1707,10 @@ impl StoredMap for Pallet { DecRefStatus::Reaped => return Ok(result), DecRefStatus::Exists => { // Update value as normal... - }, + } } } else if !was_providing && !is_providing { - return Ok(result) + return Ok(result); } Account::::mutate(k, |a| a.data = some_data.unwrap_or_default()); Ok(result) @@ -1726,7 +1726,7 @@ pub fn split_inner( Some(inner) => { let (r, s) = splitter(inner); (Some(r), Some(s)) - }, + } None => (None, None), } } diff --git a/frame/system/src/offchain.rs b/frame/system/src/offchain.rs index ed758a2556b77..fd1ace149b41d 100644 --- a/frame/system/src/offchain.rs +++ b/frame/system/src/offchain.rs @@ -175,7 +175,7 @@ impl, X> Signer }) .filter(move |account| keystore_lookup.contains(&account.public)), ) - }, + } } } @@ -211,7 +211,7 @@ impl> Signer(length: u32) -> (T::AccountId, Vec, T::AccountId) { let caller = whitelisted_caller(); - let value = T::TipReportDepositBase::get() + - T::DataDepositPerByte::get() * length.into() + - T::Currency::minimum_balance(); + let value = T::TipReportDepositBase::get() + + T::DataDepositPerByte::get() * length.into() + + T::Currency::minimum_balance(); let _ = T::Currency::make_free_balance_be(&caller, value); let reason = vec![0; length as usize]; let awesome_person = account("awesome", 0, SEED); diff --git a/frame/tips/src/lib.rs b/frame/tips/src/lib.rs index f4a4edb7b3999..9976f1a6c02b7 100644 --- a/frame/tips/src/lib.rs +++ b/frame/tips/src/lib.rs @@ -250,8 +250,8 @@ pub mod pallet { let hash = T::Hashing::hash_of(&(&reason_hash, &who)); ensure!(!Tips::::contains_key(&hash), Error::::AlreadyKnown); - let deposit = T::TipReportDepositBase::get() + - T::DataDepositPerByte::get() * (reason.len() as u32).into(); + let deposit = T::TipReportDepositBase::get() + + T::DataDepositPerByte::get() * (reason.len() as u32).into(); T::Currency::reserve(&finder, deposit)?; Reasons::::insert(&reason_hash, &reason); @@ -501,11 +501,11 @@ impl Pallet { Some(m) => { member = members_iter.next(); if m < a { - continue + continue; } else { - break true + break true; } - }, + } } }); } diff --git a/frame/tips/src/migrations/v4.rs b/frame/tips/src/migrations/v4.rs index 69df1d08d2c8a..4812738a890ec 100644 --- a/frame/tips/src/migrations/v4.rs +++ b/frame/tips/src/migrations/v4.rs @@ -49,7 +49,7 @@ pub fn migrate::on_chain_storage_version(); @@ -109,7 +109,7 @@ pub fn pre_migrate< log_migration("pre-migration", storage_prefix_reasons, old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return + return; } let new_pallet_prefix = twox_128(new_pallet_name.as_bytes()); @@ -148,7 +148,7 @@ pub fn post_migrate< log_migration("post-migration", storage_prefix_reasons, old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return + return; } // Assert that no `Tips` and `Reasons` storages remains at the old prefix. diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 28200bee7054f..883ac20746bf3 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -349,15 +349,15 @@ pub mod pallet { // loss. use sp_std::convert::TryInto; assert!( - ::max_value() >= - Multiplier::checked_from_integer( + ::max_value() + >= Multiplier::checked_from_integer( T::BlockWeights::get().max_block.try_into().unwrap() ) .unwrap(), ); - let target = T::FeeMultiplierUpdate::target() * - T::BlockWeights::get().get(DispatchClass::Normal).max_total.expect( + let target = T::FeeMultiplierUpdate::target() + * T::BlockWeights::get().get(DispatchClass::Normal).max_total.expect( "Setting `max_total` for `Normal` dispatch class is not compatible with \ `transaction-payment` pallet.", ); @@ -365,7 +365,7 @@ pub mod pallet { let addition = target / 100; if addition == 0 { // this is most likely because in a test setup we set everything to (). - return + return; } #[cfg(any(feature = "std", test))] @@ -645,12 +645,12 @@ where DispatchClass::Normal => { // For normal class we simply take the `tip_per_weight`. scaled_tip - }, + } DispatchClass::Mandatory => { // Mandatory extrinsics should be prohibited (e.g. by the [`CheckWeight`] // extensions), but just to be safe let's return the same priority as `Normal` here. scaled_tip - }, + } DispatchClass::Operational => { // A "virtual tip" value added to an `Operational` extrinsic. // This value should be kept high enough to allow `Operational` extrinsics @@ -662,7 +662,7 @@ where let scaled_virtual_tip = max_reward(virtual_tip); scaled_tip.saturating_add(scaled_virtual_tip) - }, + } } .saturated_into::() } diff --git a/frame/transaction-payment/src/payment.rs b/frame/transaction-payment/src/payment.rs index 58e6ef63109a3..ae692fac64b03 100644 --- a/frame/transaction-payment/src/payment.rs +++ b/frame/transaction-payment/src/payment.rs @@ -99,7 +99,7 @@ where tip: Self::Balance, ) -> Result { if fee.is_zero() { - return Ok(None) + return Ok(None); } let withdraw_reason = if tip.is_zero() { diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index bc31199d90391..03d75d6f6f826 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -198,7 +198,7 @@ pub mod pallet { let mut index = 0; >::mutate(|transactions| { if transactions.len() + 1 > MaxBlockTransactions::::get() as usize { - return Err(Error::::TooManyTransactions) + return Err(Error::::TooManyTransactions); } let total_chunks = transactions.last().map_or(0, |t| t.block_chunks) + chunk_count; index = transactions.len() as u32; @@ -238,7 +238,7 @@ pub mod pallet { let mut index = 0; >::mutate(|transactions| { if transactions.len() + 1 > MaxBlockTransactions::::get() as usize { - return Err(Error::::TooManyTransactions) + return Err(Error::::TooManyTransactions); } let chunks = num_chunks(info.size); let total_chunks = transactions.last().map_or(0, |t| t.block_chunks) + chunks; @@ -291,7 +291,7 @@ pub mod pallet { let chunks = num_chunks(info.size); let prev_chunks = info.block_chunks - chunks; (info, selected_chunk_index - prev_chunks) - }, + } None => Err(Error::::MissingStateData)?, }; ensure!( diff --git a/frame/uniques/src/lib.rs b/frame/uniques/src/lib.rs index 1bf220e4a7876..9427a29e931f2 100644 --- a/frame/uniques/src/lib.rs +++ b/frame/uniques/src/lib.rs @@ -536,10 +536,10 @@ pub mod pallet { if T::Currency::reserve(&class_details.owner, deposit - old).is_err() { // NOTE: No alterations made to class_details in this iteration so far, so // this is OK to do. - continue + continue; } } else { - continue + continue; } class_details.total_deposit.saturating_accrue(deposit); class_details.total_deposit.saturating_reduce(old); @@ -691,7 +691,7 @@ pub mod pallet { let details = maybe_details.as_mut().ok_or(Error::::Unknown)?; ensure!(&origin == &details.owner, Error::::NoPermission); if details.owner == owner { - return Ok(()) + return Ok(()); } // Move the deposit to the new owner. @@ -914,8 +914,9 @@ pub mod pallet { } let maybe_is_frozen = match maybe_instance { None => ClassMetadataOf::::get(class).map(|v| v.is_frozen), - Some(instance) => - InstanceMetadataOf::::get(class, instance).map(|v| v.is_frozen), + Some(instance) => { + InstanceMetadataOf::::get(class, instance).map(|v| v.is_frozen) + } }; ensure!(!maybe_is_frozen.unwrap_or(false), Error::::Frozen); @@ -978,8 +979,9 @@ pub mod pallet { } let maybe_is_frozen = match maybe_instance { None => ClassMetadataOf::::get(class).map(|v| v.is_frozen), - Some(instance) => - InstanceMetadataOf::::get(class, instance).map(|v| v.is_frozen), + Some(instance) => { + InstanceMetadataOf::::get(class, instance).map(|v| v.is_frozen) + } }; ensure!(!maybe_is_frozen.unwrap_or(false), Error::::Frozen); diff --git a/frame/utility/src/lib.rs b/frame/utility/src/lib.rs index 54de87c4740c8..8ce18ab844864 100644 --- a/frame/utility/src/lib.rs +++ b/frame/utility/src/lib.rs @@ -195,7 +195,7 @@ pub mod pallet { // Take the weight of this function itself into account. let base_weight = T::WeightInfo::batch(index.saturating_add(1) as u32); // Return the actual used weight + base_weight of this call. - return Ok(Some(base_weight + weight).into()) + return Ok(Some(base_weight + weight).into()); } Self::deposit_event(Event::ItemCompleted); } diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 27862a5ca4b72..09c0e9e9cdeb4 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -440,7 +440,7 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; if schedule1_index == schedule2_index { - return Ok(()) + return Ok(()); }; let schedule1_index = schedule1_index as usize; let schedule2_index = schedule2_index as usize; @@ -479,7 +479,7 @@ impl Pallet { (true, false) => return Some(schedule2), (false, true) => return Some(schedule1), // If neither schedule has ended don't exit early. - _ => {}, + _ => {} } let locked = schedule1 @@ -517,7 +517,7 @@ impl Pallet { // Validate user inputs. ensure!(schedule.locked() >= T::MinVestedTransfer::get(), Error::::AmountLow); if !schedule.is_valid() { - return Err(Error::::InvalidScheduleParams.into()) + return Err(Error::::InvalidScheduleParams.into()); }; let target = T::Lookup::lookup(target)?; let source = T::Lookup::lookup(source)?; @@ -658,13 +658,13 @@ impl Pallet { } // In the None case there was no new schedule to account for. (schedules, locked_now) - }, + } _ => Self::report_schedule_updates(schedules.to_vec(), action), }; debug_assert!( - locked_now > Zero::zero() && schedules.len() > 0 || - locked_now == Zero::zero() && schedules.len() == 0 + locked_now > Zero::zero() && schedules.len() > 0 + || locked_now == Zero::zero() && schedules.len() == 0 ); Ok((schedules, locked_now)) @@ -710,13 +710,13 @@ where starting_block: T::BlockNumber, ) -> DispatchResult { if locked.is_zero() { - return Ok(()) + return Ok(()); } let vesting_schedule = VestingInfo::new(locked, per_block, starting_block); // Check for `per_block` or `locked` of 0. if !vesting_schedule.is_valid() { - return Err(Error::::InvalidScheduleParams.into()) + return Err(Error::::InvalidScheduleParams.into()); }; let mut schedules = Self::vesting(who).unwrap_or_default(); @@ -744,7 +744,7 @@ where ) -> DispatchResult { // Check for `per_block` or `locked` of 0. if !VestingInfo::new(locked, per_block, starting_block).is_valid() { - return Err(Error::::InvalidScheduleParams.into()) + return Err(Error::::InvalidScheduleParams.into()); } ensure!( diff --git a/frame/vesting/src/tests.rs b/frame/vesting/src/tests.rs index 2a6dd0520c3b0..684246102363e 100644 --- a/frame/vesting/src/tests.rs +++ b/frame/vesting/src/tests.rs @@ -1131,16 +1131,16 @@ fn vested_transfer_less_than_existential_deposit_fails() { ExtBuilder::default().existential_deposit(4 * ED).build().execute_with(|| { // MinVestedTransfer is less the ED. assert!( - ::Currency::minimum_balance() > - ::MinVestedTransfer::get() + ::Currency::minimum_balance() + > ::MinVestedTransfer::get() ); let sched = VestingInfo::new(::MinVestedTransfer::get() as u64, 1u64, 10u64); // The new account balance with the schedule's locked amount would be less than ED. assert!( - Balances::free_balance(&99) + sched.locked() < - ::Currency::minimum_balance() + Balances::free_balance(&99) + sched.locked() + < ::Currency::minimum_balance() ); // vested_transfer fails. diff --git a/frame/vesting/src/vesting_info.rs b/frame/vesting/src/vesting_info.rs index 81bffa199fd72..c910a7f48b69b 100644 --- a/frame/vesting/src/vesting_info.rs +++ b/frame/vesting/src/vesting_info.rs @@ -99,8 +99,8 @@ where // the block after starting. One::one() } else { - self.locked / self.per_block() + - if (self.locked % self.per_block()).is_zero() { + self.locked / self.per_block() + + if (self.locked % self.per_block()).is_zero() { Zero::zero() } else { // `per_block` does not perfectly divide `locked`, so we need an extra block to From 98b31787a43b0601f9b05823514bb00ab0110f39 Mon Sep 17 00:00:00 2001 From: david Date: Tue, 26 Oct 2021 09:30:14 +0100 Subject: [PATCH 05/11] updated events in test files --- Cargo.lock | 1 + bin/node/executor/tests/basic.rs | 60 +++++++++---------- bin/node/executor/tests/fees.rs | 6 +- frame/assets/src/benchmarking.rs | 4 +- frame/assets/src/functions.rs | 4 +- frame/balances/src/lib.rs | 14 ++--- frame/balances/src/tests.rs | 4 +- frame/contracts/src/tests.rs | 32 +++++----- .../src/signed.rs | 4 +- frame/offences/benchmarking/src/lib.rs | 14 ++--- frame/proxy/src/tests.rs | 2 +- frame/transaction-payment/src/lib.rs | 6 +- utils/frame/remote-externalities/Cargo.toml | 1 + 13 files changed, 77 insertions(+), 75 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6325304bfceec..12119827f6c1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7203,6 +7203,7 @@ name = "remote-externalities" version = "0.10.0-dev" dependencies = [ "env_logger 0.9.0", + "frame-support", "jsonrpsee-proc-macros", "jsonrpsee-ws-client", "log 0.4.14", diff --git a/bin/node/executor/tests/basic.rs b/bin/node/executor/tests/basic.rs index bbb9339189b06..bf96253663b45 100644 --- a/bin/node/executor/tests/basic.rs +++ b/bin/node/executor/tests/basic.rs @@ -387,24 +387,24 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Withdraw(alice().into(), fees)), + event: Event::Balances(pallet_balances::Event::Withdraw{who: alice().into(), amount: fees}), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Transfer( - alice().into(), - bob().into(), - 69 * DOLLARS, - )), + event: Event::Balances(pallet_balances::Event::Transfer{ + from: alice().into(), + to: bob().into(), + value: 69 * DOLLARS, + }), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Deposit( - pallet_treasury::Pallet::::account_id(), - fees * 8 / 10, - )), + event: Event::Balances(pallet_balances::Event::Deposit{ + who: pallet_treasury::Pallet::::account_id(), + deposit: fees * 8 / 10, + }), topics: vec![], }, EventRecord { @@ -454,24 +454,24 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Withdraw(bob().into(), fees)), + event: Event::Balances(pallet_balances::Event::Withdraw{who: bob().into(), amount: fees}), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Transfer( - bob().into(), - alice().into(), - 5 * DOLLARS, - )), + event: Event::Balances(pallet_balances::Event::Transfer{ + from: bob().into(), + to: alice().into(), + value: 5 * DOLLARS, + }), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Deposit( - pallet_treasury::Pallet::::account_id(), - fees * 8 / 10, - )), + event: Event::Balances(pallet_balances::Event::Deposit{ + who: pallet_treasury::Pallet::::account_id(), + deposit: fees * 8 / 10, + }), topics: vec![], }, EventRecord { @@ -489,24 +489,24 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::Balances(pallet_balances::Event::Withdraw(alice().into(), fees)), + event: Event::Balances(pallet_balances::Event::Withdraw{who: alice().into(), amount: fees}), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::Balances(pallet_balances::Event::Transfer( - alice().into(), - bob().into(), - 15 * DOLLARS, - )), + event: Event::Balances(pallet_balances::Event::Transfer{ + from: alice().into(), + to: bob().into(), + value: 15 * DOLLARS, + }), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::Balances(pallet_balances::Event::Deposit( - pallet_treasury::Pallet::::account_id(), - fees * 8 / 10, - )), + event: Event::Balances(pallet_balances::Event::Deposit{ + who: pallet_treasury::Pallet::::account_id(), + deposit: fees * 8 / 10, + }), topics: vec![], }, EventRecord { diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index 379cdda5b76a3..5f0cf58befd07 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -241,7 +241,7 @@ fn block_weight_capacity_report() { let mut xts = (0..num_transfers) .map(|i| CheckedExtrinsic { signed: Some((charlie(), signed_extra(nonce + i as Index, 0))), - function: Call::Balances(pallet_balances::Call::transfer(bob().into(), 0)), + function: Call::Balances(pallet_balances::Call::transfer{dest: bob().into(), value: 0}), }) .collect::>(); @@ -249,7 +249,7 @@ fn block_weight_capacity_report() { 0, CheckedExtrinsic { signed: None, - function: Call::Timestamp(pallet_timestamp::Call::set(time * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set{now: time * 1000}), }, ); @@ -319,7 +319,7 @@ fn block_length_capacity_report() { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(pallet_timestamp::Call::set(time * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set{now: time * 1000}), }, CheckedExtrinsic { signed: Some((charlie(), signed_extra(nonce, 0))), diff --git a/frame/assets/src/benchmarking.rs b/frame/assets/src/benchmarking.rs index 080e068a49bdb..121c9df0344c3 100644 --- a/frame/assets/src/benchmarking.rs +++ b/frame/assets/src/benchmarking.rs @@ -155,7 +155,7 @@ benchmarks_instance_pallet! { T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup, 1u32.into()) verify { - assert_last_event::(Event::Created{asset:id: Default::default(), creator: caller.clone(), owner: caller}.into()); + assert_last_event::(Event::Created{asset_id: Default::default(), creator: caller.clone(), owner: caller}.into()); } force_create { @@ -163,7 +163,7 @@ benchmarks_instance_pallet! { let caller_lookup = T::Lookup::unlookup(caller.clone()); }: _(SystemOrigin::Root, Default::default(), caller_lookup, true, 1u32.into()) verify { - assert_last_event::(Event::ForceCreated{asset_id: Default::default(), caller}.into()); + assert_last_event::(Event::ForceCreated{asset_id: Default::default(), owner: caller}.into()); } destroy { diff --git a/frame/assets/src/functions.rs b/frame/assets/src/functions.rs index f50f671d95a4b..1ce9a384d7c79 100644 --- a/frame/assets/src/functions.rs +++ b/frame/assets/src/functions.rs @@ -599,7 +599,7 @@ impl, I: 'static> Pallet { }, )?; Asset::::insert(id, d); - Self::deposit_event(Event::ApprovedTransfer(id, owner.clone(), delegate.clone(), amount)); + Self::deposit_event(Event::ApprovedTransfer{asset_id: id, source: owner.clone(), delegate: delegate.clone(), amount}); Ok(()) } @@ -683,7 +683,7 @@ impl, I: 'static> Pallet { is_frozen: false, }); - Self::deposit_event(Event::MetadataSet(id, name, symbol, decimals, false)); + Self::deposit_event(Event::MetadataSet{asset_id: id, name, symbol, decimals, is_frozen: false}); Ok(()) }) } diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 1e032fd30503a..72dae45a98883 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -1109,7 +1109,7 @@ impl, I: 'static> fungible::Mutate for Pallet { Ok(()) })?; TotalIssuance::::mutate(|t| *t += amount); - Self::deposit_event(Event::Deposit(who.clone(), amount)); + Self::deposit_event(Event::Deposit{who: who.clone(), deposit: amount}); Ok(()) } @@ -1130,7 +1130,7 @@ impl, I: 'static> fungible::Mutate for Pallet { }, )?; TotalIssuance::::mutate(|t| *t -= actual); - Self::deposit_event(Event::Withdraw(who.clone(), amount)); + Self::deposit_event(Event::Withdraw{who: who.clone(), amount}); Ok(actual) } } @@ -1151,7 +1151,7 @@ impl, I: 'static> fungible::Unbalanced for Pallet DispatchResult { Self::mutate_account(who, |account| { account.free = amount; - Self::deposit_event(Event::BalanceSet(who.clone(), account.free, account.reserved)); + Self::deposit_event(Event::BalanceSet{who: who.clone(), free: account.free, reserved: account.reserved}); })?; Ok(()) } @@ -1625,7 +1625,7 @@ where |account, is_new| -> Result { ensure!(!is_new, Error::::DeadAccount); account.free = account.free.checked_add(&value).ok_or(ArithmeticError::Overflow)?; - Self::deposit_event(Event::Deposit(who.clone(), value)); + Self::deposit_event(Event::Deposit{who: who.clone(), deposit: value}); Ok(PositiveImbalance::new(value)) }, ) @@ -1658,7 +1658,7 @@ where None => return Ok(Self::PositiveImbalance::zero()), }; - Self::deposit_event(Event::Deposit(who.clone(), value)); + Self::deposit_event(Event::Deposit{who: who.clone(), deposit: value}); Ok(PositiveImbalance::new(value)) }, ) @@ -1696,7 +1696,7 @@ where account.free = new_free_account; - Self::deposit_event(Event::Withdraw(who.clone(), value)); + Self::deposit_event(Event::Withdraw{who: who.clone(), amount: value}); Ok(NegativeImbalance::new(value)) }, ) @@ -1729,7 +1729,7 @@ where SignedImbalance::Negative(NegativeImbalance::new(account.free - value)) }; account.free = value; - Self::deposit_event(Event::BalanceSet(who.clone(), account.free, account.reserved)); + Self::deposit_event(Event::BalanceSet{who: who.clone(), free: account.free, reserved: account.reserved}); Ok(imbalance) }, ) diff --git a/frame/balances/src/tests.rs b/frame/balances/src/tests.rs index d02be25dd169f..29b4377386861 100644 --- a/frame/balances/src/tests.rs +++ b/frame/balances/src/tests.rs @@ -314,7 +314,7 @@ macro_rules! decl_tests { <$ext_builder>::default().monied(true).build().execute_with(|| { assert_eq!(Balances::total_balance(&1), 10); assert_ok!(Balances::deposit_into_existing(&1, 10).map(drop)); - System::assert_last_event(Event::Balances(crate::Event::Deposit(1, 10))); + System::assert_last_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 10})); assert_eq!(Balances::total_balance(&1), 20); assert_eq!(>::get(), 120); }); @@ -342,7 +342,7 @@ macro_rules! decl_tests { fn balance_works() { <$ext_builder>::default().build().execute_with(|| { let _ = Balances::deposit_creating(&1, 42); - System::assert_has_event(Event::Balances(crate::Event::Deposit(1, 42))); + System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 42})); assert_eq!(Balances::free_balance(1), 42); assert_eq!(Balances::reserved_balance(1), 0); assert_eq!(Balances::total_balance(&1), 42); diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index b75bdd7f58d9f..4b3aa0bfa3c6e 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -446,7 +446,7 @@ fn instantiate_and_call_and_deposit_event() { vec![ EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Deposit(ALICE, 1_000_000)), + event: Event::Balances(pallet_balances::Event::Deposit{who: ALICE, deposit: 1_000_000}), topics: vec![], }, EventRecord { @@ -456,7 +456,7 @@ fn instantiate_and_call_and_deposit_event() { }, EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Endowed(ALICE, 1_000_000)), + event: Event::Balances(pallet_balances::Event::Endowed{account: ALICE, free_balance: 1_000_000}), topics: vec![], }, EventRecord { @@ -466,19 +466,19 @@ fn instantiate_and_call_and_deposit_event() { }, EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Endowed( - addr.clone(), - subsistence * 100 - )), + event: Event::Balances(pallet_balances::Event::Endowed{ + account: addr.clone(), + free_balance: subsistence * 100 + }), topics: vec![], }, EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Transfer( - ALICE, - addr.clone(), - subsistence * 100 - )), + event: Event::Balances(pallet_balances::Event::Transfer{ + from: ALICE, + to: addr.clone(), + value: subsistence * 100 + }), topics: vec![], }, EventRecord { @@ -765,11 +765,11 @@ fn self_destruct_works() { }, EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Transfer( - addr.clone(), - DJANGO, - 100_000, - )), + event: Event::Balances(pallet_balances::Event::Transfer{ + from: addr.clone(), + to: DJANGO, + value: 100_000, + }), topics: vec![], }, EventRecord { diff --git a/frame/election-provider-multi-phase/src/signed.rs b/frame/election-provider-multi-phase/src/signed.rs index 3ef929938b515..89ba0047dd844 100644 --- a/frame/election-provider-multi-phase/src/signed.rs +++ b/frame/election-provider-multi-phase/src/signed.rs @@ -429,7 +429,7 @@ impl Pallet { >::put(ready_solution); // emit reward event - Self::deposit_event(crate::Event::Rewarded(who.clone(), reward)); + Self::deposit_event(crate::Event::Rewarded{account: who.clone(), value: reward}); // unreserve deposit. let _remaining = T::Currency::unreserve(who, deposit); @@ -446,7 +446,7 @@ impl Pallet { /// /// Infallible pub fn finalize_signed_phase_reject_solution(who: &T::AccountId, deposit: BalanceOf) { - Self::deposit_event(crate::Event::Slashed(who.clone(), deposit)); + Self::deposit_event(crate::Event::Slashed{account: who.clone(), value: deposit}); let (negative_imbalance, _remaining) = T::Currency::slash_reserved(who, deposit); debug_assert!(_remaining.is_zero()); T::SlashHandler::on_unbalanced(negative_imbalance); diff --git a/frame/offences/benchmarking/src/lib.rs b/frame/offences/benchmarking/src/lib.rs index c920b0b900dff..5fd58b09d60bd 100644 --- a/frame/offences/benchmarking/src/lib.rs +++ b/frame/offences/benchmarking/src/lib.rs @@ -315,13 +315,13 @@ benchmarks! { ::Event::from(StakingEvent::::Slashed(id, BalanceOf::::from(slash_amount))) ); let balance_slash = |id| core::iter::once( - ::Event::from(pallet_balances::Event::::Slashed(id, slash_amount.into())) + ::Event::from(pallet_balances::Event::::Slashed{who: id, amount_slashed: slash_amount.into()}) ); let chill = |id| core::iter::once( ::Event::from(StakingEvent::::Chilled(id)) ); let balance_deposit = |id, amount: u32| - ::Event::from(pallet_balances::Event::::Deposit(id, amount.into())); + ::Event::from(pallet_balances::Event::::Deposit{who: id, deposit: amount.into()}); let mut first = true; let slash_events = raw_offenders.into_iter() .flat_map(|offender| { @@ -344,7 +344,7 @@ benchmarks! { balance_deposit(reporter.clone(), reward.into()).into(), frame_system::Event::::NewAccount(reporter.clone()).into(), ::Event::from( - pallet_balances::Event::::Endowed(reporter.clone(), reward.into()) + pallet_balances::Event::::Endowed{account: reporter.clone(), free_balance: reward.into()} ).into(), ]) .collect::>(); @@ -371,10 +371,10 @@ benchmarks! { std::iter::empty() .chain(slash_events.into_iter().map(Into::into)) .chain(std::iter::once(::Event::from( - pallet_offences::Event::Offence( - UnresponsivenessOffence::::ID, - 0_u32.to_le_bytes().to_vec(), - ) + pallet_offences::Event::Offence{ + kind: UnresponsivenessOffence::::ID, + timeslot: 0_u32.to_le_bytes().to_vec(), + } ).into())) ); } diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index d143094cc97e0..2b9d7c6e7f92a 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -407,7 +407,7 @@ fn filtering_works() { ); assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); expect_events(vec![ - BalancesEvent::::Unreserved(1, 5).into(), + BalancesEvent::::Unreserved{who: 1, value: 5}.into(), ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); }); diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 883ac20746bf3..a4c4d6d072bf4 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -1319,9 +1319,9 @@ mod tests { )); assert_eq!(Balances::free_balance(2), 0); // Transfer Event - System::assert_has_event(Event::Balances(pallet_balances::Event::Transfer( - 2, 3, 80, - ))); + System::assert_has_event(Event::Balances(pallet_balances::Event::Transfer{ + from: 2, to: 3, value: 80, + })); // Killed Event System::assert_has_event(Event::System(system::Event::KilledAccount(2))); }); diff --git a/utils/frame/remote-externalities/Cargo.toml b/utils/frame/remote-externalities/Cargo.toml index 2b35402f8f63f..7bee9f431004b 100644 --- a/utils/frame/remote-externalities/Cargo.toml +++ b/utils/frame/remote-externalities/Cargo.toml @@ -32,6 +32,7 @@ sp-version = { version = "4.0.0-dev", path = "../../../primitives/version" } [dev-dependencies] tokio = { version = "1.10", features = ["macros", "rt-multi-thread"] } pallet-elections-phragmen = { path = "../../../frame/elections-phragmen", version = "5.0.0-dev" } +frame-support = { path = "../../../frame/support", version = "4.0.0-dev" } [features] remote-test = [] From e1c8fa6c7dc73af95568076a75ce47f301c89bce Mon Sep 17 00:00:00 2001 From: david Date: Tue, 26 Oct 2021 10:38:40 +0100 Subject: [PATCH 06/11] cargo fmt --- bin/node/executor/tests/basic.rs | 27 ++-- bin/node/executor/tests/fees.rs | 9 +- frame/assets/src/functions.rs | 41 ++++- frame/assets/src/lib.rs | 95 +++++++---- frame/assets/src/tests.rs | 7 +- frame/aura/src/lib.rs | 4 +- frame/authorship/src/lib.rs | 33 ++-- frame/babe/src/equivocation.rs | 6 +- frame/babe/src/lib.rs | 10 +- frame/babe/src/tests.rs | 6 +- frame/bags-list/src/list/mod.rs | 16 +- frame/balances/src/lib.rs | 153 ++++++++++-------- frame/balances/src/tests_local.rs | 7 +- frame/balances/src/tests_reentrancy.rs | 6 +- frame/beefy-mmr/primitives/src/lib.rs | 12 +- frame/beefy-mmr/src/lib.rs | 2 +- frame/beefy/src/lib.rs | 2 +- frame/benchmarking/src/analysis.rs | 12 +- frame/benchmarking/src/lib.rs | 2 +- frame/benchmarking/src/tests.rs | 2 +- frame/benchmarking/src/utils.rs | 4 +- frame/bounties/src/lib.rs | 56 +++---- frame/bounties/src/migrations/v4.rs | 2 +- frame/collective/src/lib.rs | 8 +- frame/collective/src/migrations/v4.rs | 6 +- frame/contracts/proc-macro/src/lib.rs | 6 +- frame/contracts/src/benchmarking/code.rs | 16 +- frame/contracts/src/exec.rs | 28 ++-- frame/contracts/src/lib.rs | 7 +- frame/contracts/src/schedule.rs | 38 ++--- frame/contracts/src/storage.rs | 16 +- frame/contracts/src/tests.rs | 24 +-- frame/contracts/src/wasm/code_cache.rs | 7 +- frame/contracts/src/wasm/prepare.rs | 89 +++++----- frame/contracts/src/wasm/runtime.rs | 28 ++-- frame/democracy/src/lib.rs | 42 +++-- frame/democracy/src/types.rs | 8 +- frame/democracy/src/vote.rs | 10 +- frame/democracy/src/vote_threshold.rs | 20 ++- .../election-provider-multi-phase/src/lib.rs | 40 ++--- .../election-provider-multi-phase/src/mock.rs | 2 +- .../src/signed.rs | 20 +-- .../src/unsigned.rs | 47 +++--- frame/elections-phragmen/src/lib.rs | 26 +-- frame/elections-phragmen/src/migrations/v4.rs | 2 +- frame/elections/src/lib.rs | 39 ++--- frame/elections/src/tests.rs | 2 +- frame/example-offchain-worker/src/lib.rs | 39 +++-- frame/example-parallel/src/lib.rs | 6 +- frame/example/src/lib.rs | 4 +- frame/executive/src/lib.rs | 29 ++-- frame/gilt/src/lib.rs | 6 +- frame/grandpa/src/equivocation.rs | 6 +- frame/grandpa/src/lib.rs | 14 +- frame/grandpa/src/migrations/v4.rs | 2 +- frame/grandpa/src/tests.rs | 4 +- frame/identity/src/benchmarking.rs | 20 ++- frame/identity/src/lib.rs | 14 +- frame/identity/src/types.rs | 9 +- frame/im-online/src/lib.rs | 33 ++-- frame/im-online/src/tests.rs | 5 +- frame/lottery/src/lib.rs | 10 +- frame/membership/src/lib.rs | 2 +- frame/membership/src/migrations/v4.rs | 6 +- frame/merkle-mountain-range/src/lib.rs | 8 +- .../merkle-mountain-range/src/mmr/storage.rs | 2 +- frame/merkle-mountain-range/src/mmr/utils.rs | 2 +- frame/multisig/src/lib.rs | 4 +- frame/node-authorization/src/lib.rs | 6 +- frame/proxy/src/lib.rs | 22 ++- frame/proxy/src/tests.rs | 4 +- frame/scheduler/src/lib.rs | 24 +-- frame/scored-pool/src/lib.rs | 10 +- frame/session/src/historical/mod.rs | 8 +- frame/session/src/historical/offchain.rs | 6 +- frame/session/src/lib.rs | 10 +- frame/session/src/mock.rs | 4 +- frame/society/src/lib.rs | 44 ++--- frame/staking/reward-curve/src/lib.rs | 32 ++-- frame/staking/reward-curve/src/log.rs | 4 +- frame/staking/reward-fn/src/lib.rs | 18 +-- frame/staking/src/benchmarking.rs | 2 +- frame/staking/src/inflation.rs | 4 +- frame/staking/src/lib.rs | 2 +- frame/staking/src/mock.rs | 6 +- frame/staking/src/pallet/impls.rs | 27 ++-- frame/staking/src/pallet/mod.rs | 33 ++-- frame/staking/src/slashing.rs | 16 +- frame/staking/src/testing_utils.rs | 4 +- frame/staking/src/tests.rs | 32 ++-- frame/sudo/src/lib.rs | 2 +- .../support/procedural/src/clone_no_bound.rs | 16 +- .../src/construct_runtime/expand/event.rs | 10 +- .../src/construct_runtime/expand/origin.rs | 10 +- .../procedural/src/construct_runtime/mod.rs | 4 +- .../procedural/src/construct_runtime/parse.rs | 24 +-- frame/support/procedural/src/crate_version.rs | 2 +- .../support/procedural/src/debug_no_bound.rs | 14 +- .../procedural/src/default_no_bound.rs | 19 ++- .../procedural/src/dummy_part_checker.rs | 2 +- frame/support/procedural/src/key_prefix.rs | 2 +- .../procedural/src/pallet/expand/call.rs | 2 +- .../procedural/src/pallet/expand/event.rs | 2 +- .../src/pallet/expand/genesis_build.rs | 2 +- .../src/pallet/expand/genesis_config.rs | 10 +- .../procedural/src/pallet/expand/hooks.rs | 2 +- .../procedural/src/pallet/expand/storage.rs | 28 ++-- frame/support/procedural/src/pallet/mod.rs | 2 +- .../procedural/src/pallet/parse/call.rs | 26 +-- .../procedural/src/pallet/parse/config.rs | 34 ++-- .../procedural/src/pallet/parse/error.rs | 10 +- .../procedural/src/pallet/parse/event.rs | 6 +- .../src/pallet/parse/extra_constants.rs | 18 +-- .../src/pallet/parse/genesis_build.rs | 2 +- .../src/pallet/parse/genesis_config.rs | 8 +- .../procedural/src/pallet/parse/helper.rs | 18 +-- .../procedural/src/pallet/parse/hooks.rs | 4 +- .../procedural/src/pallet/parse/inherent.rs | 8 +- .../procedural/src/pallet/parse/mod.rs | 69 ++++---- .../procedural/src/pallet/parse/origin.rs | 8 +- .../src/pallet/parse/pallet_struct.rs | 12 +- .../procedural/src/pallet/parse/storage.rs | 84 +++++----- .../procedural/src/pallet/parse/type_value.rs | 12 +- .../src/pallet/parse/validate_unsigned.rs | 8 +- .../procedural/src/partial_eq_no_bound.rs | 16 +- .../src/storage/genesis_config/builder_def.rs | 14 +- .../genesis_config/genesis_config_def.rs | 8 +- .../support/procedural/src/storage/getters.rs | 8 +- .../procedural/src/storage/metadata.rs | 8 +- frame/support/procedural/src/storage/mod.rs | 40 +++-- frame/support/procedural/src/storage/parse.rs | 32 ++-- .../src/storage/print_pallet_upgrade.rs | 14 +- .../procedural/src/storage/storage_struct.rs | 24 +-- frame/support/procedural/tools/src/lib.rs | 6 +- frame/support/procedural/tools/src/syn_ext.rs | 4 +- frame/support/src/dispatch.rs | 8 +- frame/support/src/hash.rs | 4 +- frame/support/src/lib.rs | 2 +- .../support/src/storage/bounded_btree_map.rs | 2 +- .../support/src/storage/bounded_btree_set.rs | 2 +- frame/support/src/storage/bounded_vec.rs | 2 +- frame/support/src/storage/child.rs | 21 ++- .../src/storage/generator/double_map.rs | 12 +- frame/support/src/storage/generator/map.rs | 14 +- frame/support/src/storage/generator/nmap.rs | 8 +- frame/support/src/storage/migration.rs | 16 +- frame/support/src/storage/mod.rs | 38 ++--- frame/support/src/traits/members.rs | 8 +- frame/support/src/traits/stored_map.rs | 2 +- frame/support/src/traits/tokens/fungible.rs | 2 +- .../src/traits/tokens/fungible/balanced.rs | 2 +- frame/support/src/traits/tokens/fungibles.rs | 2 +- .../src/traits/tokens/fungibles/balanced.rs | 4 +- frame/support/src/traits/tokens/imbalance.rs | 2 +- .../tokens/imbalance/signed_imbalance.rs | 12 +- frame/support/src/weights.rs | 8 +- frame/support/test/tests/pallet.rs | 2 +- .../test/tests/pallet_compatibility.rs | 5 +- .../tests/pallet_compatibility_instance.rs | 5 +- frame/support/test/tests/pallet_instance.rs | 8 +- frame/system/src/extensions/check_nonce.rs | 4 +- frame/system/src/extensions/check_weight.rs | 9 +- frame/system/src/lib.rs | 20 +-- frame/system/src/offchain.rs | 4 +- frame/tips/src/benchmarking.rs | 6 +- frame/tips/src/lib.rs | 10 +- frame/tips/src/migrations/v4.rs | 6 +- frame/transaction-payment/src/lib.rs | 22 +-- frame/transaction-payment/src/payment.rs | 2 +- frame/transaction-storage/src/lib.rs | 6 +- frame/uniques/src/lib.rs | 16 +- frame/utility/src/lib.rs | 2 +- frame/vesting/src/lib.rs | 18 +-- frame/vesting/src/tests.rs | 8 +- frame/vesting/src/vesting_info.rs | 4 +- 175 files changed, 1297 insertions(+), 1273 deletions(-) diff --git a/bin/node/executor/tests/basic.rs b/bin/node/executor/tests/basic.rs index bf96253663b45..6923237b3ca92 100644 --- a/bin/node/executor/tests/basic.rs +++ b/bin/node/executor/tests/basic.rs @@ -387,12 +387,15 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Withdraw{who: alice().into(), amount: fees}), + event: Event::Balances(pallet_balances::Event::Withdraw { + who: alice().into(), + amount: fees, + }), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Transfer{ + event: Event::Balances(pallet_balances::Event::Transfer { from: alice().into(), to: bob().into(), value: 69 * DOLLARS, @@ -401,7 +404,7 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Deposit{ + event: Event::Balances(pallet_balances::Event::Deposit { who: pallet_treasury::Pallet::::account_id(), deposit: fees * 8 / 10, }), @@ -454,12 +457,15 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Withdraw{who: bob().into(), amount: fees}), + event: Event::Balances(pallet_balances::Event::Withdraw { + who: bob().into(), + amount: fees, + }), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Transfer{ + event: Event::Balances(pallet_balances::Event::Transfer { from: bob().into(), to: alice().into(), value: 5 * DOLLARS, @@ -468,7 +474,7 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::Balances(pallet_balances::Event::Deposit{ + event: Event::Balances(pallet_balances::Event::Deposit { who: pallet_treasury::Pallet::::account_id(), deposit: fees * 8 / 10, }), @@ -489,12 +495,15 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::Balances(pallet_balances::Event::Withdraw{who: alice().into(), amount: fees}), + event: Event::Balances(pallet_balances::Event::Withdraw { + who: alice().into(), + amount: fees, + }), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::Balances(pallet_balances::Event::Transfer{ + event: Event::Balances(pallet_balances::Event::Transfer { from: alice().into(), to: bob().into(), value: 15 * DOLLARS, @@ -503,7 +512,7 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::Balances(pallet_balances::Event::Deposit{ + event: Event::Balances(pallet_balances::Event::Deposit { who: pallet_treasury::Pallet::::account_id(), deposit: fees * 8 / 10, }), diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index 5f0cf58befd07..4c7593bdb3ab2 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -241,7 +241,10 @@ fn block_weight_capacity_report() { let mut xts = (0..num_transfers) .map(|i| CheckedExtrinsic { signed: Some((charlie(), signed_extra(nonce + i as Index, 0))), - function: Call::Balances(pallet_balances::Call::transfer{dest: bob().into(), value: 0}), + function: Call::Balances(pallet_balances::Call::transfer { + dest: bob().into(), + value: 0, + }), }) .collect::>(); @@ -249,7 +252,7 @@ fn block_weight_capacity_report() { 0, CheckedExtrinsic { signed: None, - function: Call::Timestamp(pallet_timestamp::Call::set{now: time * 1000}), + function: Call::Timestamp(pallet_timestamp::Call::set { now: time * 1000 }), }, ); @@ -319,7 +322,7 @@ fn block_length_capacity_report() { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(pallet_timestamp::Call::set{now: time * 1000}), + function: Call::Timestamp(pallet_timestamp::Call::set { now: time * 1000 }), }, CheckedExtrinsic { signed: Some((charlie(), signed_extra(nonce, 0))), diff --git a/frame/assets/src/functions.rs b/frame/assets/src/functions.rs index 1ce9a384d7c79..f01954cb970ee 100644 --- a/frame/assets/src/functions.rs +++ b/frame/assets/src/functions.rs @@ -275,7 +275,11 @@ impl, I: 'static> Pallet { details.supply = details.supply.saturating_add(amount); Ok(()) })?; - Self::deposit_event(Event::Issued{asset_id: id, owner: beneficiary.clone(), total_supply: amount}); + Self::deposit_event(Event::Issued { + asset_id: id, + owner: beneficiary.clone(), + total_supply: amount, + }); Ok(()) } @@ -342,7 +346,7 @@ impl, I: 'static> Pallet { Ok(()) })?; - Self::deposit_event(Event::Burned{asset_id: id, owner: target.clone(), balance: actual}); + Self::deposit_event(Event::Burned { asset_id: id, owner: target.clone(), balance: actual }); Ok(actual) } @@ -415,7 +419,12 @@ impl, I: 'static> Pallet { ) -> Result { // Early exist if no-op. if amount.is_zero() { - Self::deposit_event(Event::Transferred{asset_id: id, from: source.clone(), to: dest.clone(), amount}); + Self::deposit_event(Event::Transferred { + asset_id: id, + from: source.clone(), + to: dest.clone(), + amount, + }); return Ok(amount) } @@ -476,7 +485,12 @@ impl, I: 'static> Pallet { Ok(()) })?; - Self::deposit_event(Event::Transferred{asset_id: id, from: source.clone(), to: dest.clone(), amount: credit}); + Self::deposit_event(Event::Transferred { + asset_id: id, + from: source.clone(), + to: dest.clone(), + amount: credit, + }); Ok(credit) } @@ -514,7 +528,7 @@ impl, I: 'static> Pallet { is_frozen: false, }, ); - Self::deposit_event(Event::ForceCreated{asset_id: id, owner}); + Self::deposit_event(Event::ForceCreated { asset_id: id, owner }); Ok(()) } @@ -554,7 +568,7 @@ impl, I: 'static> Pallet { for ((owner, _), approval) in Approvals::::drain_prefix((&id,)) { T::Currency::unreserve(&owner, approval.deposit); } - Self::deposit_event(Event::Destroyed{asset_id: id}); + Self::deposit_event(Event::Destroyed { asset_id: id }); Ok(DestroyWitness { accounts: details.accounts, @@ -599,7 +613,12 @@ impl, I: 'static> Pallet { }, )?; Asset::::insert(id, d); - Self::deposit_event(Event::ApprovedTransfer{asset_id: id, source: owner.clone(), delegate: delegate.clone(), amount}); + Self::deposit_event(Event::ApprovedTransfer { + asset_id: id, + source: owner.clone(), + delegate: delegate.clone(), + amount, + }); Ok(()) } @@ -683,7 +702,13 @@ impl, I: 'static> Pallet { is_frozen: false, }); - Self::deposit_event(Event::MetadataSet{asset_id: id, name, symbol, decimals, is_frozen: false}); + Self::deposit_event(Event::MetadataSet { + asset_id: id, + name, + symbol, + decimals, + is_frozen: false, + }); Ok(()) }) } diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 94e3877ed10e9..4ad675ed0f77e 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -381,42 +381,69 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { /// Some asset class was created. - Created{asset_id: T::AssetId, creator: T::AccountId, owner: T::AccountId}, + Created { asset_id: T::AssetId, creator: T::AccountId, owner: T::AccountId }, /// Some assets were issued. - Issued{asset_id: T::AssetId, owner: T::AccountId, total_supply: T::Balance}, + Issued { asset_id: T::AssetId, owner: T::AccountId, total_supply: T::Balance }, /// Some assets were transferred. - Transferred{asset_id: T::AssetId, from: T::AccountId, to: T::AccountId, amount: T::Balance}, + Transferred { + asset_id: T::AssetId, + from: T::AccountId, + to: T::AccountId, + amount: T::Balance, + }, /// Some assets were destroyed. - Burned{asset_id: T::AssetId, owner: T::AccountId, balance: T::Balance}, + Burned { asset_id: T::AssetId, owner: T::AccountId, balance: T::Balance }, /// The management team changed. - TeamChanged{asset_id: T::AssetId, issuer: T::AccountId, admin: T::AccountId, freezer: T::AccountId}, + TeamChanged { + asset_id: T::AssetId, + issuer: T::AccountId, + admin: T::AccountId, + freezer: T::AccountId, + }, /// The owner changed. - OwnerChanged{asset_id: T::AssetId, owner: T::AccountId}, + OwnerChanged { asset_id: T::AssetId, owner: T::AccountId }, /// Some account `who` was frozen. - Frozen{asset_id: T::AssetId, who: T::AccountId}, + Frozen { asset_id: T::AssetId, who: T::AccountId }, /// Some account `who` was thawed. - Thawed{asset_id: T::AssetId, who: T::AccountId}, + Thawed { asset_id: T::AssetId, who: T::AccountId }, /// Some asset `asset_id` was frozen. - AssetFrozen{asset_id: T::AssetId}, + AssetFrozen { asset_id: T::AssetId }, /// Some asset `asset_id` was thawed. - AssetThawed{asset_id: T::AssetId}, + AssetThawed { asset_id: T::AssetId }, /// An asset class was destroyed. - Destroyed{asset_id: T::AssetId}, + Destroyed { asset_id: T::AssetId }, /// Some asset class was force-created. - ForceCreated{asset_id: T::AssetId, owner: T::AccountId}, + ForceCreated { asset_id: T::AssetId, owner: T::AccountId }, /// New metadata has been set for an asset. - MetadataSet{asset_id: T::AssetId, name: Vec, symbol: Vec, decimals: u8, is_frozen: bool}, + MetadataSet { + asset_id: T::AssetId, + name: Vec, + symbol: Vec, + decimals: u8, + is_frozen: bool, + }, /// Metadata has been cleared for an asset. - MetadataCleared{asset_id: T::AssetId}, + MetadataCleared { asset_id: T::AssetId }, /// (Additional) funds have been approved for transfer to a destination account. - ApprovedTransfer{asset_id: T::AssetId, source: T::AccountId, delegate: T::AccountId, amount: T::Balance}, + ApprovedTransfer { + asset_id: T::AssetId, + source: T::AccountId, + delegate: T::AccountId, + amount: T::Balance, + }, /// An approval for account `delegate` was cancelled by `owner`. - ApprovalCancelled{asset_id: T::AssetId, owner: T::AccountId, delegate: T::AccountId}, + ApprovalCancelled { asset_id: T::AssetId, owner: T::AccountId, delegate: T::AccountId }, /// An `amount` was transferred in its entirety from `owner` to `destination` by /// the approved `delegate`. - TransferredApproved{asset_id: T::AssetId, owner: T::AccountId, delegate: T::AccountId, destination: T::AccountId, amount: T::Balance}, + TransferredApproved { + asset_id: T::AssetId, + owner: T::AccountId, + delegate: T::AccountId, + destination: T::AccountId, + amount: T::Balance, + }, /// An asset has had its attributes changed by the `Force` origin. - AssetStatusChanged{asset_id: T::AssetId}, + AssetStatusChanged { asset_id: T::AssetId }, } #[pallet::error] @@ -502,7 +529,7 @@ pub mod pallet { is_frozen: false, }, ); - Self::deposit_event(Event::Created{asset_id: id, creator: owner, owner: admin}); + Self::deposit_event(Event::Created { asset_id: id, creator: owner, owner: admin }); Ok(()) } @@ -758,7 +785,7 @@ pub mod pallet { Account::::mutate(id, &who, |a| a.is_frozen = true); - Self::deposit_event(Event::::Frozen{asset_id: id, who}); + Self::deposit_event(Event::::Frozen { asset_id: id, who }); Ok(()) } @@ -787,7 +814,7 @@ pub mod pallet { Account::::mutate(id, &who, |a| a.is_frozen = false); - Self::deposit_event(Event::::Thawed{asset_id: id, who}); + Self::deposit_event(Event::::Thawed { asset_id: id, who }); Ok(()) } @@ -813,7 +840,7 @@ pub mod pallet { d.is_frozen = true; - Self::deposit_event(Event::::AssetFrozen{asset_id: id}); + Self::deposit_event(Event::::AssetFrozen { asset_id: id }); Ok(()) }) } @@ -840,7 +867,7 @@ pub mod pallet { d.is_frozen = false; - Self::deposit_event(Event::::AssetThawed{asset_id: id}); + Self::deposit_event(Event::::AssetThawed { asset_id: id }); Ok(()) }) } @@ -879,7 +906,7 @@ pub mod pallet { details.owner = owner.clone(); - Self::deposit_event(Event::OwnerChanged{asset_id: id, owner}); + Self::deposit_event(Event::OwnerChanged { asset_id: id, owner }); Ok(()) }) } @@ -917,7 +944,7 @@ pub mod pallet { details.admin = admin.clone(); details.freezer = freezer.clone(); - Self::deposit_event(Event::TeamChanged{asset_id: id, issuer, admin, freezer}); + Self::deposit_event(Event::TeamChanged { asset_id: id, issuer, admin, freezer }); Ok(()) }) } @@ -974,7 +1001,7 @@ pub mod pallet { Metadata::::try_mutate_exists(id, |metadata| { let deposit = metadata.take().ok_or(Error::::Unknown)?.deposit; T::Currency::unreserve(&d.owner, deposit); - Self::deposit_event(Event::MetadataCleared{asset_id: id}); + Self::deposit_event(Event::MetadataCleared { asset_id: id }); Ok(()) }) } @@ -1021,7 +1048,13 @@ pub mod pallet { is_frozen, }); - Self::deposit_event(Event::MetadataSet{asset_id: id, name, symbol, decimals, is_frozen}); + Self::deposit_event(Event::MetadataSet { + asset_id: id, + name, + symbol, + decimals, + is_frozen, + }); Ok(()) }) } @@ -1048,7 +1081,7 @@ pub mod pallet { Metadata::::try_mutate_exists(id, |metadata| { let deposit = metadata.take().ok_or(Error::::Unknown)?.deposit; T::Currency::unreserve(&d.owner, deposit); - Self::deposit_event(Event::MetadataCleared{asset_id: id}); + Self::deposit_event(Event::MetadataCleared { asset_id: id }); Ok(()) }) } @@ -1100,7 +1133,7 @@ pub mod pallet { asset.is_frozen = is_frozen; *maybe_asset = Some(asset); - Self::deposit_event(Event::AssetStatusChanged{asset_id: id}); + Self::deposit_event(Event::AssetStatusChanged { asset_id: id }); Ok(()) }) } @@ -1166,7 +1199,7 @@ pub mod pallet { d.approvals.saturating_dec(); Asset::::insert(id, d); - Self::deposit_event(Event::ApprovalCancelled{asset_id: id, owner, delegate}); + Self::deposit_event(Event::ApprovalCancelled { asset_id: id, owner, delegate }); Ok(()) } @@ -1208,7 +1241,7 @@ pub mod pallet { d.approvals.saturating_dec(); Asset::::insert(id, d); - Self::deposit_event(Event::ApprovalCancelled{asset_id: id, owner, delegate}); + Self::deposit_event(Event::ApprovalCancelled { asset_id: id, owner, delegate }); Ok(()) } diff --git a/frame/assets/src/tests.rs b/frame/assets/src/tests.rs index b43833a543f36..e24a1d45215da 100644 --- a/frame/assets/src/tests.rs +++ b/frame/assets/src/tests.rs @@ -500,7 +500,12 @@ fn transferring_less_than_one_unit_is_fine() { assert_ok!(Assets::mint(Origin::signed(1), 0, 1, 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 0)); - System::assert_last_event(mock::Event::Assets(crate::Event::Transferred{asset_id: 0, from: 1, to: 2, amount: 0})); + System::assert_last_event(mock::Event::Assets(crate::Event::Transferred { + asset_id: 0, + from: 1, + to: 2, + amount: 0, + })); }); } diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index b0b61928c4761..4b5294835403a 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -173,7 +173,7 @@ impl Pallet { let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime()); for (id, mut data) in pre_runtime_digests { if id == AURA_ENGINE_ID { - return Slot::decode(&mut data).ok(); + return Slot::decode(&mut data).ok() } } @@ -240,7 +240,7 @@ impl FindAuthor for Pallet { if id == AURA_ENGINE_ID { let slot = Slot::decode(&mut data).ok()?; let author_index = *slot % Self::authorities().len() as u64; - return Some(author_index as u32); + return Some(author_index as u32) } } diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 76efc9eac40cd..5d36adabe888f 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -107,7 +107,7 @@ where if let Some(ref author) = author { if !acc.insert((number.clone(), author.clone())) { - return Err("more than one uncle per number per author included"); + return Err("more than one uncle per number per author included") } } @@ -261,12 +261,12 @@ pub mod pallet { existing_hashes.push(hash); if new_uncles.len() == MAX_UNCLES { - break; + break } - } + }, Err(_) => { // skip this uncle - } + }, } } } @@ -283,9 +283,8 @@ pub mod pallet { _data: &InherentData, ) -> result::Result<(), Self::Error> { match call { - Call::set_uncles { ref new_uncles } if new_uncles.len() > MAX_UNCLES => { - Err(InherentError::Uncles(Error::::TooManyUncles.as_str().into())) - } + Call::set_uncles { ref new_uncles } if new_uncles.len() > MAX_UNCLES => + Err(InherentError::Uncles(Error::::TooManyUncles.as_str().into())), _ => Ok(()), } } @@ -304,7 +303,7 @@ impl Pallet { pub fn author() -> T::AccountId { // Check the memoized storage value. if let Some(author) = >::get() { - return author; + return author } let digest = >::digest(); @@ -361,30 +360,30 @@ impl Pallet { let hash = uncle.hash(); if uncle.number() < &One::one() { - return Err(Error::::GenesisUncle.into()); + return Err(Error::::GenesisUncle.into()) } if uncle.number() > &maximum_height { - return Err(Error::::TooHighUncle.into()); + return Err(Error::::TooHighUncle.into()) } { let parent_number = uncle.number().clone() - One::one(); let parent_hash = >::block_hash(&parent_number); if &parent_hash != uncle.parent_hash() { - return Err(Error::::InvalidUncleParent.into()); + return Err(Error::::InvalidUncleParent.into()) } } if uncle.number() < &minimum_height { - return Err(Error::::OldUncle.into()); + return Err(Error::::OldUncle.into()) } let duplicate = existing_uncles.into_iter().any(|h| *h == hash); let in_chain = >::block_hash(uncle.number()) == hash; if duplicate || in_chain { - return Err(Error::::UncleAlreadyIncluded.into()); + return Err(Error::::UncleAlreadyIncluded.into()) } // check uncle validity. @@ -483,7 +482,7 @@ mod tests { { for (id, data) in digests { if id == TEST_ID { - return u64::decode(&mut &data[..]).ok(); + return u64::decode(&mut &data[..]).ok() } } @@ -507,10 +506,10 @@ mod tests { Err(_) => return Err("wrong seal"), Ok(a) => { if a != author { - return Err("wrong author in seal"); + return Err("wrong author in seal") } - break; - } + break + }, } } } diff --git a/frame/babe/src/equivocation.rs b/frame/babe/src/equivocation.rs index 65fdc90ea37d0..2397918d1ef13 100644 --- a/frame/babe/src/equivocation.rs +++ b/frame/babe/src/equivocation.rs @@ -189,15 +189,15 @@ impl Pallet { if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call { // discard equivocation report not coming from the local node match source { - TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ } + TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ }, _ => { log::warn!( target: "runtime::babe", "rejecting unsigned report equivocation transaction because it is not local/in-block.", ); - return InvalidTransaction::Call.into(); - } + return InvalidTransaction::Call.into() + }, } // check report staleness diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index d173eeeb87aac..9c755eea6c446 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -441,11 +441,11 @@ impl FindAuthor for Pallet { for (id, mut data) in digests.into_iter() { if id == BABE_ENGINE_ID { let pre_digest: PreDigest = PreDigest::decode(&mut data).ok()?; - return Some(pre_digest.authority_index()); + return Some(pre_digest.authority_index()) } } - return None; + return None } } @@ -661,7 +661,7 @@ impl Pallet { // => let's ensure that we only modify the storage once per block let initialized = Self::initialized().is_some(); if initialized { - return; + return } let maybe_pre_digest: Option = @@ -790,7 +790,7 @@ impl Pallet { // validate the equivocation proof if !sp_consensus_babe::check_equivocation_proof(equivocation_proof) { - return Err(Error::::InvalidEquivocationProof.into()); + return Err(Error::::InvalidEquivocationProof.into()) } let validator_set_count = key_owner_proof.validator_count(); @@ -802,7 +802,7 @@ impl Pallet { // check that the slot number is consistent with the session index // in the key ownership proof (i.e. slot is for that epoch) if epoch_index != session_index { - return Err(Error::::InvalidKeyOwnershipProof.into()); + return Err(Error::::InvalidKeyOwnershipProof.into()) } // check the membership proof and extract the offender's id diff --git a/frame/babe/src/tests.rs b/frame/babe/src/tests.rs index acd066f444056..34d861d5d97f7 100644 --- a/frame/babe/src/tests.rs +++ b/frame/babe/src/tests.rs @@ -219,8 +219,8 @@ fn can_estimate_current_epoch_progress() { ); } else { assert!( - Babe::estimate_current_session_progress(i).0.unwrap() - < Permill::from_percent(100) + Babe::estimate_current_session_progress(i).0.unwrap() < + Permill::from_percent(100) ); } } @@ -462,7 +462,7 @@ fn report_equivocation_current_session_works() { // check that the balances of all other validators are left intact. for validator in &validators { if *validator == offending_validator_id { - continue; + continue } assert_eq!(Balances::total_balance(validator), 10_000_000); diff --git a/frame/bags-list/src/list/mod.rs b/frame/bags-list/src/list/mod.rs index b7f7d2a9050c5..3f55f22271910 100644 --- a/frame/bags-list/src/list/mod.rs +++ b/frame/bags-list/src/list/mod.rs @@ -130,7 +130,7 @@ impl List { pub fn migrate(old_thresholds: &[VoteWeight]) -> u32 { let new_thresholds = T::BagThresholds::get(); if new_thresholds == old_thresholds { - return 0; + return 0 } // we can't check all preconditions, but we can check one @@ -163,7 +163,7 @@ impl List { if !affected_old_bags.insert(affected_bag) { // If the previous threshold list was [10, 20], and we insert [3, 5], then there's // no point iterating through bag 10 twice. - continue; + continue } if let Some(bag) = Bag::::get(affected_bag) { @@ -175,7 +175,7 @@ impl List { // a removed bag means that all members of that bag must be rebagged for removed_bag in removed_bags.clone() { if !affected_old_bags.insert(removed_bag) { - continue; + continue } if let Some(bag) = Bag::::get(removed_bag) { @@ -263,7 +263,7 @@ impl List { /// Returns an error if the list already contains `id`. pub(crate) fn insert(id: T::AccountId, weight: VoteWeight) -> Result<(), Error> { if Self::contains(&id) { - return Err(Error::Duplicate); + return Err(Error::Duplicate) } let bag_weight = notional_bag_for::(weight); @@ -568,7 +568,7 @@ impl Bag { // infinite loop. debug_assert!(false, "system logic error: inserting a node who has the id of tail"); crate::log!(warn, "system logic error: inserting a node who has the id of tail"); - return; + return }; } @@ -775,9 +775,9 @@ impl Node { ); frame_support::ensure!( - !self.is_terminal() - || expected_bag.head.as_ref() == Some(id) - || expected_bag.tail.as_ref() == Some(id), + !self.is_terminal() || + expected_bag.head.as_ref() == Some(id) || + expected_bag.tail.as_ref() == Some(id), "a terminal node is neither its bag head or tail" ); diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 72dae45a98883..d02a57a6cc8ed 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -464,19 +464,24 @@ pub mod pallet { /// A balance was set by root. BalanceSet { who: T::AccountId, free: T::Balance, reserved: T::Balance }, /// Some amount was deposited (e.g. for transaction fees). - Deposit{who: T::AccountId, deposit: T::Balance}, + Deposit { who: T::AccountId, deposit: T::Balance }, /// Some amount was withdrawn from the account (e.g. for transaction fees). \[who, value\] - Withdraw{who: T::AccountId, amount: T::Balance}, + Withdraw { who: T::AccountId, amount: T::Balance }, /// Some balance was reserved (moved from free to reserved). Reserved { who: T::AccountId, value: T::Balance }, /// Some balance was unreserved (moved from reserved to free). Unreserved { who: T::AccountId, value: T::Balance }, /// Some balance was moved from the reserve of the first account to the second account. /// Final argument indicates the destination balance type. - ReserveRepatriated{from: T::AccountId, to: T::AccountId, balance: T::Balance, destination_status: Status}, + ReserveRepatriated { + from: T::AccountId, + to: T::AccountId, + balance: T::Balance, + destination_status: Status, + }, /// Some amount was removed from the account (e.g. for misbehavior). \[who, /// amount_slashed\] - Slashed{who: T::AccountId, amount_slashed: T::Balance}, + Slashed { who: T::AccountId, amount_slashed: T::Balance }, } /// Old name generated by `decl_event`. @@ -646,7 +651,7 @@ impl BitOr for Reasons { type Output = Reasons; fn bitor(self, other: Reasons) -> Reasons { if self == other { - return self; + return self } Reasons::All } @@ -804,11 +809,11 @@ impl, I: 'static> Pallet { account: &AccountData, ) -> DepositConsequence { if amount.is_zero() { - return DepositConsequence::Success; + return DepositConsequence::Success } if TotalIssuance::::get().checked_add(&amount).is_none() { - return DepositConsequence::Overflow; + return DepositConsequence::Overflow } let new_total_balance = match account.total().checked_add(&amount) { @@ -817,7 +822,7 @@ impl, I: 'static> Pallet { }; if new_total_balance < T::ExistentialDeposit::get() { - return DepositConsequence::BelowMinimum; + return DepositConsequence::BelowMinimum } // NOTE: We assume that we are a provider, so don't need to do any checks in the @@ -832,11 +837,11 @@ impl, I: 'static> Pallet { account: &AccountData, ) -> WithdrawConsequence { if amount.is_zero() { - return WithdrawConsequence::Success; + return WithdrawConsequence::Success } if TotalIssuance::::get().checked_sub(&amount).is_none() { - return WithdrawConsequence::Underflow; + return WithdrawConsequence::Underflow } let new_total_balance = match account.total().checked_sub(&amount) { @@ -853,7 +858,7 @@ impl, I: 'static> Pallet { if frame_system::Pallet::::can_dec_provider(who) { WithdrawConsequence::ReducedToZero(new_total_balance) } else { - return WithdrawConsequence::WouldDie; + return WithdrawConsequence::WouldDie } } else { WithdrawConsequence::Success @@ -868,7 +873,7 @@ impl, I: 'static> Pallet { // Eventual free funds must be no less than the frozen balance. let min_balance = account.frozen(Reasons::All); if new_free_balance < min_balance { - return WithdrawConsequence::Frozen; + return WithdrawConsequence::Frozen } success @@ -1011,14 +1016,14 @@ impl, I: 'static> Pallet { status: Status, ) -> Result { if value.is_zero() { - return Ok(Zero::zero()); + return Ok(Zero::zero()) } if slashed == beneficiary { return match status { Status::Free => Ok(Self::unreserve(slashed, value)), Status::Reserved => Ok(value.saturating_sub(Self::reserved_balance(slashed))), - }; + } } let ((actual, _maybe_one_dust), _maybe_other_dust) = Self::try_mutate_account_with_dust( @@ -1031,18 +1036,16 @@ impl, I: 'static> Pallet { let actual = cmp::min(from_account.reserved, value); ensure!(best_effort || actual == value, Error::::InsufficientBalance); match status { - Status::Free => { + Status::Free => to_account.free = to_account .free .checked_add(&actual) - .ok_or(ArithmeticError::Overflow)? - } - Status::Reserved => { + .ok_or(ArithmeticError::Overflow)?, + Status::Reserved => to_account.reserved = to_account .reserved .checked_add(&actual) - .ok_or(ArithmeticError::Overflow)? - } + .ok_or(ArithmeticError::Overflow)?, } from_account.reserved -= actual; Ok(actual) @@ -1101,7 +1104,7 @@ impl, I: 'static> fungible::Inspect for Pallet impl, I: 'static> fungible::Mutate for Pallet { fn mint_into(who: &T::AccountId, amount: Self::Balance) -> DispatchResult { if amount.is_zero() { - return Ok(()); + return Ok(()) } Self::try_mutate_account(who, |account, _is_new| -> DispatchResult { Self::deposit_consequence(who, amount, &account).into_result()?; @@ -1109,7 +1112,7 @@ impl, I: 'static> fungible::Mutate for Pallet { Ok(()) })?; TotalIssuance::::mutate(|t| *t += amount); - Self::deposit_event(Event::Deposit{who: who.clone(), deposit: amount}); + Self::deposit_event(Event::Deposit { who: who.clone(), deposit: amount }); Ok(()) } @@ -1118,7 +1121,7 @@ impl, I: 'static> fungible::Mutate for Pallet { amount: Self::Balance, ) -> Result { if amount.is_zero() { - return Ok(Self::Balance::zero()); + return Ok(Self::Balance::zero()) } let actual = Self::try_mutate_account( who, @@ -1130,7 +1133,7 @@ impl, I: 'static> fungible::Mutate for Pallet { }, )?; TotalIssuance::::mutate(|t| *t -= actual); - Self::deposit_event(Event::Withdraw{who: who.clone(), amount}); + Self::deposit_event(Event::Withdraw { who: who.clone(), amount }); Ok(actual) } } @@ -1151,7 +1154,11 @@ impl, I: 'static> fungible::Unbalanced for Pallet DispatchResult { Self::mutate_account(who, |account| { account.free = amount; - Self::deposit_event(Event::BalanceSet{who: who.clone(), free: account.free, reserved: account.reserved}); + Self::deposit_event(Event::BalanceSet { + who: who.clone(), + free: account.free, + reserved: account.reserved, + }); })?; Ok(()) } @@ -1169,7 +1176,7 @@ impl, I: 'static> fungible::InspectHold for Pallet, I: 'static> fungible::InspectHold for Pallet, I: 'static> fungible::MutateHold for Pallet { fn hold(who: &T::AccountId, amount: Self::Balance) -> DispatchResult { if amount.is_zero() { - return Ok(()); + return Ok(()) } ensure!(Self::can_reserve(who, amount), Error::::InsufficientBalance); Self::mutate_account(who, |a| { @@ -1198,7 +1205,7 @@ impl, I: 'static> fungible::MutateHold for Pallet Result { if amount.is_zero() { - return Ok(amount); + return Ok(amount) } // Done on a best-effort basis. Self::try_mutate_account(who, |a, _| { @@ -1404,7 +1411,7 @@ where // Check if `value` amount of free balance can be slashed from `who`. fn can_slash(who: &T::AccountId, value: Self::Balance) -> bool { if value.is_zero() { - return true; + return true } Self::free_balance(who) >= value } @@ -1421,7 +1428,7 @@ where // Is a no-op if amount to be burned is zero. fn burn(mut amount: Self::Balance) -> Self::PositiveImbalance { if amount.is_zero() { - return PositiveImbalance::zero(); + return PositiveImbalance::zero() } >::mutate(|issued| { *issued = issued.checked_sub(&amount).unwrap_or_else(|| { @@ -1437,7 +1444,7 @@ where // Is a no-op if amount to be issued it zero. fn issue(mut amount: Self::Balance) -> Self::NegativeImbalance { if amount.is_zero() { - return NegativeImbalance::zero(); + return NegativeImbalance::zero() } >::mutate(|issued| { *issued = issued.checked_add(&amount).unwrap_or_else(|| { @@ -1467,7 +1474,7 @@ where new_balance: T::Balance, ) -> DispatchResult { if amount.is_zero() { - return Ok(()); + return Ok(()) } let min_balance = Self::account(who).frozen(reasons.into()); ensure!(new_balance >= min_balance, Error::::LiquidityRestrictions); @@ -1483,7 +1490,7 @@ where existence_requirement: ExistenceRequirement, ) -> DispatchResult { if value.is_zero() || transactor == dest { - return Ok(()); + return Ok(()) } Self::try_mutate_account_with_dust( @@ -1547,10 +1554,10 @@ where /// inconsistent or `can_slash` wasn't used appropriately. fn slash(who: &T::AccountId, value: Self::Balance) -> (Self::NegativeImbalance, Self::Balance) { if value.is_zero() { - return (NegativeImbalance::zero(), Zero::zero()); + return (NegativeImbalance::zero(), Zero::zero()) } if Self::total_balance(&who).is_zero() { - return (NegativeImbalance::zero(), value); + return (NegativeImbalance::zero(), value) } for attempt in 0..2 { @@ -1595,7 +1602,7 @@ where }, ) { Ok((imbalance, not_slashed)) => { - Self::deposit_event(Event::Slashed{ + Self::deposit_event(Event::Slashed { who: who.clone(), amount_slashed: value.saturating_sub(not_slashed), }); @@ -1617,7 +1624,7 @@ where value: Self::Balance, ) -> Result { if value.is_zero() { - return Ok(PositiveImbalance::zero()); + return Ok(PositiveImbalance::zero()) } Self::try_mutate_account( @@ -1625,7 +1632,7 @@ where |account, is_new| -> Result { ensure!(!is_new, Error::::DeadAccount); account.free = account.free.checked_add(&value).ok_or(ArithmeticError::Overflow)?; - Self::deposit_event(Event::Deposit{who: who.clone(), deposit: value}); + Self::deposit_event(Event::Deposit { who: who.clone(), deposit: value }); Ok(PositiveImbalance::new(value)) }, ) @@ -1642,7 +1649,7 @@ where /// - `value` is so large it would cause the balance of `who` to overflow. fn deposit_creating(who: &T::AccountId, value: Self::Balance) -> Self::PositiveImbalance { if value.is_zero() { - return Self::PositiveImbalance::zero(); + return Self::PositiveImbalance::zero() } let r = Self::try_mutate_account( @@ -1658,7 +1665,7 @@ where None => return Ok(Self::PositiveImbalance::zero()), }; - Self::deposit_event(Event::Deposit{who: who.clone(), deposit: value}); + Self::deposit_event(Event::Deposit { who: who.clone(), deposit: value }); Ok(PositiveImbalance::new(value)) }, ) @@ -1677,7 +1684,7 @@ where liveness: ExistenceRequirement, ) -> result::Result { if value.is_zero() { - return Ok(NegativeImbalance::zero()); + return Ok(NegativeImbalance::zero()) } Self::try_mutate_account( @@ -1696,7 +1703,7 @@ where account.free = new_free_account; - Self::deposit_event(Event::Withdraw{who: who.clone(), amount: value}); + Self::deposit_event(Event::Withdraw { who: who.clone(), amount: value }); Ok(NegativeImbalance::new(value)) }, ) @@ -1729,7 +1736,11 @@ where SignedImbalance::Negative(NegativeImbalance::new(account.free - value)) }; account.free = value; - Self::deposit_event(Event::BalanceSet{who: who.clone(), free: account.free, reserved: account.reserved}); + Self::deposit_event(Event::BalanceSet { + who: who.clone(), + free: account.free, + reserved: account.reserved, + }); Ok(imbalance) }, ) @@ -1746,7 +1757,7 @@ where /// Always `true` if value to be reserved is zero. fn can_reserve(who: &T::AccountId, value: Self::Balance) -> bool { if value.is_zero() { - return true; + return true } Self::account(who).free.checked_sub(&value).map_or(false, |new_balance| { Self::ensure_can_withdraw(who, value, WithdrawReasons::RESERVE, new_balance).is_ok() @@ -1762,7 +1773,7 @@ where /// Is a no-op if value to be reserved is zero. fn reserve(who: &T::AccountId, value: Self::Balance) -> DispatchResult { if value.is_zero() { - return Ok(()); + return Ok(()) } Self::try_mutate_account(who, |account, _| -> DispatchResult { @@ -1782,10 +1793,10 @@ where /// Is a no-op if the value to be unreserved is zero or the account does not exist. fn unreserve(who: &T::AccountId, value: Self::Balance) -> Self::Balance { if value.is_zero() { - return Zero::zero(); + return Zero::zero() } if Self::total_balance(&who).is_zero() { - return value; + return value } let actual = match Self::mutate_account(who, |account| { @@ -1801,8 +1812,8 @@ where // This should never happen since we don't alter the total amount in the account. // If it ever does, then we should fail gracefully though, indicating that nothing // could be done. - return value; - } + return value + }, }; Self::deposit_event(Event::Unreserved { who: who.clone(), value: actual.clone() }); @@ -1818,10 +1829,10 @@ where value: Self::Balance, ) -> (Self::NegativeImbalance, Self::Balance) { if value.is_zero() { - return (NegativeImbalance::zero(), Zero::zero()); + return (NegativeImbalance::zero(), Zero::zero()) } if Self::total_balance(&who).is_zero() { - return (NegativeImbalance::zero(), value); + return (NegativeImbalance::zero(), value) } // NOTE: `mutate_account` may fail if it attempts to reduce the balance to the point that an @@ -1846,7 +1857,7 @@ where (NegativeImbalance::new(actual), value - actual) }) { Ok((imbalance, not_slashed)) => { - Self::deposit_event(Event::Slashed{ + Self::deposit_event(Event::Slashed { who: who.clone(), amount_slashed: value.saturating_sub(not_slashed), }); @@ -1899,7 +1910,7 @@ where value: Self::Balance, ) -> DispatchResult { if value.is_zero() { - return Ok(()); + return Ok(()) } Reserves::::try_mutate(who, |reserves| -> DispatchResult { @@ -1907,12 +1918,12 @@ where Ok(index) => { // this add can't overflow but just to be defensive. reserves[index].amount = reserves[index].amount.saturating_add(value); - } + }, Err(index) => { reserves .try_insert(index, ReserveData { id: id.clone(), amount: value }) .map_err(|_| Error::::TooManyReserves)?; - } + }, }; >::reserve(who, value)?; Ok(()) @@ -1928,7 +1939,7 @@ where value: Self::Balance, ) -> Self::Balance { if value.is_zero() { - return Zero::zero(); + return Zero::zero() } Reserves::::mutate_exists(who, |maybe_reserves| -> Self::Balance { @@ -1956,7 +1967,7 @@ where } value - actual - } + }, Err(_) => value, } } else { @@ -1975,7 +1986,7 @@ where value: Self::Balance, ) -> (Self::NegativeImbalance, Self::Balance) { if value.is_zero() { - return (NegativeImbalance::zero(), Zero::zero()); + return (NegativeImbalance::zero(), Zero::zero()) } Reserves::::mutate(who, |reserves| -> (Self::NegativeImbalance, Self::Balance) { @@ -1992,9 +2003,12 @@ where // `actual <= to_change` and `to_change <= amount`; qed; reserves[index].amount -= actual; - Self::deposit_event(Event::Slashed{who: who.clone(), amount_slashed: actual}); + Self::deposit_event(Event::Slashed { + who: who.clone(), + amount_slashed: actual, + }); (imb, value - actual) - } + }, Err(_) => (NegativeImbalance::zero(), value), } }) @@ -2014,16 +2028,15 @@ where status: Status, ) -> Result { if value.is_zero() { - return Ok(Zero::zero()); + return Ok(Zero::zero()) } if slashed == beneficiary { return match status { Status::Free => Ok(Self::unreserve_named(id, slashed, value)), - Status::Reserved => { - Ok(value.saturating_sub(Self::reserved_balance_named(id, slashed))) - } - }; + Status::Reserved => + Ok(value.saturating_sub(Self::reserved_balance_named(id, slashed))), + } } Reserves::::try_mutate(slashed, |reserves| -> Result { @@ -2055,7 +2068,7 @@ where reserves[index].amount.saturating_add(actual); Ok(actual) - } + }, Err(index) => { let remain = >::repatriate_reserved( @@ -2077,7 +2090,7 @@ where .map_err(|_| Error::::TooManyReserves)?; Ok(actual) - } + }, } }, )? @@ -2097,7 +2110,7 @@ where reserves[index].amount -= actual; Ok(value - actual) - } + }, Err(_) => Ok(value), } }) @@ -2121,7 +2134,7 @@ where reasons: WithdrawReasons, ) { if amount.is_zero() || reasons.is_empty() { - return; + return } let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() }); let mut locks = Self::locks(who) @@ -2143,7 +2156,7 @@ where reasons: WithdrawReasons, ) { if amount.is_zero() || reasons.is_empty() { - return; + return } let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() }); let mut locks = Self::locks(who) diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index a6febf270c24a..cbeb867638e95 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -173,7 +173,10 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { assert_eq!(res, (NegativeImbalance::new(98), 0)); // no events - assert_eq!(events(), [Event::Balances(crate::Event::Slashed{who :1, amount_slashed: 98})]); + assert_eq!( + events(), + [Event::Balances(crate::Event::Slashed { who: 1, amount_slashed: 98 })] + ); let res = Balances::slash(&1, 1); assert_eq!(res, (NegativeImbalance::new(1), 0)); @@ -183,7 +186,7 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { [ Event::System(system::Event::KilledAccount(1)), Event::Balances(crate::Event::DustLost { account: 1, balance: 1 }), - Event::Balances(crate::Event::Slashed{who: 1, amount_slashed: 1}) + Event::Balances(crate::Event::Slashed { who: 1, amount_slashed: 1 }) ] ); }); diff --git a/frame/balances/src/tests_reentrancy.rs b/frame/balances/src/tests_reentrancy.rs index e171bb8629501..0e23384864222 100644 --- a/frame/balances/src/tests_reentrancy.rs +++ b/frame/balances/src/tests_reentrancy.rs @@ -178,7 +178,7 @@ fn transfer_dust_removal_tst1_should_work() { account: 2, balance: 50, })); - System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 50})); + System::assert_has_event(Event::Balances(crate::Event::Deposit { who: 1, deposit: 50 })); }); } @@ -213,7 +213,7 @@ fn transfer_dust_removal_tst2_should_work() { account: 2, balance: 50, })); - System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 50})); + System::assert_has_event(Event::Balances(crate::Event::Deposit { who: 1, deposit: 50 })); }); } @@ -259,6 +259,6 @@ fn repatriating_reserved_balance_dust_removal_should_work() { account: 2, balance: 50, })); - System::assert_last_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 50})); + System::assert_last_event(Event::Balances(crate::Event::Deposit { who: 1, deposit: 50 })); }); } diff --git a/frame/beefy-mmr/primitives/src/lib.rs b/frame/beefy-mmr/primitives/src/lib.rs index 9adae4a2935a7..4d4d4e8721ac8 100644 --- a/frame/beefy-mmr/primitives/src/lib.rs +++ b/frame/beefy-mmr/primitives/src/lib.rs @@ -113,7 +113,7 @@ where // swap collections to avoid allocations upper = next; next = t; - } + }, }; } } @@ -282,7 +282,7 @@ where L: Into>, { if leaf_index >= number_of_leaves { - return false; + return false } let leaf_hash = match leaf.into() { @@ -354,11 +354,11 @@ where combined[32..64].copy_from_slice(&b); next.push(H::hash(&combined)); - } + }, // Odd number of items. Promote the item to the upper layer. (Some(a), None) if !next.is_empty() => { next.push(a); - } + }, // Last item = root. (Some(a), None) => return Ok(a), // Finish up, no more items. @@ -368,8 +368,8 @@ where "[merkelize_row] Next: {:?}", next.iter().map(hex::encode).collect::>() ); - return Err(next); - } + return Err(next) + }, } } } diff --git a/frame/beefy-mmr/src/lib.rs b/frame/beefy-mmr/src/lib.rs index fc47477ef3a8a..001831639b169 100644 --- a/frame/beefy-mmr/src/lib.rs +++ b/frame/beefy-mmr/src/lib.rs @@ -219,7 +219,7 @@ where let current_next = Self::beefy_next_authorities(); // avoid computing the merkle tree if validator set id didn't change. if id == current_next.id { - return current_next; + return current_next } let beefy_addresses = pallet_beefy::Pallet::::next_authorities() diff --git a/frame/beefy/src/lib.rs b/frame/beefy/src/lib.rs index ed6102f6aafde..3b28d454849cf 100644 --- a/frame/beefy/src/lib.rs +++ b/frame/beefy/src/lib.rs @@ -123,7 +123,7 @@ impl Pallet { fn initialize_authorities(authorities: &[T::BeefyId]) { if authorities.is_empty() { - return; + return } assert!(>::get().is_empty(), "Authorities are already initialized!"); diff --git a/frame/benchmarking/src/analysis.rs b/frame/benchmarking/src/analysis.rs index 63ee55febb4a8..2bb20ebe2e7f8 100644 --- a/frame/benchmarking/src/analysis.rs +++ b/frame/benchmarking/src/analysis.rs @@ -78,7 +78,7 @@ impl Analysis { // results. Note: We choose the median value because it is more robust to outliers. fn median_value(r: &Vec, selector: BenchmarkSelector) -> Option { if r.is_empty() { - return None; + return None } let mut values: Vec = r @@ -106,7 +106,7 @@ impl Analysis { pub fn median_slopes(r: &Vec, selector: BenchmarkSelector) -> Option { if r[0].components.is_empty() { - return Self::median_value(r, selector); + return Self::median_value(r, selector) } let results = r[0] @@ -201,7 +201,7 @@ impl Analysis { pub fn min_squares_iqr(r: &Vec, selector: BenchmarkSelector) -> Option { if r[0].components.is_empty() { - return Self::median_value(r, selector); + return Self::median_value(r, selector) } let mut results = BTreeMap::, Vec>::new(); @@ -257,7 +257,7 @@ impl Analysis { .map(|(p, vs)| { // Avoid divide by zero if vs.len() == 0 { - return (p.clone(), 0, 0); + return (p.clone(), 0, 0) } let total = vs.iter().fold(0u128, |acc, v| acc + *v); let mean = total / vs.len() as u128; @@ -284,7 +284,7 @@ impl Analysis { let min_squares = Self::min_squares_iqr(r, selector); if median_slopes.is_none() || min_squares.is_none() { - return None; + return None } let median_slopes = median_slopes.unwrap(); @@ -316,7 +316,7 @@ fn ms(mut nanos: u128) -> String { while x > 1 { if nanos > x * 1_000 { nanos = nanos / x * x; - break; + break } x /= 10; } diff --git a/frame/benchmarking/src/lib.rs b/frame/benchmarking/src/lib.rs index b9807ca2ea355..1805424426f6e 100644 --- a/frame/benchmarking/src/lib.rs +++ b/frame/benchmarking/src/lib.rs @@ -905,7 +905,7 @@ macro_rules! impl_bench_name_tests { // Every variant must implement [`BenchmarkingSetup`]. // // ```nocompile -// +// // struct Transfer; // impl BenchmarkingSetup for Transfer { ... } // diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index 0d7da7fc7bc61..a2cf381e6ecf8 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -65,7 +65,7 @@ mod pallet_test { #[pallet::weight(0)] pub fn always_error(_origin: OriginFor) -> DispatchResult { - return Err("I always fail".into()); + return Err("I always fail".into()) } } } diff --git a/frame/benchmarking/src/utils.rs b/frame/benchmarking/src/utils.rs index ce8e0133a6de7..c24ad2f64e18d 100644 --- a/frame/benchmarking/src/utils.rs +++ b/frame/benchmarking/src/utils.rs @@ -258,11 +258,11 @@ pub trait Benchmarking { item.reads += add.reads; item.writes += add.writes; item.whitelisted = item.whitelisted || add.whitelisted; - } + }, // If the key does not exist, add it. None => { whitelist.push(add); - } + }, } self.set_whitelist(whitelist); } diff --git a/frame/bounties/src/lib.rs b/frame/bounties/src/lib.rs index 33132c160e864..5c96fdcc6b98f 100644 --- a/frame/bounties/src/lib.rs +++ b/frame/bounties/src/lib.rs @@ -342,7 +342,7 @@ pub mod pallet { Bounties::::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult { let mut bounty = maybe_bounty.as_mut().ok_or(Error::::InvalidIndex)?; match bounty.status { - BountyStatus::Proposed | BountyStatus::Approved | BountyStatus::Funded => {} + BountyStatus::Proposed | BountyStatus::Approved | BountyStatus::Funded => {}, _ => return Err(Error::::UnexpectedStatus.into()), }; @@ -395,13 +395,13 @@ pub mod pallet { match bounty.status { BountyStatus::Proposed | BountyStatus::Approved | BountyStatus::Funded => { // No curator to unassign at this point. - return Err(Error::::UnexpectedStatus.into()); - } + return Err(Error::::UnexpectedStatus.into()) + }, BountyStatus::CuratorProposed { ref curator } => { // A curator has been proposed, but not accepted yet. // Either `RejectOrigin` or the proposed curator can unassign the curator. ensure!(maybe_sender.map_or(true, |sender| sender == *curator), BadOrigin); - } + }, BountyStatus::Active { ref curator, ref update_due } => { // The bounty is active. match maybe_sender { @@ -409,7 +409,7 @@ pub mod pallet { None => { slash_curator(curator, &mut bounty.curator_deposit); // Continue to change bounty status below... - } + }, Some(sender) => { // If the sender is not the curator, and the curator is inactive, // slash the curator. @@ -420,7 +420,7 @@ pub mod pallet { // Continue to change bounty status below... } else { // Curator has more time to give an update. - return Err(Error::::Premature.into()); + return Err(Error::::Premature.into()) } } else { // Else this is the curator, willingly giving up their role. @@ -430,9 +430,9 @@ pub mod pallet { debug_assert!(err_amount.is_zero()); // Continue to change bounty status below... } - } + }, } - } + }, BountyStatus::PendingPayout { ref curator, .. } => { // The bounty is pending payout, so only council can unassign a curator. // By doing so, they are claiming the curator is acting maliciously, so @@ -440,7 +440,7 @@ pub mod pallet { ensure!(maybe_sender.is_none(), BadOrigin); slash_curator(curator, &mut bounty.curator_deposit); // Continue to change bounty status below... - } + }, }; bounty.status = BountyStatus::Funded; @@ -475,13 +475,13 @@ pub mod pallet { T::Currency::reserve(curator, deposit)?; bounty.curator_deposit = deposit; - let update_due = frame_system::Pallet::::block_number() - + T::BountyUpdatePeriod::get(); + let update_due = frame_system::Pallet::::block_number() + + T::BountyUpdatePeriod::get(); bounty.status = BountyStatus::Active { curator: curator.clone(), update_due }; Ok(()) - } + }, _ => Err(Error::::UnexpectedStatus.into()), } })?; @@ -513,14 +513,14 @@ pub mod pallet { match &bounty.status { BountyStatus::Active { curator, .. } => { ensure!(signer == *curator, Error::::RequireCurator); - } + }, _ => return Err(Error::::UnexpectedStatus.into()), } bounty.status = BountyStatus::PendingPayout { curator: signer, beneficiary: beneficiary.clone(), - unlock_at: frame_system::Pallet::::block_number() - + T::BountyDepositPayoutDelay::get(), + unlock_at: frame_system::Pallet::::block_number() + + T::BountyDepositPayoutDelay::get(), }; Ok(()) @@ -623,30 +623,30 @@ pub mod pallet { // Return early, nothing else to do. return Ok( Some(::WeightInfo::close_bounty_proposed()).into() - ); - } + ) + }, BountyStatus::Approved => { // For weight reasons, we don't allow a council to cancel in this phase. // We ask for them to wait until it is funded before they can cancel. - return Err(Error::::UnexpectedStatus.into()); - } + return Err(Error::::UnexpectedStatus.into()) + }, BountyStatus::Funded | BountyStatus::CuratorProposed { .. } => { // Nothing extra to do besides the removal of the bounty below. - } + }, BountyStatus::Active { curator, .. } => { // Cancelled by council, refund deposit of the working curator. let err_amount = T::Currency::unreserve(&curator, bounty.curator_deposit); debug_assert!(err_amount.is_zero()); // Then execute removal of the bounty below. - } + }, BountyStatus::PendingPayout { .. } => { // Bounty is already pending payout. If council wants to cancel // this bounty, it should mean the curator was acting maliciously. // So the council should first unassign the curator, slashing their // deposit. - return Err(Error::::PendingPayout.into()); - } + return Err(Error::::PendingPayout.into()) + }, } let bounty_account = Self::bounty_account_id(bounty_id); @@ -693,10 +693,10 @@ pub mod pallet { match bounty.status { BountyStatus::Active { ref curator, ref mut update_due } => { ensure!(*curator == signer, Error::::RequireCurator); - *update_due = (frame_system::Pallet::::block_number() - + T::BountyUpdatePeriod::get()) + *update_due = (frame_system::Pallet::::block_number() + + T::BountyUpdatePeriod::get()) .max(*update_due); - } + }, _ => return Err(Error::::UnexpectedStatus.into()), } @@ -741,8 +741,8 @@ impl Pallet { let index = Self::bounty_count(); // reserve deposit for new bounty - let bond = T::BountyDepositBase::get() - + T::DataDepositPerByte::get() * (description.len() as u32).into(); + let bond = T::BountyDepositBase::get() + + T::DataDepositPerByte::get() * (description.len() as u32).into(); T::Currency::reserve(&proposer, bond) .map_err(|_| Error::::InsufficientProposersBalance)?; diff --git a/frame/bounties/src/migrations/v4.rs b/frame/bounties/src/migrations/v4.rs index d39e2c317ca06..a1ca0e47680b0 100644 --- a/frame/bounties/src/migrations/v4.rs +++ b/frame/bounties/src/migrations/v4.rs @@ -54,7 +54,7 @@ pub fn migrate< target: "runtime::bounties", "New pallet name is equal to the old prefix. No migration needs to be done.", ); - return 0; + return 0 } let on_chain_storage_version =

::on_chain_storage_version(); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index cdb554944499d..dd70acfddee02 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -604,7 +604,7 @@ pub mod pallet { if position_yes.is_none() { voting.ayes.push(who.clone()); } else { - return Err(Error::::DuplicateVote.into()); + return Err(Error::::DuplicateVote.into()) } if let Some(pos) = position_no { voting.nays.swap_remove(pos); @@ -613,7 +613,7 @@ pub mod pallet { if position_no.is_none() { voting.nays.push(who.clone()); } else { - return Err(Error::::DuplicateVote.into()); + return Err(Error::::DuplicateVote.into()) } if let Some(pos) = position_yes { voting.ayes.swap_remove(pos); @@ -719,7 +719,7 @@ pub mod pallet { ), Pays::Yes, ) - .into()); + .into()) } else if disapproved { Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes }); let proposal_count = Self::do_disapprove_proposal(proposal_hash); @@ -727,7 +727,7 @@ pub mod pallet { Some(T::WeightInfo::close_early_disapproved(seats, proposal_count)), Pays::No, ) - .into()); + .into()) } // Only allow actual closing of the proposal after the voting period has ended. diff --git a/frame/collective/src/migrations/v4.rs b/frame/collective/src/migrations/v4.rs index f1537c97cd57a..68284ba4df91d 100644 --- a/frame/collective/src/migrations/v4.rs +++ b/frame/collective/src/migrations/v4.rs @@ -45,7 +45,7 @@ pub fn migrate::on_chain_storage_version(); @@ -84,7 +84,7 @@ pub fn pre_migrate>(old_p log_migration("pre-migration", old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return; + return } let new_pallet_prefix = twox_128(new_pallet_name.as_bytes()); @@ -112,7 +112,7 @@ pub fn post_migrate>(old_ log_migration("post-migration", old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return; + return } // Assert that nothing remains at the old prefix. diff --git a/frame/contracts/proc-macro/src/lib.rs b/frame/contracts/proc-macro/src/lib.rs index e3bf0f1aac86f..302a0d01a93d9 100644 --- a/frame/contracts/proc-macro/src/lib.rs +++ b/frame/contracts/proc-macro/src/lib.rs @@ -55,7 +55,7 @@ fn derive_debug( name.span() => compile_error!("WeightDebug is only supported for structs."); } - .into(); + .into() }; #[cfg(feature = "full")] @@ -90,7 +90,7 @@ fn iterate_fields(data: &DataStruct, fmt: impl Fn(&Ident) -> TokenStream) -> Tok let recurse = fields.named.iter().filter_map(|f| { let name = f.ident.as_ref()?; if name.to_string().starts_with('_') { - return None; + return None } let value = fmt(name); let ret = quote_spanned! { f.span() => @@ -101,7 +101,7 @@ fn iterate_fields(data: &DataStruct, fmt: impl Fn(&Ident) -> TokenStream) -> Tok quote! { #( #recurse )* } - } + }, Fields::Unnamed(fields) => quote_spanned! { fields.span() => compile_error!("Unnamed fields are not supported") diff --git a/frame/contracts/src/benchmarking/code.rs b/frame/contracts/src/benchmarking/code.rs index 8524add953c92..b24005ec58699 100644 --- a/frame/contracts/src/benchmarking/code.rs +++ b/frame/contracts/src/benchmarking/code.rs @@ -490,14 +490,14 @@ pub mod body { let current = *offset; *offset += *increment_by; vec![Instruction::I32Const(current as i32)] - } + }, DynInstr::RandomUnaligned(low, high) => { let unaligned = rng.gen_range(*low, *high) | 1; vec![Instruction::I32Const(unaligned as i32)] - } + }, DynInstr::RandomI32(low, high) => { vec![Instruction::I32Const(rng.gen_range(*low, *high))] - } + }, DynInstr::RandomI32Repeated(num) => (&mut rng) .sample_iter(Standard) .take(*num) @@ -510,19 +510,19 @@ pub mod body { .collect(), DynInstr::RandomGetLocal(low, high) => { vec![Instruction::GetLocal(rng.gen_range(*low, *high))] - } + }, DynInstr::RandomSetLocal(low, high) => { vec![Instruction::SetLocal(rng.gen_range(*low, *high))] - } + }, DynInstr::RandomTeeLocal(low, high) => { vec![Instruction::TeeLocal(rng.gen_range(*low, *high))] - } + }, DynInstr::RandomGetGlobal(low, high) => { vec![Instruction::GetGlobal(rng.gen_range(*low, *high))] - } + }, DynInstr::RandomSetGlobal(low, high) => { vec![Instruction::SetGlobal(rng.gen_range(*low, *high))] - } + }, }) .chain(sp_std::iter::once(Instruction::End)) .collect(); diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index dd78f2cbfa608..7fa0b0b274449 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -577,7 +577,7 @@ where let executable = E::from_storage(contract.code_hash, schedule, gas_meter)?; (dest, contract, executable, ExportedFunction::Call) - } + }, FrameArgs::Instantiate { sender, trie_seed, executable, salt } => { let account_id = >::contract_address(&sender, executable.code_hash(), &salt); @@ -588,7 +588,7 @@ where executable.code_hash().clone(), )?; (account_id, contract, executable, ExportedFunction::Constructor) - } + }, }; let frame = Frame { @@ -611,7 +611,7 @@ where gas_limit: Weight, ) -> Result { if self.frames.len() == T::CallStack::size() { - return Err(Error::::MaxCallDepthReached.into()); + return Err(Error::::MaxCallDepthReached.into()) } if CONTRACT_INFO_CAN_CHANGE { @@ -656,7 +656,7 @@ where // It is not allowed to terminate a contract inside its constructor. if let CachedContract::Terminated = frame.contract_info { - return Err(Error::::TerminatedInConstructor.into()); + return Err(Error::::TerminatedInConstructor.into()) } // Deposit an instantiation event. @@ -704,7 +704,7 @@ where prev.nested_meter.absorb_nested(frame.nested_meter); // Only gas counter changes are persisted in case of a failure. if !persist { - return; + return } if let CachedContract::Cached(contract) = frame.contract_info { // optimization: Predecessor is the same contract. @@ -713,7 +713,7 @@ where // trigger a rollback. if prev.account_id == *account_id { prev.contract_info = CachedContract::Cached(contract); - return; + return } // Predecessor is a different contract: We persist the info and invalidate the first @@ -738,7 +738,7 @@ where self.gas_meter.absorb_nested(mem::take(&mut self.first_frame.nested_meter)); // Only gas counter changes are persisted in case of a failure. if !persist { - return; + return } if let CachedContract::Cached(contract) = &self.first_frame.contract_info { >::insert(&self.first_frame.account_id, contract.clone()); @@ -763,19 +763,19 @@ where value: BalanceOf, ) -> DispatchResult { if value == 0u32.into() { - return Ok(()); + return Ok(()) } let existence_requirement = match (allow_death, sender_is_contract) { (true, _) => ExistenceRequirement::AllowDeath, (false, true) => { ensure!( - T::Currency::total_balance(from).saturating_sub(value) - >= Contracts::::subsistence_threshold(), + T::Currency::total_balance(from).saturating_sub(value) >= + Contracts::::subsistence_threshold(), Error::::BelowSubsistenceThreshold, ); ExistenceRequirement::KeepAlive - } + }, (false, false) => ExistenceRequirement::KeepAlive, }; @@ -795,7 +795,7 @@ where // we can error out early. This avoids executing the constructor in cases where // we already know that the contract has too little balance. if frame.entry_point == ExportedFunction::Constructor && value < subsistence_threshold { - return Err(>::NewContractNotFunded.into()); + return Err(>::NewContractNotFunded.into()) } Self::transfer(self.caller_is_origin(), false, self.caller(), &frame.account_id, value) @@ -879,7 +879,7 @@ where let try_call = || { if !self.allows_reentry(&to) { - return Err(>::ReentranceDenied.into()); + return Err(>::ReentranceDenied.into()) } // We ignore instantiate frames in our search for a cached contract. // Otherwise it would be possible to recursively call a contract from its own @@ -931,7 +931,7 @@ where fn terminate(&mut self, beneficiary: &AccountIdOf) -> Result<(), DispatchError> { if self.is_recursive() { - return Err(Error::::TerminatedWhileReentrant.into()); + return Err(Error::::TerminatedWhileReentrant.into()) } let frame = self.top_frame_mut(); let info = frame.terminate(); diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index cb74779ec459e..62b74b9b7b954 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -729,10 +729,9 @@ where >::CodeTooLarge ); executable - } - Code::Existing(hash) => { - PrefabWasmModule::from_storage(hash, &schedule, &mut gas_meter)? - } + }, + Code::Existing(hash) => + PrefabWasmModule::from_storage(hash, &schedule, &mut gas_meter)?, }; ExecStack::>::run_instantiate( origin, diff --git a/frame/contracts/src/schedule.rs b/frame/contracts/src/schedule.rs index 1c1a6754dbe8f..c14165b4c6aec 100644 --- a/frame/contracts/src/schedule.rs +++ b/frame/contracts/src/schedule.rs @@ -669,25 +669,25 @@ impl<'a, T: Config> rules::Rules for ScheduleRules<'a, T> { let weight = match *instruction { End | Unreachable | Return | Else => 0, I32Const(_) | I64Const(_) | Block(_) | Loop(_) | Nop | Drop => w.i64const, - I32Load(_, _) - | I32Load8S(_, _) - | I32Load8U(_, _) - | I32Load16S(_, _) - | I32Load16U(_, _) - | I64Load(_, _) - | I64Load8S(_, _) - | I64Load8U(_, _) - | I64Load16S(_, _) - | I64Load16U(_, _) - | I64Load32S(_, _) - | I64Load32U(_, _) => w.i64load, - I32Store(_, _) - | I32Store8(_, _) - | I32Store16(_, _) - | I64Store(_, _) - | I64Store8(_, _) - | I64Store16(_, _) - | I64Store32(_, _) => w.i64store, + I32Load(_, _) | + I32Load8S(_, _) | + I32Load8U(_, _) | + I32Load16S(_, _) | + I32Load16U(_, _) | + I64Load(_, _) | + I64Load8S(_, _) | + I64Load8U(_, _) | + I64Load16S(_, _) | + I64Load16U(_, _) | + I64Load32S(_, _) | + I64Load32U(_, _) => w.i64load, + I32Store(_, _) | + I32Store8(_, _) | + I32Store16(_, _) | + I64Store(_, _) | + I64Store8(_, _) | + I64Store16(_, _) | + I64Store32(_, _) => w.i64store, Select => w.select, If(_) => w.r#if, Br(_) => w.br, diff --git a/frame/contracts/src/storage.rs b/frame/contracts/src/storage.rs index 702f219fdda8a..41db0796717e4 100644 --- a/frame/contracts/src/storage.rs +++ b/frame/contracts/src/storage.rs @@ -115,7 +115,7 @@ where ch: CodeHash, ) -> Result, DispatchError> { if >::contains_key(account) { - return Err(Error::::DuplicateContract.into()); + return Err(Error::::DuplicateContract.into()) } let contract = ContractInfo:: { code_hash: ch, trie_id, _reserved: None }; @@ -140,10 +140,10 @@ where /// and weight limit. pub fn deletion_budget(queue_len: usize, weight_limit: Weight) -> (u64, u32) { let base_weight = T::WeightInfo::on_initialize(); - let weight_per_queue_item = T::WeightInfo::on_initialize_per_queue_item(1) - - T::WeightInfo::on_initialize_per_queue_item(0); - let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - - T::WeightInfo::on_initialize_per_trie_key(0); + let weight_per_queue_item = T::WeightInfo::on_initialize_per_queue_item(1) - + T::WeightInfo::on_initialize_per_queue_item(0); + let weight_per_key = T::WeightInfo::on_initialize_per_trie_key(1) - + T::WeightInfo::on_initialize_per_trie_key(0); let decoding_weight = weight_per_queue_item.saturating_mul(queue_len as Weight); // `weight_per_key` being zero makes no sense and would constitute a failure to @@ -163,7 +163,7 @@ where pub fn process_deletion_queue_batch(weight_limit: Weight) -> Weight { let queue_len = >::decode_len().unwrap_or(0); if queue_len == 0 { - return 0; + return 0 } let (weight_per_key, mut remaining_key_budget) = @@ -173,7 +173,7 @@ where // proceeding. Too little weight for decoding might happen during runtime upgrades // which consume the whole block before the other `on_initialize` blocks are called. if remaining_key_budget == 0 { - return weight_limit; + return weight_limit } let mut queue = >::get(); @@ -189,7 +189,7 @@ where // noone waits for the trie to be deleted. queue.swap_remove(0); count - } + }, }; remaining_key_budget = remaining_key_budget.saturating_sub(keys_removed); } diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 4b3aa0bfa3c6e..226cc087600b6 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -162,7 +162,7 @@ impl ChainExtension for TestExtension { env.write(&input, false, None)?; TEST_EXTENSION.with(|e| e.borrow_mut().last_seen_buffer = input); Ok(RetVal::Converging(func_id)) - } + }, 1 => { let env = env.only_in(); TEST_EXTENSION.with(|e| { @@ -170,17 +170,17 @@ impl ChainExtension for TestExtension { (env.val0(), env.val1(), env.val2(), env.val3()) }); Ok(RetVal::Converging(func_id)) - } + }, 2 => { let mut env = env.buf_in_buf_out(); let weight = env.read(2)?[1].into(); env.charge_weight(weight)?; Ok(RetVal::Converging(func_id)) - } + }, 3 => Ok(RetVal::Diverging { flags: ReturnFlags::REVERT, data: vec![42, 99] }), _ => { panic!("Passed unknown func_id to test chain extension: {}", func_id); - } + }, } } @@ -446,7 +446,10 @@ fn instantiate_and_call_and_deposit_event() { vec![ EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Deposit{who: ALICE, deposit: 1_000_000}), + event: Event::Balances(pallet_balances::Event::Deposit { + who: ALICE, + deposit: 1_000_000 + }), topics: vec![], }, EventRecord { @@ -456,7 +459,10 @@ fn instantiate_and_call_and_deposit_event() { }, EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Endowed{account: ALICE, free_balance: 1_000_000}), + event: Event::Balances(pallet_balances::Event::Endowed { + account: ALICE, + free_balance: 1_000_000 + }), topics: vec![], }, EventRecord { @@ -466,7 +472,7 @@ fn instantiate_and_call_and_deposit_event() { }, EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Endowed{ + event: Event::Balances(pallet_balances::Event::Endowed { account: addr.clone(), free_balance: subsistence * 100 }), @@ -474,7 +480,7 @@ fn instantiate_and_call_and_deposit_event() { }, EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Transfer{ + event: Event::Balances(pallet_balances::Event::Transfer { from: ALICE, to: addr.clone(), value: subsistence * 100 @@ -765,7 +771,7 @@ fn self_destruct_works() { }, EventRecord { phase: Phase::Initialization, - event: Event::Balances(pallet_balances::Event::Transfer{ + event: Event::Balances(pallet_balances::Event::Transfer { from: addr.clone(), to: DJANGO, value: 100_000, diff --git a/frame/contracts/src/wasm/code_cache.rs b/frame/contracts/src/wasm/code_cache.rs index b080aa5d2d8c1..afb68d4d81179 100644 --- a/frame/contracts/src/wasm/code_cache.rs +++ b/frame/contracts/src/wasm/code_cache.rs @@ -60,7 +60,7 @@ where None => { *existing = Some(prefab_module); Contracts::::deposit_event(Event::CodeStored { code_hash }) - } + }, }); } @@ -230,9 +230,8 @@ where // the contract. match *self { Instrument(len) => T::WeightInfo::instrument(len / 1024), - Load(len) => { - T::WeightInfo::code_load(len / 1024).saturating_sub(T::WeightInfo::code_load(0)) - } + Load(len) => + T::WeightInfo::code_load(len / 1024).saturating_sub(T::WeightInfo::code_load(0)), UpdateRefcount(len) => T::WeightInfo::code_refcount(len / 1024) .saturating_sub(T::WeightInfo::code_refcount(0)), } diff --git a/frame/contracts/src/wasm/prepare.rs b/frame/contracts/src/wasm/prepare.rs index 77600ea026ffe..c766914f3d46e 100644 --- a/frame/contracts/src/wasm/prepare.rs +++ b/frame/contracts/src/wasm/prepare.rs @@ -64,7 +64,7 @@ impl<'a, T: Config> ContractModule<'a, T> { /// we reject such a module. fn ensure_no_internal_memory(&self) -> Result<(), &'static str> { if self.module.memory_section().map_or(false, |ms| ms.entries().len() > 0) { - return Err("module declares internal memory"); + return Err("module declares internal memory") } Ok(()) } @@ -75,13 +75,13 @@ impl<'a, T: Config> ContractModule<'a, T> { // In Wasm MVP spec, there may be at most one table declared. Double check this // explicitly just in case the Wasm version changes. if table_section.entries().len() > 1 { - return Err("multiple tables declared"); + return Err("multiple tables declared") } if let Some(table_type) = table_section.entries().first() { // Check the table's initial size as there is no instruction or environment function // capable of growing the table. if table_type.limits().initial() > limit { - return Err("table exceeds maximum size allowed"); + return Err("table exceeds maximum size allowed") } } } @@ -93,13 +93,13 @@ impl<'a, T: Config> ContractModule<'a, T> { let code_section = if let Some(type_section) = self.module.code_section() { type_section } else { - return Ok(()); + return Ok(()) }; for instr in code_section.bodies().iter().flat_map(|body| body.code().elements()) { use self::elements::Instruction::BrTable; if let BrTable(table) = instr { if table.table.len() > limit as usize { - return Err("BrTable's immediate value is too big."); + return Err("BrTable's immediate value is too big.") } } } @@ -109,7 +109,7 @@ impl<'a, T: Config> ContractModule<'a, T> { fn ensure_global_variable_limit(&self, limit: u32) -> Result<(), &'static str> { if let Some(global_section) = self.module.global_section() { if global_section.entries().len() > limit as usize { - return Err("module declares too many globals"); + return Err("module declares too many globals") } } Ok(()) @@ -120,10 +120,9 @@ impl<'a, T: Config> ContractModule<'a, T> { if let Some(global_section) = self.module.global_section() { for global in global_section.entries() { match global.global_type().content_type() { - ValueType::F32 | ValueType::F64 => { - return Err("use of floating point type in globals is forbidden") - } - _ => {} + ValueType::F32 | ValueType::F64 => + return Err("use of floating point type in globals is forbidden"), + _ => {}, } } } @@ -132,10 +131,9 @@ impl<'a, T: Config> ContractModule<'a, T> { for func_body in code_section.bodies() { for local in func_body.locals() { match local.value_type() { - ValueType::F32 | ValueType::F64 => { - return Err("use of floating point type in locals is forbidden") - } - _ => {} + ValueType::F32 | ValueType::F64 => + return Err("use of floating point type in locals is forbidden"), + _ => {}, } } } @@ -148,15 +146,14 @@ impl<'a, T: Config> ContractModule<'a, T> { let return_type = func_type.results().get(0); for value_type in func_type.params().iter().chain(return_type) { match value_type { - ValueType::F32 | ValueType::F64 => { + ValueType::F32 | ValueType::F64 => return Err( "use of floating point type in function types is forbidden", - ) - } - _ => {} + ), + _ => {}, } } - } + }, } } } @@ -169,12 +166,12 @@ impl<'a, T: Config> ContractModule<'a, T> { let type_section = if let Some(type_section) = self.module.type_section() { type_section } else { - return Ok(()); + return Ok(()) }; for Type::Function(func) in type_section.types() { if func.params().len() > limit as usize { - return Err("Use of a function type with too many parameters."); + return Err("Use of a function type with too many parameters.") } } @@ -247,8 +244,8 @@ impl<'a, T: Config> ContractModule<'a, T> { Some(fn_idx) => fn_idx, None => { // Underflow here means fn_idx points to imported function which we don't allow! - return Err("entry point points to an imported function"); - } + return Err("entry point points to an imported function") + }, }; // Then check the signature. @@ -261,18 +258,18 @@ impl<'a, T: Config> ContractModule<'a, T> { let Type::Function(ref func_ty) = types .get(func_ty_idx as usize) .ok_or_else(|| "function has a non-existent type")?; - if !(func_ty.params().is_empty() - && (func_ty.results().is_empty() || func_ty.results() == [ValueType::I32])) + if !(func_ty.params().is_empty() && + (func_ty.results().is_empty() || func_ty.results() == [ValueType::I32])) { - return Err("entry point has wrong signature"); + return Err("entry point has wrong signature") } } if !deploy_found { - return Err("deploy function isn't exported"); + return Err("deploy function isn't exported") } if !call_found { - return Err("call function isn't exported"); + return Err("call function isn't exported") } Ok(()) @@ -303,33 +300,33 @@ impl<'a, T: Config> ContractModule<'a, T> { &External::Function(ref type_idx) => type_idx, &External::Memory(ref memory_type) => { if import.module() != IMPORT_MODULE_MEMORY { - return Err("Invalid module for imported memory"); + return Err("Invalid module for imported memory") } if import.field() != "memory" { - return Err("Memory import must have the field name 'memory'"); + return Err("Memory import must have the field name 'memory'") } if imported_mem_type.is_some() { - return Err("Multiple memory imports defined"); + return Err("Multiple memory imports defined") } imported_mem_type = Some(memory_type); - continue; - } + continue + }, }; let Type::Function(ref func_ty) = types .get(*type_idx as usize) .ok_or_else(|| "validation: import entry points to a non-existent type")?; - if !T::ChainExtension::enabled() - && import.field().as_bytes() == b"seal_call_chain_extension" + if !T::ChainExtension::enabled() && + import.field().as_bytes() == b"seal_call_chain_extension" { - return Err("module uses chain extensions but chain extensions are disabled"); + return Err("module uses chain extensions but chain extensions are disabled") } - if import_fn_banlist.iter().any(|f| import.field().as_bytes() == *f) - || !C::can_satisfy(import.module().as_bytes(), import.field().as_bytes(), func_ty) + if import_fn_banlist.iter().any(|f| import.field().as_bytes() == *f) || + !C::can_satisfy(import.module().as_bytes(), import.field().as_bytes(), func_ty) { - return Err("module imports a non-existent function"); + return Err("module imports a non-existent function") } } Ok(imported_mem_type) @@ -348,21 +345,19 @@ fn get_memory_limits( // Inspect the module to extract the initial and maximum page count. let limits = memory_type.limits(); match (limits.initial(), limits.maximum()) { - (initial, Some(maximum)) if initial > maximum => { + (initial, Some(maximum)) if initial > maximum => return Err( "Requested initial number of pages should not exceed the requested maximum", - ) - } - (_, Some(maximum)) if maximum > schedule.limits.memory_pages => { - return Err("Maximum number of pages should not exceed the configured maximum.") - } + ), + (_, Some(maximum)) if maximum > schedule.limits.memory_pages => + return Err("Maximum number of pages should not exceed the configured maximum."), (initial, Some(maximum)) => Ok((initial, maximum)), (_, None) => { // Maximum number of pages should be always declared. // This isn't a hard requirement and can be treated as a maximum set // to configured maximum. - return Err("Maximum number of pages should be always declared."); - } + return Err("Maximum number of pages should be always declared.") + }, } } else { // If none memory imported then just crate an empty placeholder. diff --git a/frame/contracts/src/wasm/runtime.rs b/frame/contracts/src/wasm/runtime.rs index fcf64ac78badd..52b864bf18eac 100644 --- a/frame/contracts/src/wasm/runtime.rs +++ b/frame/contracts/src/wasm/runtime.rs @@ -244,16 +244,14 @@ impl RuntimeCosts { .saturating_add(s.deposit_event_per_topic.saturating_mul(num_topic.into())) .saturating_add(s.deposit_event_per_byte.saturating_mul(len.into())), DebugMessage => s.debug_message, - SetStorage(len) => { - s.set_storage.saturating_add(s.set_storage_per_byte.saturating_mul(len.into())) - } + SetStorage(len) => + s.set_storage.saturating_add(s.set_storage_per_byte.saturating_mul(len.into())), ClearStorage => s.clear_storage, GetStorageBase => s.get_storage, GetStorageCopyOut(len) => s.get_storage_per_byte.saturating_mul(len.into()), Transfer => s.transfer, - CallBase(len) => { - s.call.saturating_add(s.call_per_input_byte.saturating_mul(len.into())) - } + CallBase(len) => + s.call.saturating_add(s.call_per_input_byte.saturating_mul(len.into())), CallSurchargeTransfer => s.call_transfer_surcharge, CallCopyOut(len) => s.call_per_output_byte.saturating_mul(len.into()), InstantiateBase { input_data_len, salt_len } => s @@ -390,12 +388,11 @@ where let flags = ReturnFlags::from_bits(flags) .ok_or_else(|| "used reserved bit in return flags")?; Ok(ExecReturnValue { flags, data: Bytes(data) }) - } - TrapReason::Termination => { - Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Bytes(Vec::new()) }) - } + }, + TrapReason::Termination => + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Bytes(Vec::new()) }), TrapReason::SupervisorError(error) => Err(error)?, - }; + } } // Check the exact type of the error. @@ -410,9 +407,8 @@ where // a trap for now. Eventually, we might want to revisit this. Err(sp_sandbox::Error::Module) => Err("validation error")?, // Any other kind of a trap should result in a failure. - Err(sp_sandbox::Error::Execution) | Err(sp_sandbox::Error::OutOfBounds) => { - Err(Error::::ContractTrapped)? - } + Err(sp_sandbox::Error::Execution) | Err(sp_sandbox::Error::OutOfBounds) => + Err(Error::::ContractTrapped)?, } } @@ -543,7 +539,7 @@ where create_token: impl FnOnce(u32) -> Option, ) -> Result<(), DispatchError> { if allow_skip && out_ptr == u32::MAX { - return Ok(()); + return Ok(()) } let buf_len = buf.len() as u32; @@ -677,7 +673,7 @@ where return Err(TrapReason::Return(ReturnData { flags: return_value.flags.bits(), data: return_value.data.0, - })); + })) } } diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index 78f8a8559cf4a..529bcebc8e374 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -1088,9 +1088,8 @@ pub mod pallet { let (provider, deposit, since, expiry) = >::get(&proposal_hash) .and_then(|m| match m { - PreimageStatus::Available { provider, deposit, since, expiry, .. } => { - Some((provider, deposit, since, expiry)) - } + PreimageStatus::Available { provider, deposit, since, expiry, .. } => + Some((provider, deposit, since, expiry)), _ => None, }) .ok_or(Error::::PreimageMissing)?; @@ -1377,14 +1376,14 @@ impl Pallet { status.tally.reduce(approve, *delegations); } votes[i].1 = vote; - } + }, Err(i) => { ensure!( votes.len() as u32 <= T::MaxVotes::get(), Error::::MaxVotesReached ); votes.insert(i, (ref_index, vote)); - } + }, } // Shouldn't be possible to fail, but we handle it gracefully. status.tally.add(vote).ok_or(ArithmeticError::Overflow)?; @@ -1429,7 +1428,7 @@ impl Pallet { status.tally.reduce(approve, *delegations); } ReferendumInfoOf::::insert(ref_index, ReferendumInfo::Ongoing(status)); - } + }, Some(ReferendumInfo::Finished { end, approved }) => { if let Some((lock_periods, balance)) = votes[i].1.locked_if(approved) { let unlock_at = end + T::VoteLockingPeriod::get() * lock_periods.into(); @@ -1442,8 +1441,8 @@ impl Pallet { prior.accumulate(unlock_at, balance) } } - } - None => {} // Referendum was cancelled. + }, + None => {}, // Referendum was cancelled. } votes.remove(i); } @@ -1459,7 +1458,7 @@ impl Pallet { // We don't support second level delegating, so we don't need to do anything more. *delegations = delegations.saturating_add(amount); 1 - } + }, Voting::Direct { votes, delegations, .. } => { *delegations = delegations.saturating_add(amount); for &(ref_index, account_vote) in votes.iter() { @@ -1472,7 +1471,7 @@ impl Pallet { } } votes.len() as u32 - } + }, }) } @@ -1483,7 +1482,7 @@ impl Pallet { // We don't support second level delegating, so we don't need to do anything more. *delegations = delegations.saturating_sub(amount); 1 - } + }, Voting::Direct { votes, delegations, .. } => { *delegations = delegations.saturating_sub(amount); for &(ref_index, account_vote) in votes.iter() { @@ -1496,7 +1495,7 @@ impl Pallet { } } votes.len() as u32 - } + }, }) } @@ -1525,12 +1524,12 @@ impl Pallet { // remove any delegation votes to our current target. Self::reduce_upstream_delegation(&target, conviction.votes(balance)); voting.set_common(delegations, prior); - } + }, Voting::Direct { votes, delegations, prior } => { // here we just ensure that we're currently idling with no votes recorded. ensure!(votes.is_empty(), Error::::VotesExist); voting.set_common(delegations, prior); - } + }, } let votes = Self::increase_upstream_delegation(&target, conviction.votes(balance)); // Extend the lock to `balance` (rather than setting it) since we don't know what other @@ -1560,7 +1559,7 @@ impl Pallet { voting.set_common(delegations, prior); Ok(votes) - } + }, Voting::Direct { .. } => Err(Error::::NotDelegating.into()), } })?; @@ -1706,9 +1705,8 @@ impl Pallet { Preimages::::mutate_exists( &status.proposal_hash, |maybe_pre| match *maybe_pre { - Some(PreimageStatus::Available { ref mut expiry, .. }) => { - *expiry = Some(when) - } + Some(PreimageStatus::Available { ref mut expiry, .. }) => + *expiry = Some(when), ref mut a => *a = Some(PreimageStatus::Missing(when)), }, ); @@ -1822,7 +1820,7 @@ impl Pallet { _ => { sp_runtime::print("Failed to decode `PreimageStatus` variant"); Err(Error::::NotImminent.into()) - } + }, } } @@ -1850,8 +1848,8 @@ impl Pallet { Ok(0) => return Err(Error::::PreimageMissing.into()), _ => { sp_runtime::print("Failed to decode `PreimageStatus` variant"); - return Err(Error::::PreimageMissing.into()); - } + return Err(Error::::PreimageMissing.into()) + }, } // Decode the length of the vector. @@ -1929,6 +1927,6 @@ fn decode_compact_u32_at(key: &[u8]) -> Option { sp_runtime::print("Failed to decode compact u32 at:"); sp_runtime::print(key); None - } + }, } } diff --git a/frame/democracy/src/types.rs b/frame/democracy/src/types.rs index e6c117b6ca655..2eb004ba61bc4 100644 --- a/frame/democracy/src/types.rs +++ b/frame/democracy/src/types.rs @@ -104,14 +104,14 @@ impl< true => self.ayes = self.ayes.checked_add(&votes)?, false => self.nays = self.nays.checked_add(&votes)?, } - } + }, AccountVote::Split { aye, nay } => { let aye = Conviction::None.votes(aye); let nay = Conviction::None.votes(nay); self.turnout = self.turnout.checked_add(&aye.capital)?.checked_add(&nay.capital)?; self.ayes = self.ayes.checked_add(&aye.votes)?; self.nays = self.nays.checked_add(&nay.votes)?; - } + }, } Some(()) } @@ -126,14 +126,14 @@ impl< true => self.ayes = self.ayes.checked_sub(&votes)?, false => self.nays = self.nays.checked_sub(&votes)?, } - } + }, AccountVote::Split { aye, nay } => { let aye = Conviction::None.votes(aye); let nay = Conviction::None.votes(nay); self.turnout = self.turnout.checked_sub(&aye.capital)?.checked_sub(&nay.capital)?; self.ayes = self.ayes.checked_sub(&aye.votes)?; self.nays = self.nays.checked_sub(&nay.votes)?; - } + }, } Some(()) } diff --git a/frame/democracy/src/vote.rs b/frame/democracy/src/vote.rs index 29f5bd7e6038c..03ca020ca0949 100644 --- a/frame/democracy/src/vote.rs +++ b/frame/democracy/src/vote.rs @@ -81,9 +81,8 @@ impl AccountVote { pub fn locked_if(self, approved: bool) -> Option<(u32, Balance)> { // winning side: can only be removed after the lock period ends. match self { - AccountVote::Standard { vote, balance } if vote.aye == approved => { - Some((vote.conviction.lock_periods(), balance)) - } + AccountVote::Standard { vote, balance } if vote.aye == approved => + Some((vote.conviction.lock_periods(), balance)), _ => None, } } @@ -182,9 +181,8 @@ impl Balance { match self { - Voting::Direct { votes, prior, .. } => { - votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)) - } + Voting::Direct { votes, prior, .. } => + votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)), Voting::Delegating { balance, .. } => *balance, } } diff --git a/frame/democracy/src/vote_threshold.rs b/frame/democracy/src/vote_threshold.rs index cd230bf558c24..ad8bce290ed4f 100644 --- a/frame/democracy/src/vote_threshold.rs +++ b/frame/democracy/src/vote_threshold.rs @@ -58,18 +58,18 @@ fn compare_rationals< let q1 = n1 / d1; let q2 = n2 / d2; if q1 < q2 { - return true; + return true } if q2 < q1 { - return false; + return false } let r1 = n1 % d1; let r2 = n2 % d2; if r2.is_zero() { - return false; + return false } if r1.is_zero() { - return true; + return true } n1 = d2; n2 = d1; @@ -93,15 +93,13 @@ impl< let sqrt_voters = tally.turnout.integer_sqrt(); let sqrt_electorate = electorate.integer_sqrt(); if sqrt_voters.is_zero() { - return false; + return false } match *self { - VoteThreshold::SuperMajorityApprove => { - compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate) - } - VoteThreshold::SuperMajorityAgainst => { - compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters) - } + VoteThreshold::SuperMajorityApprove => + compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate), + VoteThreshold::SuperMajorityAgainst => + compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters), VoteThreshold::SimpleMajority => tally.ayes > tally.nays, } } diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 3c712c08c29d1..101f24077f4e2 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -723,14 +723,14 @@ pub mod pallet { Ok(_) => { Self::on_initialize_open_signed(); T::WeightInfo::on_initialize_open_signed() - } + }, Err(why) => { // Not much we can do about this at this point. log!(warn, "failed to open signed phase due to {:?}", why); T::WeightInfo::on_initialize_nothing() - } + }, } - } + }, Phase::Signed | Phase::Off if remaining <= unsigned_deadline && remaining > Zero::zero() => { @@ -762,11 +762,11 @@ pub mod pallet { Ok(_) => { Self::on_initialize_open_unsigned(enabled, now); T::WeightInfo::on_initialize_open_unsigned() - } + }, Err(why) => { log!(warn, "failed to open unsigned phase due to {:?}", why); T::WeightInfo::on_initialize_nothing() - } + }, } } else { Self::on_initialize_open_unsigned(enabled, now); @@ -792,10 +792,10 @@ pub mod pallet { match lock.try_lock() { Ok(_guard) => { Self::do_synchronized_offchain_worker(now); - } + }, Err(deadline) => { log!(debug, "offchain worker lock not released, deadline is {:?}", deadline); - } + }, }; } @@ -958,8 +958,8 @@ pub mod pallet { // ensure witness data is correct. ensure!( - num_signed_submissions - >= >::decode_len().unwrap_or_default() as u32, + num_signed_submissions >= + >::decode_len().unwrap_or_default() as u32, Error::::SignedInvalidWitness, ); @@ -1077,7 +1077,7 @@ pub mod pallet { if let Call::submit_unsigned { raw_solution, .. } = call { // Discard solution not coming from the local OCW. match source { - TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ } + TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ }, _ => return InvalidTransaction::Call.into(), } @@ -1232,15 +1232,15 @@ impl Pallet { Self::mine_check_save_submit() }); log!(debug, "initial offchain thread output: {:?}", initial_output); - } + }, Phase::Unsigned((true, opened)) if opened < now => { // Try and resubmit the cached solution, and recompute ONLY if it is not // feasible. let resubmit_output = Self::ensure_offchain_repeat_frequency(now) .and_then(|_| Self::restore_or_compute_then_maybe_submit()); log!(debug, "resubmit offchain thread output: {:?}", resubmit_output); - } - _ => {} + }, + _ => {}, } } @@ -1310,7 +1310,7 @@ impl Pallet { // Defensive-only. if targets.len() > target_limit || voters.len() > voter_limit { debug_assert!(false, "Snapshot limit has not been respected."); - return Err(ElectionError::DataProvider("Snapshot too big for submission.")); + return Err(ElectionError::DataProvider("Snapshot too big for submission.")) } Ok((targets, voters, desired_targets)) @@ -1420,7 +1420,7 @@ impl Pallet { // Check that all of the targets are valid based on the snapshot. if assignment.distribution.iter().any(|(d, _)| !targets.contains(d)) { - return Err(FeasibilityError::InvalidVote); + return Err(FeasibilityError::InvalidVote) } Ok(()) }) @@ -1513,12 +1513,12 @@ impl ElectionProvider for Pallet { Self::weigh_supports(&supports); Self::rotate_round(); Ok(supports) - } + }, Err(why) => { log!(error, "Entering emergency mode: {:?}", why); >::put(Phase::Emergency); Err(why) - } + }, } } } @@ -2067,9 +2067,9 @@ mod tests { }; let mut active = 1; - while weight_with(active) - <= ::BlockWeights::get().max_block - || active == all_voters + while weight_with(active) <= + ::BlockWeights::get().max_block || + active == all_voters { active += 1; } diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index 5030ee5bcba49..1a65316be1f10 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -426,7 +426,7 @@ impl ElectionDataProvider for StakingMock { let targets = Targets::get(); if maybe_max_len.map_or(false, |max_len| targets.len() > max_len) { - return Err("Targets too big"); + return Err("Targets too big") } Ok(targets) diff --git a/frame/election-provider-multi-phase/src/signed.rs b/frame/election-provider-multi-phase/src/signed.rs index 89ba0047dd844..b762ad706486c 100644 --- a/frame/election-provider-multi-phase/src/signed.rs +++ b/frame/election-provider-multi-phase/src/signed.rs @@ -275,12 +275,12 @@ impl SignedSubmissions { self.indices .try_insert(submission.raw_solution.score, prev_idx) .expect("didn't change the map size; qed"); - return InsertResult::NotInserted; - } + return InsertResult::NotInserted + }, Ok(None) => { // successfully inserted into the set; no need to take out weakest member None - } + }, Err((insert_score, insert_idx)) => { // could not insert into the set because it is full. // note that we short-circuit return here in case the iteration produces `None`. @@ -294,11 +294,11 @@ impl SignedSubmissions { // if we haven't improved on the weakest score, don't change anything. if !is_score_better(insert_score, weakest_score, threshold) { - return InsertResult::NotInserted; + return InsertResult::NotInserted } self.swap_out_submission(weakest_score, Some((insert_score, insert_idx))) - } + }, }; // we've taken out the weakest, so update the storage map and the next index @@ -382,13 +382,13 @@ impl Pallet { weight = weight .saturating_add(T::WeightInfo::finalize_signed_phase_accept_solution()); - break; - } + break + }, Err(_) => { Self::finalize_signed_phase_reject_solution(&who, deposit); weight = weight .saturating_add(T::WeightInfo::finalize_signed_phase_reject_solution()); - } + }, } } @@ -429,7 +429,7 @@ impl Pallet { >::put(ready_solution); // emit reward event - Self::deposit_event(crate::Event::Rewarded{account: who.clone(), value: reward}); + Self::deposit_event(crate::Event::Rewarded { account: who.clone(), value: reward }); // unreserve deposit. let _remaining = T::Currency::unreserve(who, deposit); @@ -446,7 +446,7 @@ impl Pallet { /// /// Infallible pub fn finalize_signed_phase_reject_solution(who: &T::AccountId, deposit: BalanceOf) { - Self::deposit_event(crate::Event::Slashed{account: who.clone(), value: deposit}); + Self::deposit_event(crate::Event::Slashed { account: who.clone(), value: deposit }); let (negative_imbalance, _remaining) = T::Currency::slash_reserved(who, deposit); debug_assert!(_remaining.is_zero()); T::SlashHandler::on_unbalanced(negative_imbalance); diff --git a/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index f5e2a3330526c..0ed9b5427b1ec 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/frame/election-provider-multi-phase/src/unsigned.rs @@ -108,16 +108,15 @@ fn save_solution(call: &Call) -> Result<(), MinerError> { let storage = StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL); match storage.mutate::<_, (), _>(|_| Ok(call.clone())) { Ok(_) => Ok(()), - Err(MutateStorageError::ConcurrentModification(_)) => { - Err(MinerError::FailedToStoreSolution) - } + Err(MutateStorageError::ConcurrentModification(_)) => + Err(MinerError::FailedToStoreSolution), Err(MutateStorageError::ValueFunctionFailed(_)) => { // this branch should be unreachable according to the definition of // `StorageValueRef::mutate`: that function should only ever `Err` if the closure we // pass it returns an error. however, for safety in case the definition changes, we do // not optimize the branch away or panic. Err(MinerError::FailedToStoreSolution) - } + }, } } @@ -180,7 +179,7 @@ impl Pallet { let call = Self::mine_checked_call()?; save_solution(&call)?; Ok(call) - } + }, MinerError::Feasibility(_) => { log!(trace, "wiping infeasible solution."); // kill the infeasible solution, hopefully in the next runs (whenever they @@ -188,11 +187,11 @@ impl Pallet { kill_ocw_solution::(); clear_offchain_repeat_frequency(); Err(error) - } + }, _ => { // nothing to do. Return the error as-is. Err(error) - } + }, } })?; @@ -444,7 +443,7 @@ impl Pallet { // not much we can do if assignments are already empty. if high == low { - return Ok(()); + return Ok(()) } while high - low > 1 { @@ -455,8 +454,8 @@ impl Pallet { high = test; } } - let maximum_allowed_voters = if low < assignments.len() - && encoded_size_of(&assignments[..low + 1])? <= max_allowed_length + let maximum_allowed_voters = if low < assignments.len() && + encoded_size_of(&assignments[..low + 1])? <= max_allowed_length { low + 1 } else { @@ -468,8 +467,8 @@ impl Pallet { encoded_size_of(&assignments[..maximum_allowed_voters]).unwrap() <= max_allowed_length ); debug_assert!(if maximum_allowed_voters < assignments.len() { - encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap() - > max_allowed_length + encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap() > + max_allowed_length } else { true }); @@ -499,7 +498,7 @@ impl Pallet { max_weight: Weight, ) -> u32 { if size.voters < 1 { - return size.voters; + return size.voters } let max_voters = size.voters.max(1); @@ -518,7 +517,7 @@ impl Pallet { Some(voters) if voters < max_voters => Ok(voters), _ => Err(()), } - } + }, Ordering::Greater => voters.checked_sub(step).ok_or(()), Ordering::Equal => Ok(voters), } @@ -533,7 +532,7 @@ impl Pallet { // proceed with the binary search Ok(next) if next != voters => { voters = next; - } + }, // we are out of bounds, break out of the loop. Err(()) => break, // we found the right value - early exit the function. @@ -579,17 +578,16 @@ impl Pallet { |maybe_head: Result, _>| { match maybe_head { Ok(Some(head)) if now < head => Err("fork."), - Ok(Some(head)) if now >= head && now <= head + threshold => { - Err("recently executed.") - } + Ok(Some(head)) if now >= head && now <= head + threshold => + Err("recently executed."), Ok(Some(head)) if now > head + threshold => { // we can run again now. Write the new head. Ok(now) - } + }, _ => { // value doesn't exists. Probably this node just booted up. Write, and run Ok(now) - } + }, } }, ); @@ -598,9 +596,8 @@ impl Pallet { // all good Ok(_) => Ok(()), // failed to write. - Err(MutateStorageError::ConcurrentModification(_)) => { - Err(MinerError::Lock("failed to write to offchain db (concurrent modification).")) - } + Err(MutateStorageError::ConcurrentModification(_)) => + Err(MinerError::Lock("failed to write to offchain db (concurrent modification).")), // fork etc. Err(MutateStorageError::ValueFunctionFailed(why)) => Err(MinerError::Lock(why)), } @@ -624,8 +621,8 @@ impl Pallet { // ensure correct number of winners. ensure!( - Self::desired_targets().unwrap_or_default() - == raw_solution.solution.unique_targets().len() as u32, + Self::desired_targets().unwrap_or_default() == + raw_solution.solution.unique_targets().len() as u32, Error::::PreDispatchWrongWinnerCount, ); diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 8d4e5d354b382..116c0937bf983 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -325,14 +325,14 @@ pub mod pallet { let to_reserve = new_deposit - old_deposit; T::Currency::reserve(&who, to_reserve) .map_err(|_| Error::::UnableToPayBond)?; - } - Ordering::Equal => {} + }, + Ordering::Equal => {}, Ordering::Less => { // Must unreserve a bit. let to_unreserve = old_deposit - new_deposit; let _remainder = T::Currency::unreserve(&who, to_unreserve); debug_assert!(_remainder.is_zero()); - } + }, }; // Amount to be locked up. @@ -426,7 +426,7 @@ pub mod pallet { let _ = Self::remove_and_replace_member(&who, false) .map_err(|_| Error::::InvalidRenouncing)?; Self::deposit_event(Event::Renounced { candidate: who }); - } + }, Renouncing::RunnerUp => { >::try_mutate::<_, Error, _>(|runners_up| { let index = runners_up @@ -440,7 +440,7 @@ pub mod pallet { Self::deposit_event(Event::Renounced { candidate: who }); Ok(()) })?; - } + }, Renouncing::Candidate(count) => { >::try_mutate::<_, Error, _>(|candidates| { ensure!(count >= candidates.len() as u32, Error::::InvalidWitnessData); @@ -453,7 +453,7 @@ pub mod pallet { Self::deposit_event(Event::Renounced { candidate: who }); Ok(()) })?; - } + }, }; Ok(None.into()) } @@ -491,7 +491,7 @@ pub mod pallet { return Err(Error::::InvalidReplacement.with_weight( // refund. The weight value comes from a benchmark which is special to this. T::WeightInfo::remove_member_wrong_refund(), - )); + )) } let had_replacement = Self::remove_and_replace_member(&who, true)?; @@ -680,7 +680,7 @@ pub mod pallet { match members.binary_search_by(|m| m.who.cmp(member)) { Ok(_) => { panic!("Duplicate member in elections-phragmen genesis: {}", member) - } + }, Err(pos) => members.insert( pos, SeatHolder { @@ -790,7 +790,7 @@ impl Pallet { &remaining_member_ids_sorted[..], ); true - } + }, None => { T::ChangeMembers::change_members_sorted( &[], @@ -798,7 +798,7 @@ impl Pallet { &remaining_member_ids_sorted[..], ); false - } + }, }; // if there was a prime before and they are not the one being removed, then set them @@ -889,7 +889,7 @@ impl Pallet { if candidates_and_deposit.len().is_zero() { Self::deposit_event(Event::EmptyTerm); - return T::DbWeight::get().reads(5); + return T::DbWeight::get().reads(5) } // All of the new winners that come out of phragmen will thus have a deposit recorded. @@ -1002,8 +1002,8 @@ impl Pallet { // All candidates/members/runners-up who are no longer retaining a position as a // seat holder will lose their bond. candidates_and_deposit.iter().for_each(|(c, d)| { - if new_members_ids_sorted.binary_search(c).is_err() - && new_runners_up_ids_sorted.binary_search(c).is_err() + if new_members_ids_sorted.binary_search(c).is_err() && + new_runners_up_ids_sorted.binary_search(c).is_err() { let (imbalance, _) = T::Currency::slash_reserved(c, *d); T::LoserCandidate::on_unbalanced(imbalance); diff --git a/frame/elections-phragmen/src/migrations/v4.rs b/frame/elections-phragmen/src/migrations/v4.rs index e52f793ee1ef2..9acc1297294d9 100644 --- a/frame/elections-phragmen/src/migrations/v4.rs +++ b/frame/elections-phragmen/src/migrations/v4.rs @@ -38,7 +38,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { target: "runtime::elections-phragmen", "New pallet name is equal to the old prefix. No migration needs to be done.", ); - return 0; + return 0 } let storage_version = StorageVersion::get::>(); log::info!( diff --git a/frame/elections/src/lib.rs b/frame/elections/src/lib.rs index 4a7f37e554f4a..7ca11f4ed20e8 100644 --- a/frame/elections/src/lib.rs +++ b/frame/elections/src/lib.rs @@ -657,8 +657,8 @@ pub mod pallet { let count = Self::candidate_count() as usize; let candidates = Self::candidates(); ensure!( - (slot == count && count == candidates.len()) - || (slot < candidates.len() && candidates[slot] == T::AccountId::default()), + (slot == count && count == candidates.len()) || + (slot < candidates.len() && candidates[slot] == T::AccountId::default()), Error::::InvalidCandidateSlot, ); // NOTE: This must be last as it has side-effects. @@ -732,7 +732,7 @@ pub mod pallet { } else { None } - } + }, _ => None, }) .fold(Zero::zero(), |acc, n| acc + n); @@ -850,13 +850,14 @@ impl Pallet { None } else { let c = Self::members(); - let (next_possible, count, coming) = - if let Some((tally_end, comers, leavers)) = Self::next_finalize() { - // if there's a tally in progress, then next tally can begin immediately afterwards - (tally_end, c.len() - leavers.len() + comers as usize, comers) - } else { - (>::block_number(), c.len(), 0) - }; + let (next_possible, count, coming) = if let Some((tally_end, comers, leavers)) = + Self::next_finalize() + { + // if there's a tally in progress, then next tally can begin immediately afterwards + (tally_end, c.len() - leavers.len() + comers as usize, comers) + } else { + (>::block_number(), c.len(), 0) + }; if count < desired_seats as usize { Some(next_possible) } else { @@ -951,7 +952,7 @@ impl Pallet { CellStatus::Hole => { // requested cell was a valid hole. >::mutate(set_index, |set| set[vec_index] = Some(who.clone())); - } + }, CellStatus::Head | CellStatus::Occupied => { // Either occupied or out-of-range. let next = Self::next_nonfull_voter_set(); @@ -973,7 +974,7 @@ impl Pallet { NextVoterSet::::put(next + 1); } >::append(next, Some(who.clone())); - } + }, } T::Currency::reserve(&who, T::VotingBond::get())?; @@ -1143,7 +1144,7 @@ impl Pallet { loop { let next_set = >::get(index); if next_set.is_empty() { - break; + break } else { index += 1; all.extend(next_set); @@ -1225,7 +1226,7 @@ impl Pallet { pub fn bool_to_flag(x: Vec) -> Vec { let mut result: Vec = Vec::with_capacity(x.len() / APPROVAL_FLAG_LEN); if x.is_empty() { - return result; + return result } result.push(0); let mut index = 0; @@ -1235,7 +1236,7 @@ impl Pallet { result[index] += (if x[counter] { 1 } else { 0 }) << shl_index; counter += 1; if counter > x.len() - 1 { - break; + break } if counter % APPROVAL_FLAG_LEN == 0 { result.push(0); @@ -1249,7 +1250,7 @@ impl Pallet { pub fn flag_to_bool(chunk: Vec) -> Vec { let mut result = Vec::with_capacity(chunk.len()); if chunk.is_empty() { - return vec![]; + return vec![] } chunk .into_iter() @@ -1274,7 +1275,7 @@ impl Pallet { loop { let chunk = Self::approvals_of((who.clone(), index)); if chunk.is_empty() { - break; + break } all.extend(Self::flag_to_bool(chunk)); index += 1; @@ -1291,7 +1292,7 @@ impl Pallet { >::remove((who.clone(), index)); index += 1; } else { - break; + break } } } @@ -1309,7 +1310,7 @@ impl Pallet { fn get_offset(stake: BalanceOf, t: VoteIndex) -> BalanceOf { let decay_ratio: BalanceOf = T::DecayRatio::get().into(); if t > 150 { - return stake * decay_ratio; + return stake * decay_ratio } let mut offset = stake; let mut r = Zero::zero(); diff --git a/frame/elections/src/tests.rs b/frame/elections/src/tests.rs index f4b54cdb094b9..0df84c6d79baf 100644 --- a/frame/elections/src/tests.rs +++ b/frame/elections/src/tests.rs @@ -966,7 +966,7 @@ fn election_seats_should_be_released() { assert_ok!(Elections::end_block(System::block_number())); if Elections::members().len() == 0 { free_block = current; - break; + break } } // 11 + 2 which is the next voting period. diff --git a/frame/example-offchain-worker/src/lib.rs b/frame/example-offchain-worker/src/lib.rs index f93493e0d185b..e152adfad9856 100644 --- a/frame/example-offchain-worker/src/lib.rs +++ b/frame/example-offchain-worker/src/lib.rs @@ -195,12 +195,10 @@ pub mod pallet { let should_send = Self::choose_transaction_type(block_number); let res = match should_send { TransactionType::Signed => Self::fetch_price_and_send_signed(), - TransactionType::UnsignedForAny => { - Self::fetch_price_and_send_unsigned_for_any_account(block_number) - } - TransactionType::UnsignedForAll => { - Self::fetch_price_and_send_unsigned_for_all_accounts(block_number) - } + TransactionType::UnsignedForAny => + Self::fetch_price_and_send_unsigned_for_any_account(block_number), + TransactionType::UnsignedForAll => + Self::fetch_price_and_send_unsigned_for_all_accounts(block_number), TransactionType::Raw => Self::fetch_price_and_send_raw_unsigned(block_number), TransactionType::None => Ok(()), }; @@ -312,7 +310,7 @@ pub mod pallet { let signature_valid = SignedPayload::::verify::(payload, signature.clone()); if !signature_valid { - return InvalidTransaction::BadProof.into(); + return InvalidTransaction::BadProof.into() } Self::validate_transaction_parameters(&payload.block_number, &payload.price) } else if let Call::submit_price_unsigned { block_number, price: new_price } = call { @@ -389,9 +387,8 @@ impl Pallet { match last_send { // If we already have a value in storage and the block number is recent enough // we avoid sending another transaction at this time. - Ok(Some(block)) if block_number < block + T::GracePeriod::get() => { - Err(RECENTLY_SENT) - } + Ok(Some(block)) if block_number < block + T::GracePeriod::get() => + Err(RECENTLY_SENT), // In every other case we attempt to acquire the lock and send a transaction. _ => Ok(block_number), } @@ -424,7 +421,7 @@ impl Pallet { } else { TransactionType::Raw } - } + }, // We are in the grace period, we should not send a transaction this time. Err(MutateStorageError::ValueFunctionFailed(RECENTLY_SENT)) => TransactionType::None, // We wanted to send a transaction, but failed to write the block number (acquire a @@ -442,7 +439,7 @@ impl Pallet { if !signer.can_sign() { return Err( "No local accounts available. Consider adding one via `author_insertKey` RPC.", - )?; + )? } // Make an external HTTP request to fetch the current price. // Note this call will block until response is received. @@ -475,7 +472,7 @@ impl Pallet { // anyway. let next_unsigned_at = >::get(); if next_unsigned_at > block_number { - return Err("Too early to send unsigned transaction"); + return Err("Too early to send unsigned transaction") } // Make an external HTTP request to fetch the current price. @@ -509,7 +506,7 @@ impl Pallet { // anyway. let next_unsigned_at = >::get(); if next_unsigned_at > block_number { - return Err("Too early to send unsigned transaction"); + return Err("Too early to send unsigned transaction") } // Make an external HTTP request to fetch the current price. @@ -539,7 +536,7 @@ impl Pallet { // anyway. let next_unsigned_at = >::get(); if next_unsigned_at > block_number { - return Err("Too early to send unsigned transaction"); + return Err("Too early to send unsigned transaction") } // Make an external HTTP request to fetch the current price. @@ -557,7 +554,7 @@ impl Pallet { ); for (_account_id, result) in transaction_results.into_iter() { if result.is_err() { - return Err("Unable to submit transaction"); + return Err("Unable to submit transaction") } } @@ -593,7 +590,7 @@ impl Pallet { // Let's check the status code before we proceed to reading the response. if response.code != 200 { log::warn!("Unexpected status code: {}", response.code); - return Err(http::Error::Unknown); + return Err(http::Error::Unknown) } // Next we want to fully read the response body and collect it to a vector of bytes. @@ -612,7 +609,7 @@ impl Pallet { None => { log::warn!("Unable to extract price from the response: {:?}", body_str); Err(http::Error::Unknown) - } + }, }?; log::warn!("Got price: {} cents", price); @@ -632,7 +629,7 @@ impl Pallet { JsonValue::Number(number) => number, _ => return None, } - } + }, _ => return None, }; @@ -677,12 +674,12 @@ impl Pallet { // Now let's check if the transaction has any chance to succeed. let next_unsigned_at = >::get(); if &next_unsigned_at > block_number { - return InvalidTransaction::Stale.into(); + return InvalidTransaction::Stale.into() } // Let's make sure to reject transactions from the future. let current_block = >::block_number(); if ¤t_block < block_number { - return InvalidTransaction::Future.into(); + return InvalidTransaction::Future.into() } // We prioritize transactions that are more far away from current average. diff --git a/frame/example-parallel/src/lib.rs b/frame/example-parallel/src/lib.rs index 676f52578c795..c86cac4295684 100644 --- a/frame/example-parallel/src/lib.rs +++ b/frame/example-parallel/src/lib.rs @@ -111,7 +111,7 @@ impl EnlistedParticipant { Ok(signature) => { let public = sp_core::sr25519::Public::from_slice(self.account.as_ref()); signature.verify(event_id, &public) - } + }, _ => false, } } @@ -125,7 +125,7 @@ fn validate_participants_parallel(event_id: &[u8], participants: &[EnlistedParti for participant in participants { if !participant.verify(&event_id) { - return false.encode(); + return false.encode() } } true.encode() @@ -141,7 +141,7 @@ fn validate_participants_parallel(event_id: &[u8], participants: &[EnlistedParti for participant in &participants[participants.len() / 2 + 1..] { if !participant.verify(event_id) { result = false; - break; + break } } diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index 0b10c9851c316..45f0091d30d11 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -738,7 +738,7 @@ where ) -> TransactionValidity { // if the transaction is too big, just drop it. if len > 200 { - return InvalidTransaction::ExhaustsResources.into(); + return InvalidTransaction::ExhaustsResources.into() } // check for `set_dummy` @@ -749,7 +749,7 @@ where let mut valid_tx = ValidTransaction::default(); valid_tx.priority = Bounded::max_value(); Ok(valid_tx) - } + }, _ => Ok(Default::default()), } } diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index d5569d3af3081..b1bdf357ec07d 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -345,9 +345,9 @@ where // Check that `parent_hash` is correct. let n = header.number().clone(); assert!( - n > System::BlockNumber::zero() - && >::block_hash(n - System::BlockNumber::one()) - == *header.parent_hash(), + n > System::BlockNumber::zero() && + >::block_hash(n - System::BlockNumber::one()) == + *header.parent_hash(), "Parent hash should be valid.", ); @@ -878,8 +878,8 @@ mod tests { .assimilate_storage(&mut t) .unwrap(); let xt = TestXt::new(call_transfer(2, 69), sign_extra(1, 0, 0)); - let weight = xt.get_dispatch_info().weight - + ::BlockWeights::get() + let weight = xt.get_dispatch_info().weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; let fee: Balance = @@ -1078,8 +1078,8 @@ mod tests { assert!(Executive::apply_extrinsic(x2.clone()).unwrap().is_ok()); // default weight for `TestXt` == encoded length. - let extrinsic_weight = len as Weight - + ::BlockWeights::get() + let extrinsic_weight = len as Weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; assert_eq!( @@ -1150,8 +1150,8 @@ mod tests { Call::System(SystemCall::remark { remark: vec![1u8] }), sign_extra(1, 0, 0), ); - let weight = xt.get_dispatch_info().weight - + ::BlockWeights::get() + let weight = xt.get_dispatch_info().weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; let fee: Balance = @@ -1374,12 +1374,11 @@ mod tests { // Weights are recorded correctly assert_eq!( frame_system::Pallet::::block_weight().total(), - frame_system_upgrade_weight - + custom_runtime_upgrade_weight - + runtime_upgrade_weight - + frame_system_on_initialize_weight - + on_initialize_weight - + base_block_weight, + frame_system_upgrade_weight + + custom_runtime_upgrade_weight + + runtime_upgrade_weight + + frame_system_on_initialize_weight + + on_initialize_weight + base_block_weight, ); }); } diff --git a/frame/gilt/src/lib.rs b/frame/gilt/src/lib.rs index 41b2e7356f4a2..449b1defbd750 100644 --- a/frame/gilt/src/lib.rs +++ b/frame/gilt/src/lib.rs @@ -582,7 +582,7 @@ pub mod pallet { QueueTotals::::mutate(|qs| { for duration in (1..=T::QueueCount::get()).rev() { if qs[duration as usize - 1].0 == 0 { - continue; + continue } let queue_index = duration as usize - 1; let expiry = @@ -624,14 +624,14 @@ pub mod pallet { bids_taken += 1; if remaining.is_zero() || bids_taken == max_bids { - break; + break } } queues_hit += 1; qs[queue_index].0 = q.len() as u32; }); if remaining.is_zero() || bids_taken == max_bids { - break; + break } } }); diff --git a/frame/grandpa/src/equivocation.rs b/frame/grandpa/src/equivocation.rs index 277e88c89af0b..8a23ce6e1ef1e 100644 --- a/frame/grandpa/src/equivocation.rs +++ b/frame/grandpa/src/equivocation.rs @@ -208,15 +208,15 @@ impl Pallet { if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call { // discard equivocation report not coming from the local node match source { - TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ } + TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ }, _ => { log::warn!( target: "runtime::afg", "rejecting unsigned report equivocation transaction because it is not local/in-block." ); - return InvalidTransaction::Call.into(); - } + return InvalidTransaction::Call.into() + }, } // check report staleness diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 894e6edc65e81..b145f3441b7dd 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -174,7 +174,7 @@ pub mod pallet { >::put(StoredState::Paused); Self::deposit_event(Event::Paused); } - } + }, StoredState::PendingResume { scheduled_at, delay } => { // signal change to resume if block_number == scheduled_at { @@ -186,8 +186,8 @@ pub mod pallet { >::put(StoredState::Live); Self::deposit_event(Event::Resumed); } - } - _ => {} + }, + _ => {}, } } } @@ -550,7 +550,7 @@ impl Pallet { // validate equivocation proof (check votes are different and // signatures are valid). if !sp_finality_grandpa::check_equivocation_proof(equivocation_proof) { - return Err(Error::::InvalidEquivocationProof.into()); + return Err(Error::::InvalidEquivocationProof.into()) } // fetch the current and previous sets last session index. on the @@ -569,12 +569,12 @@ impl Pallet { // check that the session id for the membership proof is within the // bounds of the set id reported in the equivocation. - if session_index > set_id_session_index - || previous_set_id_session_index + if session_index > set_id_session_index || + previous_set_id_session_index .map(|previous_index| session_index <= previous_index) .unwrap_or(false) { - return Err(Error::::InvalidEquivocationProof.into()); + return Err(Error::::InvalidEquivocationProof.into()) } // report to the offences module rewarding the sender. diff --git a/frame/grandpa/src/migrations/v4.rs b/frame/grandpa/src/migrations/v4.rs index ad2b346727e02..094f276efef31 100644 --- a/frame/grandpa/src/migrations/v4.rs +++ b/frame/grandpa/src/migrations/v4.rs @@ -37,7 +37,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { target: "runtime::afg", "New pallet name is equal to the old prefix. No migration needs to be done.", ); - return 0; + return 0 } let storage_version = StorageVersion::get::>(); log::info!( diff --git a/frame/grandpa/src/tests.rs b/frame/grandpa/src/tests.rs index 2a20d723fa147..6dc0a26da8bd3 100644 --- a/frame/grandpa/src/tests.rs +++ b/frame/grandpa/src/tests.rs @@ -379,7 +379,7 @@ fn report_equivocation_current_set_works() { // check that the balances of all other validators are left intact. for validator in &validators { if *validator == equivocation_validator_id { - continue; + continue } assert_eq!(Balances::total_balance(validator), 10_000_000); @@ -458,7 +458,7 @@ fn report_equivocation_old_set_works() { // check that the balances of all other validators are left intact. for validator in &validators { if *validator == equivocation_validator_id { - continue; + continue } assert_eq!(Balances::total_balance(validator), 10_000_000); diff --git a/frame/identity/src/benchmarking.rs b/frame/identity/src/benchmarking.rs index da2c4cae50cda..df7aba72fd958 100644 --- a/frame/identity/src/benchmarking.rs +++ b/frame/identity/src/benchmarking.rs @@ -44,16 +44,14 @@ fn add_registrars(r: u32) -> Result<(), &'static str> { i.into(), 10u32.into(), )?; - let fields = IdentityFields( - IdentityField::Display - | IdentityField::Legal - | IdentityField::Web - | IdentityField::Riot - | IdentityField::Email - | IdentityField::PgpFingerprint - | IdentityField::Image - | IdentityField::Twitter, - ); + let fields = + IdentityFields( + IdentityField::Display | + IdentityField::Legal | IdentityField::Web | + IdentityField::Riot | IdentityField::Email | + IdentityField::PgpFingerprint | + IdentityField::Image | IdentityField::Twitter, + ); Identity::::set_fields(RawOrigin::Signed(registrar.clone()).into(), i.into(), fields)?; } @@ -115,7 +113,7 @@ fn create_identity_info(num_fields: u32) -> IdentityInfo Registration { info: *info, judgements: BoundedVec::default(), @@ -541,16 +541,14 @@ pub mod pallet { let item = (reg_index, Judgement::FeePaid(registrar.fee)); match id.judgements.binary_search_by_key(®_index, |x| x.0) { - Ok(i) => { + Ok(i) => if id.judgements[i].1.is_sticky() { Err(Error::::StickyJudgement)? } else { id.judgements[i] = item - } - } - Err(i) => { - id.judgements.try_insert(i, item).map_err(|_| Error::::TooManyRegistrars)? - } + }, + Err(i) => + id.judgements.try_insert(i, item).map_err(|_| Error::::TooManyRegistrars)?, } T::Currency::reserve(&sender, registrar.fee)?; @@ -788,7 +786,7 @@ pub mod pallet { ); } id.judgements[position] = item - } + }, Err(position) => id .judgements .try_insert(position, item) diff --git a/frame/identity/src/types.rs b/frame/identity/src/types.rs index 9be05c3b832f6..ed6aeb18e96a1 100644 --- a/frame/identity/src/types.rs +++ b/frame/identity/src/types.rs @@ -64,7 +64,7 @@ impl Decode for Data { .expect("bound checked in match arm condition; qed"); input.read(&mut r[..])?; Data::Raw(r) - } + }, 34 => Data::BlakeTwo256(<[u8; 32]>::decode(input)?), 35 => Data::Sha256(<[u8; 32]>::decode(input)?), 36 => Data::Keccak256(<[u8; 32]>::decode(input)?), @@ -83,7 +83,7 @@ impl Encode for Data { let mut r = vec![l as u8 + 1; l + 1]; r[1..].copy_from_slice(&x[..l as usize]); r - } + }, Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(), Data::Sha256(ref h) => once(35u8).chain(h.iter().cloned()).collect(), Data::Keccak256(ref h) => once(36u8).chain(h.iter().cloned()).collect(), @@ -368,9 +368,8 @@ impl< > Registration { pub(crate) fn total_deposit(&self) -> Balance { - self.deposit - + self - .judgements + self.deposit + + self.judgements .iter() .map(|(_, ref j)| if let Judgement::FeePaid(fee) = j { *fee } else { Zero::zero() }) .fold(Zero::zero(), |a, i| a + i) diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index f18c072ca3aed..c6b3543151201 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -193,10 +193,10 @@ impl sp_std::fmt::Debug for OffchainErr write!(fmt, "Too early to send heartbeat."), OffchainErr::WaitingForInclusion(ref block) => { write!(fmt, "Heartbeat already sent at {:?}. Waiting for inclusion.", block) - } + }, OffchainErr::AlreadyOnline(auth_idx) => { write!(fmt, "Authority {} is already online", auth_idx) - } + }, OffchainErr::FailedSigning => write!(fmt, "Failed to sign heartbeat"), OffchainErr::FailedToAcquireLock => write!(fmt, "Failed to acquire lock"), OffchainErr::NetworkState => write!(fmt, "Failed to fetch network state"), @@ -555,19 +555,19 @@ pub mod pallet { if let Call::heartbeat { heartbeat, signature } = call { if >::is_online(heartbeat.authority_index) { // we already received a heartbeat for this authority - return InvalidTransaction::Stale.into(); + return InvalidTransaction::Stale.into() } // check if session index from heartbeat is recent let current_session = T::ValidatorSet::session_index(); if heartbeat.session_index != current_session { - return InvalidTransaction::Stale.into(); + return InvalidTransaction::Stale.into() } // verify that the incoming (unverified) pubkey is actually an authority id let keys = Keys::::get(); if keys.len() as u32 != heartbeat.validators_len { - return InvalidTransaction::Custom(INVALID_VALIDATORS_LEN).into(); + return InvalidTransaction::Custom(INVALID_VALIDATORS_LEN).into() } let authority_id = match keys.get(heartbeat.authority_index as usize) { Some(id) => id, @@ -580,7 +580,7 @@ pub mod pallet { }); if !signature_valid { - return InvalidTransaction::BadProof.into(); + return InvalidTransaction::BadProof.into() } ValidTransaction::with_tag_prefix("ImOnline") @@ -624,7 +624,7 @@ impl Pallet { let current_validators = T::ValidatorSet::validators(); if authority_index >= current_validators.len() as u32 { - return false; + return false } let authority = ¤t_validators[authority_index as usize]; @@ -635,8 +635,8 @@ impl Pallet { fn is_online_aux(authority_index: AuthIndex, authority: &ValidatorId) -> bool { let current_session = T::ValidatorSet::session_index(); - ReceivedHeartbeats::::contains_key(¤t_session, &authority_index) - || AuthoredBlocks::::get(¤t_session, authority) != 0 + ReceivedHeartbeats::::contains_key(¤t_session, &authority_index) || + AuthoredBlocks::::get(¤t_session, authority) != 0 } /// Returns `true` if a heartbeat has been received for the authority at `authority_index` in @@ -686,8 +686,8 @@ impl Pallet { // haven't sent an heartbeat yet we'll send one unconditionally. the idea is to prevent // all nodes from sending the heartbeats at the same block and causing a temporary (but // deterministic) spike in transactions. - progress >= START_HEARTBEAT_FINAL_PERIOD - || progress >= START_HEARTBEAT_RANDOM_PERIOD && random_choice(progress) + progress >= START_HEARTBEAT_FINAL_PERIOD || + progress >= START_HEARTBEAT_RANDOM_PERIOD && random_choice(progress) } else { // otherwise we fallback to using the block number calculated at the beginning // of the session that should roughly correspond to the middle of the session @@ -696,7 +696,7 @@ impl Pallet { }; if !should_heartbeat { - return Err(OffchainErr::TooEarly); + return Err(OffchainErr::TooEarly) } let session_index = T::ValidatorSet::session_index(); @@ -738,7 +738,7 @@ impl Pallet { }; if Self::is_online(authority_index) { - return Err(OffchainErr::AlreadyOnline(authority_index)); + return Err(OffchainErr::AlreadyOnline(authority_index)) } // acquire lock for that authority at current heartbeat to make sure we don't @@ -804,16 +804,15 @@ impl Pallet { // we will re-send it. match status { // we are still waiting for inclusion. - Ok(Some(status)) if status.is_recent(session_index, now) => { - Err(OffchainErr::WaitingForInclusion(status.sent_at)) - } + Ok(Some(status)) if status.is_recent(session_index, now) => + Err(OffchainErr::WaitingForInclusion(status.sent_at)), // attempt to set new status _ => Ok(HeartbeatStatus { session_index, sent_at: now }), } }, ); if let Err(MutateStorageError::ValueFunctionFailed(err)) = res { - return Err(err); + return Err(err) } let mut new_status = res.map_err(|_| OffchainErr::FailedToAcquireLock)?; diff --git a/frame/im-online/src/tests.rs b/frame/im-online/src/tests.rs index d1dd29abf0890..bb2c4c7cae548 100644 --- a/frame/im-online/src/tests.rs +++ b/frame/im-online/src/tests.rs @@ -135,9 +135,8 @@ fn heartbeat( signature: signature.clone(), }) .map_err(|e| match e { - TransactionValidityError::Invalid(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN)) => { - "invalid validators len" - } + TransactionValidityError::Invalid(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN)) => + "invalid validators len", e @ _ => <&'static str>::from(e), })?; ImOnline::heartbeat(Origin::none(), heartbeat, signature) diff --git a/frame/lottery/src/lib.rs b/frame/lottery/src/lib.rs index 364a484a3abc9..c1c536b8ba290 100644 --- a/frame/lottery/src/lib.rs +++ b/frame/lottery/src/lib.rs @@ -259,18 +259,18 @@ pub mod pallet { LotteryIndex::::mutate(|index| *index = index.saturating_add(1)); // Set a new start with the current block. config.start = n; - return T::WeightInfo::on_initialize_repeat(); + return T::WeightInfo::on_initialize_repeat() } else { // Else, kill the lottery storage. *lottery = None; - return T::WeightInfo::on_initialize_end(); + return T::WeightInfo::on_initialize_end() } // We choose not need to kill Participants and Tickets to avoid a large // number of writes at one time. Instead, data persists between lotteries, // but is not used if it is not relevant. } } - return T::DbWeight::get().reads(1); + return T::DbWeight::get().reads(1) }) } } @@ -410,7 +410,7 @@ impl Pallet { if encoded_call.len() < 2 { Err(Error::::EncodingFailed)? } - return Ok((encoded_call[0], encoded_call[1])); + return Ok((encoded_call[0], encoded_call[1])) } // Logic for buying a ticket. @@ -464,7 +464,7 @@ impl Pallet { // Best effort attempt to remove bias from modulus operator. for i in 1..T::MaxGenerateRandom::get() { if random_number < u32::MAX - u32::MAX % total { - break; + break } random_number = Self::generate_random_number(i); diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 7d001240cd417..6cd8c13f39aff 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -215,7 +215,7 @@ pub mod pallet { T::SwapOrigin::ensure_origin(origin)?; if remove == add { - return Ok(()); + return Ok(()) } let mut members = >::get(); diff --git a/frame/membership/src/migrations/v4.rs b/frame/membership/src/migrations/v4.rs index a0601b4027864..c1c944be1fd4f 100644 --- a/frame/membership/src/migrations/v4.rs +++ b/frame/membership/src/migrations/v4.rs @@ -46,7 +46,7 @@ pub fn migrate::on_chain_storage_version(); @@ -85,7 +85,7 @@ pub fn pre_migrate>(old_pallet_name: N, new_ log_migration("pre-migration", old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return; + return } let new_pallet_prefix = twox_128(new_pallet_name.as_bytes()); @@ -113,7 +113,7 @@ pub fn post_migrate>(old_pallet_name: N, new log_migration("post-migration", old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return; + return } // Assert that nothing remains at the old prefix. diff --git a/frame/merkle-mountain-range/src/lib.rs b/frame/merkle-mountain-range/src/lib.rs index 227cde08c889d..01bf1b2254f09 100644 --- a/frame/merkle-mountain-range/src/lib.rs +++ b/frame/merkle-mountain-range/src/lib.rs @@ -255,12 +255,12 @@ impl, I: 'static> Pallet { leaf: LeafOf, proof: primitives::Proof<>::Hash>, ) -> Result<(), primitives::Error> { - if proof.leaf_count > Self::mmr_leaves() - || proof.leaf_count == 0 - || proof.items.len() as u32 > mmr::utils::NodesUtils::new(proof.leaf_count).depth() + if proof.leaf_count > Self::mmr_leaves() || + proof.leaf_count == 0 || + proof.items.len() as u32 > mmr::utils::NodesUtils::new(proof.leaf_count).depth() { return Err(primitives::Error::Verify - .log_debug("The proof has incorrect number of leaves or proof items.")); + .log_debug("The proof has incorrect number of leaves or proof items.")) } let mmr: ModuleMmr = mmr::Mmr::new(proof.leaf_count); diff --git a/frame/merkle-mountain-range/src/mmr/storage.rs b/frame/merkle-mountain-range/src/mmr/storage.rs index c895a5e8799d1..09e24017816ec 100644 --- a/frame/merkle-mountain-range/src/mmr/storage.rs +++ b/frame/merkle-mountain-range/src/mmr/storage.rs @@ -86,7 +86,7 @@ where let mut leaves = crate::NumberOfLeaves::::get(); let mut size = crate::mmr::utils::NodesUtils::new(leaves).size(); if pos != size { - return Err(mmr_lib::Error::InconsistentStore); + return Err(mmr_lib::Error::InconsistentStore) } for elem in elems { diff --git a/frame/merkle-mountain-range/src/mmr/utils.rs b/frame/merkle-mountain-range/src/mmr/utils.rs index 233a0da474f80..8fc725f11e72f 100644 --- a/frame/merkle-mountain-range/src/mmr/utils.rs +++ b/frame/merkle-mountain-range/src/mmr/utils.rs @@ -46,7 +46,7 @@ impl NodesUtils { /// Calculate maximal depth of the MMR. pub fn depth(&self) -> u32 { if self.no_of_leaves == 0 { - return 0; + return 0 } 64 - self.no_of_leaves.next_power_of_two().leading_zeros() diff --git a/frame/multisig/src/lib.rs b/frame/multisig/src/lib.rs index 28fbc575392e8..65684dd391730 100644 --- a/frame/multisig/src/lib.rs +++ b/frame/multisig/src/lib.rs @@ -297,7 +297,7 @@ pub mod pallet { let post_info = Some(weight_used).into(); let error = err.error.into(); DispatchErrorWithPostInfo { post_info, error } - } + }, None => err, }) } @@ -535,7 +535,7 @@ impl Pallet { let call_hash = blake2_256(call.encoded()); let call_len = call.encoded_len(); (call_hash, call_len, Some(call), should_store) - } + }, CallOrHash::Hash(h) => (h, 0, None, false), }; diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 8259d7d1773e0..6e3ec58ba63f9 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -193,7 +193,7 @@ pub mod pallet { true, ), } - } + }, } } } @@ -270,7 +270,7 @@ pub mod pallet { ensure!(add.0.len() < T::MaxPeerIdLength::get() as usize, Error::::PeerIdTooLong); if remove == add { - return Ok(()); + return Ok(()) } let mut nodes = WellKnownNodes::::get(); @@ -388,7 +388,7 @@ pub mod pallet { for add_node in connections.iter() { if *add_node == node { - continue; + continue } nodes.insert(add_node.clone()); } diff --git a/frame/proxy/src/lib.rs b/frame/proxy/src/lib.rs index cfebb60cd7119..695fa077f98d5 100644 --- a/frame/proxy/src/lib.rs +++ b/frame/proxy/src/lib.rs @@ -537,9 +537,9 @@ pub mod pallet { let call_hash = T::CallHasher::hash_of(&call); let now = system::Pallet::::block_number(); Self::edit_announcements(&delegate, |ann| { - ann.real != real - || ann.call_hash != call_hash - || now.saturating_sub(ann.height) < def.delay + ann.real != real || + ann.call_hash != call_hash || + now.saturating_sub(ann.height) < def.delay }) .map_err(|_| Error::::Unannounced)?; @@ -782,8 +782,8 @@ impl Pallet { force_proxy_type: Option, ) -> Result, DispatchError> { let f = |x: &ProxyDefinition| -> bool { - &x.delegate == delegate - && force_proxy_type.as_ref().map_or(true, |y| &x.proxy_type == y) + &x.delegate == delegate && + force_proxy_type.as_ref().map_or(true, |y| &x.proxy_type == y) }; Ok(Proxies::::get(real).0.into_iter().find(f).ok_or(Error::::NotProxy)?) } @@ -801,19 +801,15 @@ impl Pallet { match c.is_sub_type() { // Proxy call cannot add or remove a proxy with more permissions than it already // has. - Some(Call::add_proxy { ref proxy_type, .. }) - | Some(Call::remove_proxy { ref proxy_type, .. }) + Some(Call::add_proxy { ref proxy_type, .. }) | + Some(Call::remove_proxy { ref proxy_type, .. }) if !def.proxy_type.is_superset(&proxy_type) => - { - false - } + false, // Proxy call cannot remove all proxies or kill anonymous proxies unless it has full // permissions. Some(Call::remove_proxies { .. }) | Some(Call::kill_anonymous { .. }) if def.proxy_type != T::ProxyType::default() => - { - false - } + false, _ => def.proxy_type.filter(c), } }); diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index 2b9d7c6e7f92a..50c64c1f6ee2c 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -135,7 +135,7 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::JustTransfer => { matches!(c, Call::Balances(pallet_balances::Call::transfer { .. })) - } + }, ProxyType::JustUtility => matches!(c, Call::Utility { .. }), } } @@ -407,7 +407,7 @@ fn filtering_works() { ); assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); expect_events(vec![ - BalancesEvent::::Unreserved{who: 1, value: 5}.into(), + BalancesEvent::::Unreserved { who: 1, value: 5 }.into(), ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); }); diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index 590b50cedf7c8..ca9e15812a76d 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -296,9 +296,9 @@ pub mod pallet { // - It's priority is `HARD_DEADLINE` // - It does not push the weight past the limit. // - It is the first item in the schedule - if s.priority <= schedule::HARD_DEADLINE - || cumulative_weight <= limit - || order == 0 + if s.priority <= schedule::HARD_DEADLINE || + cumulative_weight <= limit || + order == 0 { let r = s.call.clone().dispatch(s.origin.clone().into()); let maybe_id = s.maybe_id.clone(); @@ -563,7 +563,7 @@ impl Pallet { }; if when <= now { - return Err(Error::::TargetBlockNumberInPast.into()); + return Err(Error::::TargetBlockNumberInPast.into()) } Ok(when) @@ -615,7 +615,7 @@ impl Pallet { |s| -> Result>, DispatchError> { if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) { if *o != s.origin { - return Err(BadOrigin.into()); + return Err(BadOrigin.into()) } }; Ok(s.take()) @@ -640,7 +640,7 @@ impl Pallet { let new_time = Self::resolve_time(new_time)?; if new_time == when { - return Err(Error::::RescheduleNoChange.into()); + return Err(Error::::RescheduleNoChange.into()) } Agenda::::try_mutate(when, |agenda| -> DispatchResult { @@ -667,7 +667,7 @@ impl Pallet { ) -> Result, DispatchError> { // ensure id it is unique if Lookup::::contains_key(&id) { - return Err(Error::::FailedToSchedule)?; + return Err(Error::::FailedToSchedule)? } let when = Self::resolve_time(when)?; @@ -710,7 +710,7 @@ impl Pallet { if let Some(s) = agenda.get_mut(i) { if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) { if *o != s.origin { - return Err(BadOrigin.into()); + return Err(BadOrigin.into()) } } *s = None; @@ -737,7 +737,7 @@ impl Pallet { let (when, index) = lookup.ok_or(Error::::NotFound)?; if new_time == when { - return Err(Error::::RescheduleNoChange.into()); + return Err(Error::::RescheduleNoChange.into()) } Agenda::::try_mutate(when, |agenda| -> DispatchResult { @@ -1439,9 +1439,9 @@ mod tests { let call_weight = MaximumSchedulerWeight::get() / 2; assert_eq!( actual_weight, - call_weight - + base_weight + base_multiplier - + named_multiplier + periodic_multiplier + call_weight + + base_weight + base_multiplier + + named_multiplier + periodic_multiplier ); assert_eq!(logger::log(), vec![(root(), 2600u32)]); diff --git a/frame/scored-pool/src/lib.rs b/frame/scored-pool/src/lib.rs index 7397496114778..a5cdb6274f995 100644 --- a/frame/scored-pool/src/lib.rs +++ b/frame/scored-pool/src/lib.rs @@ -428,12 +428,10 @@ impl, I: 'static> Pallet { >::put(&new_members); match notify { - ChangeReceiver::MembershipInitialized => { - T::MembershipInitialized::initialize_members(&new_members) - } - ChangeReceiver::MembershipChanged => { - T::MembershipChanged::set_members_sorted(&new_members[..], &old_members[..]) - } + ChangeReceiver::MembershipInitialized => + T::MembershipInitialized::initialize_members(&new_members), + ChangeReceiver::MembershipChanged => + T::MembershipChanged::set_members_sorted(&new_members[..], &old_members[..]), } } diff --git a/frame/session/src/historical/mod.rs b/frame/session/src/historical/mod.rs index 48aac50e40259..0801b2aca1701 100644 --- a/frame/session/src/historical/mod.rs +++ b/frame/session/src/historical/mod.rs @@ -94,7 +94,7 @@ impl Module { let up_to = sp_std::cmp::min(up_to, end); if up_to < start { - return; // out of bounds. harmless. + return // out of bounds. harmless. } (start..up_to).for_each(::HistoricalSessions::remove); @@ -170,7 +170,7 @@ impl> NoteHi Err(reason) => { print("Failed to generate historical ancestry-inclusion proof."); print(reason); - } + }, }; } else { let previous_index = new_index.saturating_sub(1); @@ -341,7 +341,7 @@ impl> frame_support::traits::KeyOwnerProofSystem<(KeyT let count = >::validators().len() as ValidatorCount; if count != proof.validator_count { - return None; + return None } Some((owner, id)) @@ -351,7 +351,7 @@ impl> frame_support::traits::KeyOwnerProofSystem<(KeyT let (root, count) = >::get(&proof.session)?; if count != proof.validator_count { - return None; + return None } let trie = ProvingTrie::::from_nodes(root, &proof.trie_nodes); diff --git a/frame/session/src/historical/offchain.rs b/frame/session/src/historical/offchain.rs index f5fb921663dad..b646ecc2764f7 100644 --- a/frame/session/src/historical/offchain.rs +++ b/frame/session/src/historical/offchain.rs @@ -121,9 +121,9 @@ pub fn prune_older_than(first_to_keep: SessionIndex) { let _ = StorageValueRef::persistent(derived_key.as_ref()).clear(); } } - } - Err(MutateStorageError::ConcurrentModification(_)) => {} - Err(MutateStorageError::ValueFunctionFailed(_)) => {} + }, + Err(MutateStorageError::ConcurrentModification(_)) => {}, + Err(MutateStorageError::ValueFunctionFailed(_)) => {}, } } diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 3321da359f1c1..7fe163e0dfeac 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -675,7 +675,7 @@ impl Pallet { let mut now_session_keys = session_keys.iter(); let mut check_next_changed = |keys: &T::Keys| { if changed { - return; + return } // since a new validator set always leads to `changed` starting // as true, we can ensure that `now_session_keys` and `next_validators` @@ -683,7 +683,7 @@ impl Pallet { if let Some(&(_, ref old_keys)) = now_session_keys.next() { if old_keys != keys { changed = true; - return; + return } } }; @@ -712,14 +712,14 @@ impl Pallet { /// Disable the validator of index `i`, returns `false` if the validator was already disabled. pub fn disable_index(i: u32) -> bool { if i >= Validators::::decode_len().unwrap_or(0) as u32 { - return false; + return false } >::mutate(|disabled| { if let Err(index) = disabled.binary_search(&i) { disabled.insert(index, i); T::SessionHandler::on_disabled(i); - return true; + return true } false @@ -834,7 +834,7 @@ impl Pallet { if let Some(old) = old_keys.as_ref().map(|k| k.get_raw(*id)) { if key == old { - continue; + continue } Self::clear_key_owner(*id, old); diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index b611089373637..6db7727fa5391 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -118,8 +118,8 @@ pub struct TestShouldEndSession; impl ShouldEndSession for TestShouldEndSession { fn should_end_session(now: u64) -> bool { let l = SESSION_LENGTH.with(|l| *l.borrow()); - now % l == 0 - || FORCE_SESSION_END.with(|l| { + now % l == 0 || + FORCE_SESSION_END.with(|l| { let r = *l.borrow(); *l.borrow_mut() = false; r diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 92390a7cb180c..83b1c4203722b 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -766,10 +766,10 @@ pub mod pallet { BidKind::Deposit(deposit) => { let err_amount = T::Currency::unreserve(&who, deposit); debug_assert!(err_amount.is_zero()); - } + }, BidKind::Vouch(voucher, _) => { >::remove(&voucher); - } + }, } Self::deposit_event(Event::::Unbid(who)); Ok(()) @@ -998,7 +998,7 @@ pub mod pallet { } else { >::insert(&who, payouts); } - return Ok(()); + return Ok(()) } } Err(Error::::NoPayout)? @@ -1195,10 +1195,10 @@ pub mod pallet { // Reduce next pot by payout >::put(pot - value); // Add payout for new candidate - let maturity = >::block_number() - + Self::lock_duration(Self::members().len() as u32); + let maturity = >::block_number() + + Self::lock_duration(Self::members().len() as u32); Self::pay_accepted_candidate(&who, value, kind, maturity); - } + }, Judgement::Reject => { // Founder has rejected this candidate match kind { @@ -1211,19 +1211,19 @@ pub mod pallet { BalanceStatus::Free, ); debug_assert!(res.is_ok()); - } + }, BidKind::Vouch(voucher, _) => { // Ban the voucher from vouching again >::insert(&voucher, VouchingStatus::Banned); - } + }, } - } + }, Judgement::Rebid => { // Founder has taken no judgement, and candidate is placed back into the // pool. let bids = >::get(); Self::put_bid(bids, &who, value, kind); - } + }, } // Remove suspended candidate @@ -1324,7 +1324,7 @@ impl, I: 'static> Pallet { } else { bids.push(Bid { value, who: who.clone(), kind: bid_kind }); } - } + }, Err(pos) => bids.insert(pos, Bid { value, who: who.clone(), kind: bid_kind }), } // Keep it reasonably small. @@ -1334,10 +1334,10 @@ impl, I: 'static> Pallet { BidKind::Deposit(deposit) => { let err_amount = T::Currency::unreserve(&popped, deposit); debug_assert!(err_amount.is_zero()); - } + }, BidKind::Vouch(voucher, _) => { >::remove(&voucher); - } + }, } Self::deposit_event(Event::::AutoUnbid(popped)); } @@ -1377,7 +1377,7 @@ impl, I: 'static> Pallet { T::MembershipChanged::change_members_sorted(&[who.clone()], &[], &members); >::put(members); Ok(()) - } + }, // User is already a member, do nothing. Ok(_) => Ok(()), } @@ -1399,7 +1399,7 @@ impl, I: 'static> Pallet { T::MembershipChanged::change_members_sorted(&[], &[m.clone()], &members[..]); >::put(members); Ok(()) - } + }, } } @@ -1426,8 +1426,8 @@ impl, I: 'static> Pallet { // out of society. members.reserve(candidates.len()); - let maturity = >::block_number() - + Self::lock_duration(members.len() as u32); + let maturity = >::block_number() + + Self::lock_duration(members.len() as u32); let mut rewardees = Vec::new(); let mut total_approvals = 0; @@ -1613,7 +1613,7 @@ impl, I: 'static> Pallet { // whole slash is accounted for. *amount -= rest; rest = Zero::zero(); - break; + break } } >::insert(who, &payouts[dropped..]); @@ -1656,7 +1656,7 @@ impl, I: 'static> Pallet { let err_amount = T::Currency::unreserve(candidate, deposit); debug_assert!(err_amount.is_zero()); value - } + }, BidKind::Vouch(voucher, tip) => { // Check that the voucher is still vouching, else some other logic may have removed // their status. @@ -1668,7 +1668,7 @@ impl, I: 'static> Pallet { } else { value } - } + }, }; Self::bump_payout(candidate, maturity, value); @@ -1786,7 +1786,7 @@ impl, I: 'static> Pallet { selected.push(bid.clone()); zero_selected = true; count += 1; - return false; + return false } } else { total_cost += bid.value; @@ -1794,7 +1794,7 @@ impl, I: 'static> Pallet { if total_cost <= pot { selected.push(bid.clone()); count += 1; - return false; + return false } } } diff --git a/frame/staking/reward-curve/src/lib.rs b/frame/staking/reward-curve/src/lib.rs index d46ede184fffb..06e35d11350e0 100644 --- a/frame/staking/reward-curve/src/lib.rs +++ b/frame/staking/reward-curve/src/lib.rs @@ -87,7 +87,7 @@ pub fn build(input: TokenStream) -> TokenStream { Ok(FoundCrate::Name(sp_runtime)) => { let ident = syn::Ident::new(&sp_runtime, Span::call_site()); quote!( extern crate #ident as _sp_runtime; ) - } + }, Err(e) => syn::Error::new(Span::call_site(), e).to_compile_error(), }; @@ -136,10 +136,10 @@ struct Bounds { impl Bounds { fn check(&self, value: u32) -> bool { - let wrong = (self.min_strict && value <= self.min) - || (!self.min_strict && value < self.min) - || (self.max_strict && value >= self.max) - || (!self.max_strict && value > self.max); + let wrong = (self.min_strict && value <= self.min) || + (!self.min_strict && value < self.min) || + (self.max_strict && value >= self.max) || + (!self.max_strict && value > self.max); !wrong } @@ -175,7 +175,7 @@ fn parse_field( value, bounds, ), - )); + )) } Ok(value) @@ -196,7 +196,7 @@ impl Parse for INposInput { ::parse(input)?; if !input.is_empty() { - return Err(input.error("expected end of input stream, no token expected")); + return Err(input.error("expected end of input stream, no token expected")) } let min_inflation = parse_field::( @@ -231,7 +231,7 @@ impl Parse for INposInput { >::parse(&args_input)?; if !args_input.is_empty() { - return Err(args_input.error("expected end of input stream, no token expected")); + return Err(args_input.error("expected end of input stream, no token expected")) } Ok(Self { @@ -273,7 +273,7 @@ impl INPoS { // See web3 docs for the details fn compute_opposite_after_x_ideal(&self, y: u32) -> u32 { if y == self.i_0 { - return u32::MAX; + return u32::MAX } // Note: the log term calculated here represents a per_million value let log = log2(self.i_ideal_times_x_ideal - self.i_0, y - self.i_0); @@ -291,8 +291,8 @@ fn compute_points(input: &INposInput) -> Vec<(u32, u32)> { // For each point p: (next_p.0 - p.0) < segment_length && (next_p.1 - p.1) < segment_length. // This ensures that the total number of segment doesn't overflow max_piece_count. - let max_length = (input.max_inflation - input.min_inflation + 1_000_000 - inpos.x_ideal) - / (input.max_piece_count - 1); + let max_length = (input.max_inflation - input.min_inflation + 1_000_000 - inpos.x_ideal) / + (input.max_piece_count - 1); let mut delta_y = max_length; let mut y = input.max_inflation; @@ -304,29 +304,29 @@ fn compute_points(input: &INposInput) -> Vec<(u32, u32)> { if next_y <= input.min_inflation { delta_y = delta_y.saturating_sub(1); - continue; + continue } let next_x = inpos.compute_opposite_after_x_ideal(next_y); if (next_x - points.last().unwrap().0) > max_length { delta_y = delta_y.saturating_sub(1); - continue; + continue } if next_x >= 1_000_000 { let prev = points.last().unwrap(); // Compute the y corresponding to x=1_000_000 using the this point and the previous one. - let delta_y: u32 = ((next_x - 1_000_000) as u64 * (prev.1 - next_y) as u64 - / (next_x - prev.0) as u64) + let delta_y: u32 = ((next_x - 1_000_000) as u64 * (prev.1 - next_y) as u64 / + (next_x - prev.0) as u64) .try_into() .unwrap(); let y = next_y + delta_y; points.push((1_000_000, y)); - return points; + return points } points.push((next_x, next_y)); y = next_y; diff --git a/frame/staking/reward-curve/src/log.rs b/frame/staking/reward-curve/src/log.rs index 8e71056b86e6b..c196aaaa31a93 100644 --- a/frame/staking/reward-curve/src/log.rs +++ b/frame/staking/reward-curve/src/log.rs @@ -41,7 +41,7 @@ pub fn log2(p: u32, q: u32) -> u32 { // log2(1) = 0 if p == q { - return 0; + return 0 } // find the power of 2 where q * 2^n <= p < q * 2^(n+1) @@ -61,7 +61,7 @@ pub fn log2(p: u32, q: u32) -> u32 { loop { let term = taylor_term(k, y_num.into(), y_den.into()); if term == 0 { - break; + break } res += term; diff --git a/frame/staking/reward-fn/src/lib.rs b/frame/staking/reward-fn/src/lib.rs index 845b16702f011..dd5e629b3984c 100644 --- a/frame/staking/reward-fn/src/lib.rs +++ b/frame/staking/reward-fn/src/lib.rs @@ -55,12 +55,12 @@ use sp_arithmetic::{ pub fn compute_inflation(stake: P, ideal_stake: P, falloff: P) -> P { if stake < ideal_stake { // ideal_stake is more than 0 because it is strictly more than stake - return stake / ideal_stake; + return stake / ideal_stake } if falloff < P::from_percent(1.into()) { log::error!("Invalid inflation computation: falloff less than 1% is not supported"); - return PerThing::zero(); + return PerThing::zero() } let accuracy = { @@ -97,7 +97,7 @@ pub fn compute_inflation(stake: P, ideal_stake: P, falloff: P) -> P _ => { log::error!("Invalid inflation computation: unexpected result {:?}", res); P::zero() - } + }, } } @@ -131,7 +131,7 @@ fn compute_taylor_serie_part(p: &INPoSParam) -> BigUint { last_taylor_term = compute_taylor_term(k, &last_taylor_term, p); if last_taylor_term.is_zero() { - break; + break } let last_taylor_term_positive = k % 2 == 0; @@ -156,7 +156,7 @@ fn compute_taylor_serie_part(p: &INPoSParam) -> BigUint { } if !taylor_sum_positive { - return BigUint::zero(); + return BigUint::zero() } taylor_sum.lstrip(); @@ -198,15 +198,15 @@ fn div_by_stripped(mut a: BigUint, b: &BigUint) -> BigUint { if b.len() == 0 { log::error!("Computation error: Invalid division"); - return BigUint::zero(); + return BigUint::zero() } if b.len() == 1 { - return a.div_unit(b.checked_get(0).unwrap_or(1)); + return a.div_unit(b.checked_get(0).unwrap_or(1)) } if b.len() > a.len() { - return BigUint::zero(); + return BigUint::zero() } if b.len() == a.len() { @@ -220,7 +220,7 @@ fn div_by_stripped(mut a: BigUint, b: &BigUint) -> BigUint { .map(|res| res.0) .unwrap_or_else(|| BigUint::zero()) .div_unit(100_000) - .div_unit(100_000); + .div_unit(100_000) } a.div(b, false).map(|res| res.0).unwrap_or_else(|| BigUint::zero()) diff --git a/frame/staking/src/benchmarking.rs b/frame/staking/src/benchmarking.rs index ec91cf785bf72..220e8f1e6a24c 100644 --- a/frame/staking/src/benchmarking.rs +++ b/frame/staking/src/benchmarking.rs @@ -50,7 +50,7 @@ const MAX_SLASHES: u32 = 1000; // read and write operations. fn add_slashing_spans(who: &T::AccountId, spans: u32) { if spans == 0 { - return; + return } // For the first slashing span, we initialize diff --git a/frame/staking/src/inflation.rs b/frame/staking/src/inflation.rs index 8811f3514e57a..8e44a8c5482e5 100644 --- a/frame/staking/src/inflation.rs +++ b/frame/staking/src/inflation.rs @@ -42,8 +42,8 @@ where const MILLISECONDS_PER_YEAR: u64 = 1000 * 3600 * 24 * 36525 / 100; let portion = Perbill::from_rational(era_duration as u64, MILLISECONDS_PER_YEAR); - let payout = portion - * yearly_inflation + let payout = portion * + yearly_inflation .calculate_for_fraction_times_denominator(npos_token_staked, total_tokens.clone()); let maximum = portion * (yearly_inflation.maximum * total_tokens); (payout, maximum) diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 61aef8bf93638..be02e8d91d326 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -498,7 +498,7 @@ impl } if unlocking_balance >= value { - break; + break } } diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index a6137bd7b9614..95d397359f8d6 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -585,7 +585,7 @@ fn check_nominators() { e.others.iter().filter(|e| e.who == nominator).collect::>(); let len = individual.len(); match len { - 0 => { /* not supporting this validator at all. */ } + 0 => { /* not supporting this validator at all. */ }, 1 => sum += individual[0].value, _ => panic!("nominator cannot back a validator more than once."), }; @@ -769,9 +769,9 @@ pub(crate) fn on_offence_in_era( for &(bonded_era, start_session) in bonded_eras.iter() { if bonded_era == era { let _ = Staking::on_offence(offenders, slash_fraction, start_session); - return; + return } else if bonded_era > era { - break; + break } } diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index 2958d07ca8bcb..02099d8543d4c 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -143,7 +143,7 @@ impl Pallet { // Nothing to do if they have no reward points. if validator_reward_points.is_zero() { - return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into()); + return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into()) } // This is the fraction of the total reward that the validator and the @@ -235,9 +235,8 @@ impl Pallet { Self::update_ledger(&controller, &l); r }), - RewardDestination::Account(dest_account) => { - Some(T::Currency::deposit_creating(&dest_account, amount)) - } + RewardDestination::Account(dest_account) => + Some(T::Currency::deposit_creating(&dest_account, amount)), RewardDestination::None => None, } } @@ -265,14 +264,14 @@ impl Pallet { _ => { // Either `Forcing::ForceNone`, // or `Forcing::NotForcing if era_length >= T::SessionsPerEra::get()`. - return None; - } + return None + }, } // New era. let maybe_new_era_validators = Self::try_trigger_new_era(session_index, is_genesis); - if maybe_new_era_validators.is_some() - && matches!(ForceEra::::get(), Forcing::ForceNew) + if maybe_new_era_validators.is_some() && + matches!(ForceEra::::get(), Forcing::ForceNew) { ForceEra::::put(Forcing::NotForcing); } @@ -458,12 +457,12 @@ impl Pallet { // TODO: this should be simplified #8911 CurrentEra::::put(0); ErasStartSessionIndex::::insert(&0, &start_session_index); - } + }, _ => (), } Self::deposit_event(Event::StakingElectionFailed); - return None; + return None } Self::deposit_event(Event::StakersElected); @@ -699,7 +698,7 @@ impl Pallet { Some(nominator) => { nominators_seen.saturating_inc(); nominator - } + }, None => break, }; @@ -877,7 +876,7 @@ impl ElectionDataProvider> for Pallet // We can't handle this case yet -- return an error. if maybe_max_len.map_or(false, |max_len| target_count > max_len as u32) { - return Err("Target snapshot too big"); + return Err("Target snapshot too big") } Ok(Self::get_npos_targets()) @@ -1143,7 +1142,7 @@ where add_db_reads_writes(1, 0); if active_era.is_none() { // This offence need not be re-submitted. - return consumed_weight; + return consumed_weight } active_era.expect("value checked not to be `None`; qed").index }; @@ -1189,7 +1188,7 @@ where // Skip if the validator is invulnerable. if invulnerables.contains(stash) { - continue; + continue } let unapplied = slashing::compute_slash::(slashing::SlashParams { diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index 3ecae1a80f9a7..8e97a90e07544 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -907,23 +907,24 @@ pub mod pallet { ledger = ledger.consolidate_unlocked(current_era) } - let post_info_weight = - if ledger.unlocking.is_empty() && ledger.active < T::Currency::minimum_balance() { - // This account must have called `unbond()` with some value that caused the active - // portion to fall below existential deposit + will have no more unlocking chunks - // left. We can now safely remove all staking-related information. - Self::kill_stash(&stash, num_slashing_spans)?; - // Remove the lock. - T::Currency::remove_lock(STAKING_ID, &stash); - // This is worst case scenario, so we use the full weight and return None - None - } else { - // This was the consequence of a partial unbond. just update the ledger and move on. - Self::update_ledger(&controller, &ledger); + let post_info_weight = if ledger.unlocking.is_empty() && + ledger.active < T::Currency::minimum_balance() + { + // This account must have called `unbond()` with some value that caused the active + // portion to fall below existential deposit + will have no more unlocking chunks + // left. We can now safely remove all staking-related information. + Self::kill_stash(&stash, num_slashing_spans)?; + // Remove the lock. + T::Currency::remove_lock(STAKING_ID, &stash); + // This is worst case scenario, so we use the full weight and return None + None + } else { + // This was the consequence of a partial unbond. just update the ledger and move on. + Self::update_ledger(&controller, &ledger); - // This is only an update, so we use less overall weight. - Some(T::WeightInfo::withdraw_unbonded_update(num_slashing_spans)) - }; + // This is only an update, so we use less overall weight. + Some(T::WeightInfo::withdraw_unbonded_update(num_slashing_spans)) + }; // `old_total` should never be less than the new total because // `consolidate_unlocked` strictly subtracts balance. diff --git a/frame/staking/src/slashing.rs b/frame/staking/src/slashing.rs index 6fccf91fe3947..68088d0e0d777 100644 --- a/frame/staking/src/slashing.rs +++ b/frame/staking/src/slashing.rs @@ -123,7 +123,7 @@ impl SlashingSpans { pub(crate) fn end_span(&mut self, now: EraIndex) -> bool { let next_start = now + 1; if next_start <= self.last_start { - return false; + return false } let last_length = next_start - self.last_start; @@ -170,7 +170,7 @@ impl SlashingSpans { self.prior.truncate(o); let new_earliest = self.span_index - self.prior.len() as SpanIndex; Some((earliest_span_index, new_earliest)) - } + }, None => None, }; @@ -236,7 +236,7 @@ pub(crate) fn compute_slash( // kick out the validator even if they won't be slashed, // as long as the misbehavior is from their most recent slashing span. kick_out_if_recent::(params); - return None; + return None } let (prior_slash_p, _era_slash) = @@ -255,7 +255,7 @@ pub(crate) fn compute_slash( // pays out some reward even if the latest report is not max-in-era. // we opt to avoid the nominator lookups and edits and leave more rewards // for more drastic misbehavior. - return None; + return None } // apply slash to validator. @@ -350,7 +350,7 @@ fn add_offending_validator(stash: &T::AccountId, disable: bool) { if disable { T::SessionInterface::disable_validator(validator_index_u32); } - } + }, Ok(index) => { if disable && !offending[index].1 { // the validator had previously offended without being disabled, @@ -358,7 +358,7 @@ fn add_offending_validator(stash: &T::AccountId, disable: bool) { offending[index].1 = true; T::SessionInterface::disable_validator(validator_index_u32); } - } + }, } }); } @@ -542,7 +542,7 @@ impl<'a, T: 'a + Config> Drop for InspectingSpans<'a, T> { fn drop(&mut self) { // only update on disk if we slashed this account. if !self.dirty { - return; + return } if let Some((start, end)) = self.spans.prune(self.window_start) { @@ -656,7 +656,7 @@ fn pay_reporters( // nobody to pay out to or nothing to pay; // just treat the whole value as slashed. T::Slash::on_unbalanced(slashed_imbalance); - return; + return } // take rewards out of the slashed imbalance. diff --git a/frame/staking/src/testing_utils.rs b/frame/staking/src/testing_utils.rs index 7ed7d97ebe4d9..13762cf5886db 100644 --- a/frame/staking/src/testing_utils.rs +++ b/frame/staking/src/testing_utils.rs @@ -85,7 +85,7 @@ pub fn create_stash_controller( amount, destination, )?; - return Ok((stash, controller)); + return Ok((stash, controller)) } /// Create a stash and controller pair with fixed balance. @@ -127,7 +127,7 @@ pub fn create_stash_and_dead_controller( amount, destination, )?; - return Ok((stash, controller)); + return Ok((stash, controller)) } /// create `max` validators. diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 0c71c6394a2d6..d6d92d5bd57fc 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -275,9 +275,9 @@ fn rewards_should_work() { assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2); assert_eq_error_rate!( Balances::total_balance(&100), - init_balance_100 - + part_for_100_from_10 * total_payout_0 * 2 / 3 - + part_for_100_from_20 * total_payout_0 * 1 / 3, + init_balance_100 + + part_for_100_from_10 * total_payout_0 * 2 / 3 + + part_for_100_from_20 * total_payout_0 * 1 / 3, 2 ); assert_eq_error_rate!(Balances::total_balance(&101), init_balance_101, 2); @@ -313,9 +313,9 @@ fn rewards_should_work() { assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2); assert_eq_error_rate!( Balances::total_balance(&100), - init_balance_100 - + part_for_100_from_10 * (total_payout_0 * 2 / 3 + total_payout_1) - + part_for_100_from_20 * total_payout_0 * 1 / 3, + init_balance_100 + + part_for_100_from_10 * (total_payout_0 * 2 / 3 + total_payout_1) + + part_for_100_from_20 * total_payout_0 * 1 / 3, 2 ); assert_eq_error_rate!(Balances::total_balance(&101), init_balance_101, 2); @@ -3985,8 +3985,8 @@ mod election_data_provider { #[test] fn targets_2sec_block() { let mut validators = 1000; - while ::WeightInfo::get_npos_targets(validators) - < 2 * frame_support::weights::constants::WEIGHT_PER_SECOND + while ::WeightInfo::get_npos_targets(validators) < + 2 * frame_support::weights::constants::WEIGHT_PER_SECOND { validators += 1; } @@ -4003,8 +4003,8 @@ mod election_data_provider { let slashing_spans = validators; let mut nominators = 1000; - while ::WeightInfo::get_npos_voters(validators, nominators, slashing_spans) - < 2 * frame_support::weights::constants::WEIGHT_PER_SECOND + while ::WeightInfo::get_npos_voters(validators, nominators, slashing_spans) < + 2 * frame_support::weights::constants::WEIGHT_PER_SECOND { nominators += 1; } @@ -4076,8 +4076,8 @@ mod election_data_provider { .build_and_execute(|| { // sum of all nominators who'd be voters (1), plus the self-votes (4). assert_eq!( - ::SortedListProvider::count() - + >::iter().count() as u32, + ::SortedListProvider::count() + + >::iter().count() as u32, 5 ); @@ -4116,8 +4116,8 @@ mod election_data_provider { // and total voters assert_eq!( - ::SortedListProvider::count() - + >::iter().count() as u32, + ::SortedListProvider::count() + + >::iter().count() as u32, 7 ); @@ -4161,8 +4161,8 @@ mod election_data_provider { // and total voters assert_eq!( - ::SortedListProvider::count() - + >::iter().count() as u32, + ::SortedListProvider::count() + + >::iter().count() as u32, 6 ); diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index fc6187bde7682..427455849bb00 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -52,7 +52,7 @@ //! This is an example of a pallet that exposes a privileged function: //! //! ``` -//! +//! //! #[frame_support::pallet] //! pub mod logger { //! use frame_support::pallet_prelude::*; diff --git a/frame/support/procedural/src/clone_no_bound.rs b/frame/support/procedural/src/clone_no_bound.rs index 8810bd4fcc029..747900fd023f6 100644 --- a/frame/support/procedural/src/clone_no_bound.rs +++ b/frame/support/procedural/src/clone_no_bound.rs @@ -37,7 +37,7 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke }); quote::quote!( Self { #( #fields, )* } ) - } + }, syn::Fields::Unnamed(unnamed) => { let fields = unnamed.unnamed.iter().enumerate().map(|(i, _)| syn::Index::from(i)).map(|i| { @@ -47,10 +47,10 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke }); quote::quote!( Self ( #( #fields, )* ) ) - } + }, syn::Fields::Unit => { quote::quote!(Self) - } + }, }, syn::Data::Enum(enum_) => { let variants = enum_.variants.iter().map(|variant| { @@ -66,7 +66,7 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke quote::quote!( Self::#ident { #( ref #captured, )* } => Self::#ident { #( #cloned, )*} ) - } + }, syn::Fields::Unnamed(unnamed) => { let captured = unnamed .unnamed @@ -81,7 +81,7 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke quote::quote!( Self::#ident ( #( ref #captured, )* ) => Self::#ident ( #( #cloned, )*) ) - } + }, syn::Fields::Unit => quote::quote!( Self::#ident => Self::#ident ), } }); @@ -89,11 +89,11 @@ pub fn derive_clone_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke quote::quote!(match self { #( #variants, )* }) - } + }, syn::Data::Union(_) => { let msg = "Union type not supported by `derive(CloneNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into(); - } + return syn::Error::new(input.span(), msg).to_compile_error().into() + }, }; quote::quote!( diff --git a/frame/support/procedural/src/construct_runtime/expand/event.rs b/frame/support/procedural/src/construct_runtime/expand/event.rs index 4a62ab372f4b4..798646bf27334 100644 --- a/frame/support/procedural/src/construct_runtime/expand/event.rs +++ b/frame/support/procedural/src/construct_runtime/expand/event.rs @@ -43,7 +43,7 @@ pub fn expand_outer_event( be constructed: pallet `{}` must have generic `Event`", pallet_name, ); - return Err(syn::Error::new(pallet_name.span(), msg)); + return Err(syn::Error::new(pallet_name.span(), msg)) } let part_is_generic = !generics.params.is_empty(); @@ -101,16 +101,16 @@ fn expand_event_variant( match instance { Some(inst) if part_is_generic => { quote!(#[codec(index = #index)] #variant_name(#path::Event<#runtime, #path::#inst>),) - } + }, Some(inst) => { quote!(#[codec(index = #index)] #variant_name(#path::Event<#path::#inst>),) - } + }, None if part_is_generic => { quote!(#[codec(index = #index)] #variant_name(#path::Event<#runtime>),) - } + }, None => { quote!(#[codec(index = #index)] #variant_name(#path::Event),) - } + }, } } diff --git a/frame/support/procedural/src/construct_runtime/expand/origin.rs b/frame/support/procedural/src/construct_runtime/expand/origin.rs index fd822fcb55755..57adf86a9fe18 100644 --- a/frame/support/procedural/src/construct_runtime/expand/origin.rs +++ b/frame/support/procedural/src/construct_runtime/expand/origin.rs @@ -53,7 +53,7 @@ pub fn expand_outer_origin( be constructed: pallet `{}` must have generic `Origin`", name ); - return Err(syn::Error::new(name.span(), msg)); + return Err(syn::Error::new(name.span(), msg)) } caller_variants.extend(expand_origin_caller_variant( @@ -281,16 +281,16 @@ fn expand_origin_caller_variant( match instance { Some(inst) if part_is_generic => { quote!(#[codec(index = #index)] #variant_name(#path::Origin<#runtime, #path::#inst>),) - } + }, Some(inst) => { quote!(#[codec(index = #index)] #variant_name(#path::Origin<#path::#inst>),) - } + }, None if part_is_generic => { quote!(#[codec(index = #index)] #variant_name(#path::Origin<#runtime>),) - } + }, None => { quote!(#[codec(index = #index)] #variant_name(#path::Origin),) - } + }, } } diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index d318955aa6535..863df34266591 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -84,7 +84,7 @@ fn complete_pallets(decl: impl Iterator) -> syn::Resul ); let mut err = syn::Error::new(used_pallet.span(), &msg); err.combine(syn::Error::new(pallet.name.span(), msg)); - return Err(err); + return Err(err) } if let Some(used_pallet) = names.insert(pallet.name.clone(), pallet.name.span()) { @@ -92,7 +92,7 @@ fn complete_pallets(decl: impl Iterator) -> syn::Resul let mut err = syn::Error::new(used_pallet, &msg); err.combine(syn::Error::new(pallet.name.span(), &msg)); - return Err(err); + return Err(err) } Ok(Pallet { diff --git a/frame/support/procedural/src/construct_runtime/parse.rs b/frame/support/procedural/src/construct_runtime/parse.rs index e68966aeb6d38..a0ec6dfa5803e 100644 --- a/frame/support/procedural/src/construct_runtime/parse.rs +++ b/frame/support/procedural/src/construct_runtime/parse.rs @@ -77,9 +77,9 @@ impl Parse for WhereSection { definitions.push(definition); if !input.peek(Token![,]) { if !input.peek(token::Brace) { - return Err(input.error("Expected `,` or `{`")); + return Err(input.error("Expected `,` or `{`")) } - break; + break } input.parse::()?; } @@ -92,7 +92,7 @@ impl Parse for WhereSection { "`{:?}` was declared above. Please use exactly one declaration for `{:?}`.", kind, kind ); - return Err(Error::new(*kind_span, msg)); + return Err(Error::new(*kind_span, msg)) } Ok(Self { block, node_block, unchecked_extrinsic }) } @@ -122,7 +122,7 @@ impl Parse for WhereDefinition { } else if lookahead.peek(keyword::UncheckedExtrinsic) { (input.parse::()?.span(), WhereKind::UncheckedExtrinsic) } else { - return Err(lookahead.error()); + return Err(lookahead.error()) }; Ok(Self { @@ -205,17 +205,17 @@ impl Parse for PalletPath { let mut lookahead = input.lookahead1(); let mut segments = Punctuated::new(); - if lookahead.peek(Token![crate]) - || lookahead.peek(Token![self]) - || lookahead.peek(Token![super]) - || lookahead.peek(Ident) + if lookahead.peek(Token![crate]) || + lookahead.peek(Token![self]) || + lookahead.peek(Token![super]) || + lookahead.peek(Ident) { let ident = input.call(Ident::parse_any)?; segments.push(PathSegment { ident, arguments: PathArguments::None }); let _: Token![::] = input.parse()?; lookahead = input.lookahead1(); } else { - return Err(lookahead.error()); + return Err(lookahead.error()) } while lookahead.peek(Ident) { @@ -226,7 +226,7 @@ impl Parse for PalletPath { } if !lookahead.peek(token::Brace) && !lookahead.peek(Token![<]) { - return Err(lookahead.error()); + return Err(lookahead.error()) } Ok(Self { inner: Path { leading_colon: None, segments } }) @@ -252,7 +252,7 @@ fn parse_pallet_parts(input: ParseStream) -> Result> { "`{}` was already declared before. Please remove the duplicate declaration", part.name(), ); - return Err(Error::new(part.keyword.span(), msg)); + return Err(Error::new(part.keyword.span(), msg)) } } @@ -357,7 +357,7 @@ impl Parse for PalletPart { keyword.name(), valid_generics, ); - return Err(syn::Error::new(keyword.span(), msg)); + return Err(syn::Error::new(keyword.span(), msg)) } Ok(Self { keyword, generics }) diff --git a/frame/support/procedural/src/crate_version.rs b/frame/support/procedural/src/crate_version.rs index 02d54b8b5aca2..cfa35c6190e15 100644 --- a/frame/support/procedural/src/crate_version.rs +++ b/frame/support/procedural/src/crate_version.rs @@ -30,7 +30,7 @@ fn create_error(message: &str) -> Error { /// Implementation of the `crate_to_crate_version!` macro. pub fn crate_to_crate_version(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(create_error("No arguments expected!")); + return Err(create_error("No arguments expected!")) } let major_version = get_cargo_env_var::("CARGO_PKG_VERSION_MAJOR") diff --git a/frame/support/procedural/src/debug_no_bound.rs b/frame/support/procedural/src/debug_no_bound.rs index ad6753ebf48f8..acfd8d0cabc8a 100644 --- a/frame/support/procedural/src/debug_no_bound.rs +++ b/frame/support/procedural/src/debug_no_bound.rs @@ -40,7 +40,7 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke #( #fields )* .finish() ) - } + }, syn::Fields::Unnamed(unnamed) => { let fields = unnamed .unnamed @@ -54,7 +54,7 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke #( #fields )* .finish() ) - } + }, syn::Fields::Unit => quote::quote!(fmt.write_str(stringify!(#input_ident))), }, syn::Data::Enum(enum_) => { @@ -76,7 +76,7 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke .finish() } ) - } + }, syn::Fields::Unnamed(unnamed) => { let captured = unnamed .unnamed @@ -93,7 +93,7 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke .finish() } ) - } + }, syn::Fields::Unit => quote::quote!( Self::#ident => fmt.write_str(#full_variant_str) ), @@ -103,11 +103,11 @@ pub fn derive_debug_no_bound(input: proc_macro::TokenStream) -> proc_macro::Toke quote::quote!(match *self { #( #variants, )* }) - } + }, syn::Data::Union(_) => { let msg = "Union type not supported by `derive(DebugNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into(); - } + return syn::Error::new(input.span(), msg).to_compile_error().into() + }, }; quote::quote!( diff --git a/frame/support/procedural/src/default_no_bound.rs b/frame/support/procedural/src/default_no_bound.rs index 2550326671b5f..38d6e19b1732f 100644 --- a/frame/support/procedural/src/default_no_bound.rs +++ b/frame/support/procedural/src/default_no_bound.rs @@ -37,7 +37,7 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To }); quote::quote!( Self { #( #fields, )* } ) - } + }, syn::Fields::Unnamed(unnamed) => { let fields = unnamed.unnamed.iter().enumerate().map(|(i, _)| syn::Index::from(i)).map(|i| { @@ -47,12 +47,12 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To }); quote::quote!( Self ( #( #fields, )* ) ) - } + }, syn::Fields::Unit => { quote::quote!(Self) - } + }, }, - syn::Data::Enum(enum_) => { + syn::Data::Enum(enum_) => if let Some(first_variant) = enum_.variants.first() { let variant_ident = &first_variant.ident; match &first_variant.fields { @@ -64,7 +64,7 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To }); quote::quote!( #name :: #ty_generics :: #variant_ident { #( #fields, )* } ) - } + }, syn::Fields::Unnamed(unnamed) => { let fields = unnamed .unnamed @@ -78,17 +78,16 @@ pub fn derive_default_no_bound(input: proc_macro::TokenStream) -> proc_macro::To }); quote::quote!( #name :: #ty_generics :: #variant_ident ( #( #fields, )* ) ) - } + }, syn::Fields::Unit => quote::quote!( #name :: #ty_generics :: #variant_ident ), } } else { quote::quote!(Self) - } - } + }, syn::Data::Union(_) => { let msg = "Union type not supported by `derive(CloneNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into(); - } + return syn::Error::new(input.span(), msg).to_compile_error().into() + }, }; quote::quote!( diff --git a/frame/support/procedural/src/dummy_part_checker.rs b/frame/support/procedural/src/dummy_part_checker.rs index 0377fb04e778d..792b17a8f7758 100644 --- a/frame/support/procedural/src/dummy_part_checker.rs +++ b/frame/support/procedural/src/dummy_part_checker.rs @@ -5,7 +5,7 @@ pub fn generate_dummy_part_checker(input: TokenStream) -> TokenStream { if !input.is_empty() { return syn::Error::new(proc_macro2::Span::call_site(), "No arguments expected") .to_compile_error() - .into(); + .into() } let count = COUNTER.with(|counter| counter.borrow_mut().inc()); diff --git a/frame/support/procedural/src/key_prefix.rs b/frame/support/procedural/src/key_prefix.rs index 53305e396f375..3f424e8b8b8dd 100644 --- a/frame/support/procedural/src/key_prefix.rs +++ b/frame/support/procedural/src/key_prefix.rs @@ -23,7 +23,7 @@ const MAX_IDENTS: usize = 18; pub fn impl_key_prefix_for_tuples(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")); + return Err(syn::Error::new(Span::call_site(), "No arguments expected")) } let mut all_trait_impls = TokenStream::new(); diff --git a/frame/support/procedural/src/pallet/expand/call.rs b/frame/support/procedural/src/pallet/expand/call.rs index 6baa5694b51ef..8f7bcdccaf22d 100644 --- a/frame/support/procedural/src/pallet/expand/call.rs +++ b/frame/support/procedural/src/pallet/expand/call.rs @@ -30,7 +30,7 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { let docs = call.docs.clone(); (span, where_clause, methods, docs) - } + }, None => (def.item.span(), None, Vec::new(), Vec::new()), }; let frame_support = &def.frame_support; diff --git a/frame/support/procedural/src/pallet/expand/event.rs b/frame/support/procedural/src/pallet/expand/event.rs index ac915817b8d79..625c2d98baac5 100644 --- a/frame/support/procedural/src/pallet/expand/event.rs +++ b/frame/support/procedural/src/pallet/expand/event.rs @@ -55,7 +55,7 @@ pub fn expand_event(def: &mut Def) -> proc_macro2::TokenStream { #[doc(hidden)] pub use #macro_ident as is_event_part_defined; } - }; + } }; let event_where_clause = &event.where_clause; diff --git a/frame/support/procedural/src/pallet/expand/genesis_build.rs b/frame/support/procedural/src/pallet/expand/genesis_build.rs index fce251948ecad..06acaf324254c 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_build.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_build.rs @@ -24,7 +24,7 @@ pub fn expand_genesis_build(def: &mut Def) -> proc_macro2::TokenStream { let genesis_config = if let Some(genesis_config) = &def.genesis_config { genesis_config } else { - return Default::default(); + return Default::default() }; let genesis_build = def.genesis_build.as_ref().expect("Checked by def parser"); diff --git a/frame/support/procedural/src/pallet/expand/genesis_config.rs b/frame/support/procedural/src/pallet/expand/genesis_config.rs index 6562add2a51db..b2eb2166165cb 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_config.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_config.rs @@ -71,7 +71,7 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { #[doc(hidden)] pub use #std_macro_ident as is_std_enabled_for_genesis; } - }; + } }; let frame_support = &def.frame_support; @@ -82,9 +82,9 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { let serde_crate = format!("{}::serde", frame_support); match genesis_config_item { - syn::Item::Enum(syn::ItemEnum { attrs, .. }) - | syn::Item::Struct(syn::ItemStruct { attrs, .. }) - | syn::Item::Type(syn::ItemType { attrs, .. }) => { + syn::Item::Enum(syn::ItemEnum { attrs, .. }) | + syn::Item::Struct(syn::ItemStruct { attrs, .. }) | + syn::Item::Type(syn::ItemType { attrs, .. }) => { if get_doc_literals(&attrs).is_empty() { attrs.push(syn::parse_quote!( #[doc = r" @@ -103,7 +103,7 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { attrs.push(syn::parse_quote!( #[serde(bound(serialize = ""))] )); attrs.push(syn::parse_quote!( #[serde(bound(deserialize = ""))] )); attrs.push(syn::parse_quote!( #[serde(crate = #serde_crate)] )); - } + }, _ => unreachable!("Checked by genesis_config parser"), } diff --git a/frame/support/procedural/src/pallet/expand/hooks.rs b/frame/support/procedural/src/pallet/expand/hooks.rs index 99a51387c13be..e0b7e3669da43 100644 --- a/frame/support/procedural/src/pallet/expand/hooks.rs +++ b/frame/support/procedural/src/pallet/expand/hooks.rs @@ -26,7 +26,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { let span = hooks.attr_span; let has_runtime_upgrade = hooks.has_runtime_upgrade; (where_clause, span, has_runtime_upgrade) - } + }, None => (None, def.pallet_struct.attr_span, false), }; diff --git a/frame/support/procedural/src/pallet/expand/storage.rs b/frame/support/procedural/src/pallet/expand/storage.rs index d3402de5301c3..a4f030722f1c1 100644 --- a/frame/support/procedural/src/pallet/expand/storage.rs +++ b/frame/support/procedural/src/pallet/expand/storage.rs @@ -60,7 +60,7 @@ fn check_prefix_duplicates( if let Some(other_dup_err) = used_prefixes.insert(prefix.clone(), dup_err.clone()) { let mut err = dup_err; err.combine(other_dup_err); - return Err(err); + return Err(err) } if let Metadata::CountedMap { .. } = storage_def.metadata { @@ -79,7 +79,7 @@ fn check_prefix_duplicates( { let mut err = counter_dup_err; err.combine(other_dup_err); - return Err(err); + return Err(err) } } @@ -135,7 +135,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(query_kind)); let on_empty = on_empty.unwrap_or_else(|| default_on_empty.clone()); args.args.push(syn::GenericArgument::Type(on_empty)); - } + }, StorageGenerics::Map { hasher, key, value, query_kind, on_empty, max_values } => { args.args.push(syn::GenericArgument::Type(hasher)); args.args.push(syn::GenericArgument::Type(key)); @@ -146,7 +146,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(on_empty)); let max_values = max_values.unwrap_or_else(|| default_max_values.clone()); args.args.push(syn::GenericArgument::Type(max_values)); - } + }, StorageGenerics::CountedMap { hasher, key, @@ -164,7 +164,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(on_empty)); let max_values = max_values.unwrap_or_else(|| default_max_values.clone()); args.args.push(syn::GenericArgument::Type(max_values)); - } + }, StorageGenerics::DoubleMap { hasher1, key1, @@ -186,7 +186,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(on_empty)); let max_values = max_values.unwrap_or_else(|| default_max_values.clone()); args.args.push(syn::GenericArgument::Type(max_values)); - } + }, StorageGenerics::NMap { keygen, value, query_kind, on_empty, max_values } => { args.args.push(syn::GenericArgument::Type(keygen)); args.args.push(syn::GenericArgument::Type(value)); @@ -196,7 +196,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { args.args.push(syn::GenericArgument::Type(on_empty)); let max_values = max_values.unwrap_or_else(|| default_max_values.clone()); args.args.push(syn::GenericArgument::Type(max_values)); - } + }, } } else { args.args[0] = syn::parse_quote!( #prefix_ident<#type_use_gen> ); @@ -215,7 +215,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { /// * generate metadatas pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { if let Err(e) = process_generics(def) { - return e.into_compile_error().into(); + return e.into_compile_error().into() } // Check for duplicate prefixes @@ -226,7 +226,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { .filter_map(|storage_def| check_prefix_duplicates(storage_def, &mut prefix_set).err()); if let Some(mut final_error) = errors.next() { errors.for_each(|error| final_error.combine(error)); - return final_error.into_compile_error(); + return final_error.into_compile_error() } let frame_support = &def.frame_support; @@ -291,7 +291,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - } + }, Metadata::Map { key, value } => { let query = match storage.query_kind.as_ref().expect("Checked by def") { QueryKind::OptionQuery => quote::quote_spanned!(storage.attr_span => @@ -312,7 +312,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - } + }, Metadata::CountedMap { key, value } => { let query = match storage.query_kind.as_ref().expect("Checked by def") { QueryKind::OptionQuery => quote::quote_spanned!(storage.attr_span => @@ -333,7 +333,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - } + }, Metadata::DoubleMap { key1, key2, value } => { let query = match storage.query_kind.as_ref().expect("Checked by def") { QueryKind::OptionQuery => quote::quote_spanned!(storage.attr_span => @@ -356,7 +356,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - } + }, Metadata::NMap { keygen, value, .. } => { let query = match storage.query_kind.as_ref().expect("Checked by def") { QueryKind::OptionQuery => quote::quote_spanned!(storage.attr_span => @@ -382,7 +382,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { } } ) - } + }, } } else { Default::default() diff --git a/frame/support/procedural/src/pallet/mod.rs b/frame/support/procedural/src/pallet/mod.rs index 2e2e7e8476160..93797906d04d9 100644 --- a/frame/support/procedural/src/pallet/mod.rs +++ b/frame/support/procedural/src/pallet/mod.rs @@ -40,7 +40,7 @@ pub fn pallet( "Invalid pallet macro call: expected no attributes, e.g. macro call must be just \ `#[frame_support::pallet]` or `#[pallet]`"; let span = proc_macro2::TokenStream::from(attr).span(); - return syn::Error::new(span, msg).to_compile_error().into(); + return syn::Error::new(span, msg).to_compile_error().into() } let item = syn::parse_macro_input!(item as syn::ItemMod); diff --git a/frame/support/procedural/src/pallet/parse/call.rs b/frame/support/procedural/src/pallet/parse/call.rs index e0ba5a8c3dd9a..0563568f33311 100644 --- a/frame/support/procedural/src/pallet/parse/call.rs +++ b/frame/support/procedural/src/pallet/parse/call.rs @@ -130,7 +130,7 @@ impl CallDef { let item = if let syn::Item::Impl(item) = item { item } else { - return Err(syn::Error::new(item.span(), "Invalid pallet::call, expected item impl")); + return Err(syn::Error::new(item.span(), "Invalid pallet::call, expected item impl")) }; let mut instances = vec![]; @@ -140,7 +140,7 @@ impl CallDef { if let Some((_, _, for_)) = item.trait_ { let msg = "Invalid pallet::call, expected no trait ident as in \ `impl<..> Pallet<..> { .. }`"; - return Err(syn::Error::new(for_.span(), msg)); + return Err(syn::Error::new(for_.span(), msg)) } let mut methods = vec![]; @@ -155,22 +155,22 @@ impl CallDef { _ => method.vis.span(), }; - return Err(syn::Error::new(span, msg)); + return Err(syn::Error::new(span, msg)) } match method.sig.inputs.first() { None => { let msg = "Invalid pallet::call, must have at least origin arg"; - return Err(syn::Error::new(method.sig.span(), msg)); - } + return Err(syn::Error::new(method.sig.span(), msg)) + }, Some(syn::FnArg::Receiver(_)) => { let msg = "Invalid pallet::call, first argument must be a typed argument, \ e.g. `origin: OriginFor`"; - return Err(syn::Error::new(method.sig.span(), msg)); - } + return Err(syn::Error::new(method.sig.span(), msg)) + }, Some(syn::FnArg::Typed(arg)) => { check_dispatchable_first_arg_type(&*arg.ty)?; - } + }, } if let syn::ReturnType::Type(_, type_) = &method.sig.output { @@ -178,7 +178,7 @@ impl CallDef { } else { let msg = "Invalid pallet::call, require return type \ DispatchResultWithPostInfo"; - return Err(syn::Error::new(method.sig.span(), msg)); + return Err(syn::Error::new(method.sig.span(), msg)) } let mut call_var_attrs: Vec = @@ -190,7 +190,7 @@ impl CallDef { } else { "Invalid pallet::call, too many weight attributes given" }; - return Err(syn::Error::new(method.sig.span(), msg)); + return Err(syn::Error::new(method.sig.span(), msg)) } let weight = call_var_attrs.pop().unwrap().weight; @@ -207,14 +207,14 @@ impl CallDef { if arg_attrs.len() > 1 { let msg = "Invalid pallet::call, argument has too many attributes"; - return Err(syn::Error::new(arg.span(), msg)); + return Err(syn::Error::new(arg.span(), msg)) } let arg_ident = if let syn::Pat::Ident(pat) = &*arg.pat { pat.ident.clone() } else { let msg = "Invalid pallet::call, argument must be ident"; - return Err(syn::Error::new(arg.pat.span(), msg)); + return Err(syn::Error::new(arg.pat.span(), msg)) }; args.push((!arg_attrs.is_empty(), arg_ident, arg.ty.clone())); @@ -225,7 +225,7 @@ impl CallDef { methods.push(CallVariantDef { name: method.sig.ident.clone(), weight, args, docs }); } else { let msg = "Invalid pallet::call, only method accepted"; - return Err(syn::Error::new(impl_item.span(), msg)); + return Err(syn::Error::new(impl_item.span(), msg)) } } diff --git a/frame/support/procedural/src/pallet/parse/config.rs b/frame/support/procedural/src/pallet/parse/config.rs index b07c2ae602f84..712c20ffc7b4c 100644 --- a/frame/support/procedural/src/pallet/parse/config.rs +++ b/frame/support/procedural/src/pallet/parse/config.rs @@ -226,7 +226,7 @@ fn check_event_type( if !type_.generics.params.is_empty() || type_.generics.where_clause.is_some() { let msg = "Invalid `type Event`, associated type `Event` is reserved and must have\ no generics nor where_clause"; - return Err(syn::Error::new(trait_item.span(), msg)); + return Err(syn::Error::new(trait_item.span(), msg)) } // Check bound contains IsType and From @@ -241,7 +241,7 @@ fn check_event_type( bound: `IsType<::Event>`", frame_system, ); - return Err(syn::Error::new(type_.span(), msg)); + return Err(syn::Error::new(type_.span(), msg)) } let from_event_bound = type_ @@ -254,7 +254,7 @@ fn check_event_type( } else { let msg = "Invalid `type Event`, associated type `Event` is reserved and must \ bound: `From` or `From>` or `From>`"; - return Err(syn::Error::new(type_.span(), msg)); + return Err(syn::Error::new(type_.span(), msg)) }; if from_event_bound.is_generic && (from_event_bound.has_instance != trait_has_instance) @@ -262,7 +262,7 @@ fn check_event_type( let msg = "Invalid `type Event`, associated type `Event` bounds inconsistent \ `From`. Config and generic Event must be both with instance or \ without instance"; - return Err(syn::Error::new(type_.span(), msg)); + return Err(syn::Error::new(type_.span(), msg)) } Ok(true) @@ -279,12 +279,10 @@ pub fn replace_self_by_t(input: proc_macro2::TokenStream) -> proc_macro2::TokenS input .into_iter() .map(|token_tree| match token_tree { - proc_macro2::TokenTree::Group(group) => { - proc_macro2::Group::new(group.delimiter(), replace_self_by_t(group.stream())).into() - } - proc_macro2::TokenTree::Ident(ident) if ident == "Self" => { - proc_macro2::Ident::new("T", ident.span()).into() - } + proc_macro2::TokenTree::Group(group) => + proc_macro2::Group::new(group.delimiter(), replace_self_by_t(group.stream())).into(), + proc_macro2::TokenTree::Ident(ident) if ident == "Self" => + proc_macro2::Ident::new("T", ident.span()).into(), other => other, }) .collect() @@ -301,12 +299,12 @@ impl ConfigDef { item } else { let msg = "Invalid pallet::config, expected trait definition"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) }; if !matches!(item.vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::config, trait must be public"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) } syn::parse2::(item.ident.to_token_stream())?; @@ -321,7 +319,7 @@ impl ConfigDef { if item.generics.params.len() > 1 { let msg = "Invalid pallet::config, expected no more than one generic"; - return Err(syn::Error::new(item.generics.params[2].span(), msg)); + return Err(syn::Error::new(item.generics.params[2].span(), msg)) } let has_instance = if item.generics.params.first().is_some() { @@ -343,7 +341,7 @@ impl ConfigDef { if type_attrs_const.len() > 1 { let msg = "Invalid attribute in pallet::config, only one attribute is expected"; - return Err(syn::Error::new(type_attrs_const[1].span(), msg)); + return Err(syn::Error::new(type_attrs_const[1].span(), msg)) } if type_attrs_const.len() == 1 { @@ -351,13 +349,13 @@ impl ConfigDef { syn::TraitItem::Type(ref type_) => { let constant = ConstMetadataDef::try_from(type_)?; consts_metadata.push(constant); - } + }, _ => { let msg = "Invalid pallet::constant in pallet::config, expected type trait \ item"; - return Err(syn::Error::new(trait_item.span(), msg)); - } + return Err(syn::Error::new(trait_item.span(), msg)) + }, } } } @@ -392,7 +390,7 @@ impl ConfigDef { To disable this check, use `#[pallet::disable_frame_system_supertrait_check]`", frame_system, found, ); - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) } Ok(Self { index, has_instance, consts_metadata, has_event_type, where_clause, attr_span }) diff --git a/frame/support/procedural/src/pallet/parse/error.rs b/frame/support/procedural/src/pallet/parse/error.rs index 3afa0da866f19..9c9a95105c53c 100644 --- a/frame/support/procedural/src/pallet/parse/error.rs +++ b/frame/support/procedural/src/pallet/parse/error.rs @@ -49,11 +49,11 @@ impl ErrorDef { let item = if let syn::Item::Enum(item) = item { item } else { - return Err(syn::Error::new(item.span(), "Invalid pallet::error, expected item enum")); + return Err(syn::Error::new(item.span(), "Invalid pallet::error, expected item enum")) }; if !matches!(item.vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::error, `Error` must be public"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) } let mut instances = vec![]; @@ -61,7 +61,7 @@ impl ErrorDef { if item.generics.where_clause.is_some() { let msg = "Invalid pallet::error, where clause is not allowed on pallet error item"; - return Err(syn::Error::new(item.generics.where_clause.as_ref().unwrap().span(), msg)); + return Err(syn::Error::new(item.generics.where_clause.as_ref().unwrap().span(), msg)) } let error = syn::parse2::(item.ident.to_token_stream())?; @@ -72,13 +72,13 @@ impl ErrorDef { .map(|variant| { if !matches!(variant.fields, syn::Fields::Unit) { let msg = "Invalid pallet::error, unexpected fields, must be `Unit`"; - return Err(syn::Error::new(variant.fields.span(), msg)); + return Err(syn::Error::new(variant.fields.span(), msg)) } if variant.discriminant.is_some() { let msg = "Invalid pallet::error, unexpected discriminant, discriminant \ are not supported"; let span = variant.discriminant.as_ref().unwrap().0.span(); - return Err(syn::Error::new(span, msg)); + return Err(syn::Error::new(span, msg)) } Ok((variant.ident.clone(), get_doc_literals(&variant.attrs))) diff --git a/frame/support/procedural/src/pallet/parse/event.rs b/frame/support/procedural/src/pallet/parse/event.rs index a728cd00e5242..33de4aca8b599 100644 --- a/frame/support/procedural/src/pallet/parse/event.rs +++ b/frame/support/procedural/src/pallet/parse/event.rs @@ -87,7 +87,7 @@ impl PalletEventAttrInfo { if deposit_event.is_none() { deposit_event = Some(attr) } else { - return Err(syn::Error::new(attr.span, "Duplicate attribute")); + return Err(syn::Error::new(attr.span, "Duplicate attribute")) } } @@ -104,7 +104,7 @@ impl EventDef { let item = if let syn::Item::Enum(item) = item { item } else { - return Err(syn::Error::new(item.span(), "Invalid pallet::event, expected item enum")); + return Err(syn::Error::new(item.span(), "Invalid pallet::event, expected item enum")) }; let event_attrs: Vec = @@ -114,7 +114,7 @@ impl EventDef { if !matches!(item.vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::event, `Event` must be public"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) } let where_clause = item.generics.where_clause.clone(); diff --git a/frame/support/procedural/src/pallet/parse/extra_constants.rs b/frame/support/procedural/src/pallet/parse/extra_constants.rs index 9cf0642464267..a5f3c0a8c2dab 100644 --- a/frame/support/procedural/src/pallet/parse/extra_constants.rs +++ b/frame/support/procedural/src/pallet/parse/extra_constants.rs @@ -84,7 +84,7 @@ impl ExtraConstantsDef { return Err(syn::Error::new( item.span(), "Invalid pallet::extra_constants, expected item impl", - )); + )) }; let mut instances = vec![]; @@ -94,7 +94,7 @@ impl ExtraConstantsDef { if let Some((_, _, for_)) = item.trait_ { let msg = "Invalid pallet::call, expected no trait ident as in \ `impl<..> Pallet<..> { .. }`"; - return Err(syn::Error::new(for_.span(), msg)); + return Err(syn::Error::new(for_.span(), msg)) } let mut extra_constants = vec![]; @@ -103,29 +103,29 @@ impl ExtraConstantsDef { method } else { let msg = "Invalid pallet::call, only method accepted"; - return Err(syn::Error::new(impl_item.span(), msg)); + return Err(syn::Error::new(impl_item.span(), msg)) }; if !method.sig.inputs.is_empty() { let msg = "Invalid pallet::extra_constants, method must have 0 args"; - return Err(syn::Error::new(method.sig.span(), msg)); + return Err(syn::Error::new(method.sig.span(), msg)) } if !method.sig.generics.params.is_empty() { let msg = "Invalid pallet::extra_constants, method must have 0 generics"; - return Err(syn::Error::new(method.sig.generics.params[0].span(), msg)); + return Err(syn::Error::new(method.sig.generics.params[0].span(), msg)) } if method.sig.generics.where_clause.is_some() { let msg = "Invalid pallet::extra_constants, method must have no where clause"; - return Err(syn::Error::new(method.sig.generics.where_clause.span(), msg)); + return Err(syn::Error::new(method.sig.generics.where_clause.span(), msg)) } let type_ = match &method.sig.output { syn::ReturnType::Default => { let msg = "Invalid pallet::extra_constants, method must have a return type"; - return Err(syn::Error::new(method.span(), msg)); - } + return Err(syn::Error::new(method.span(), msg)) + }, syn::ReturnType::Type(_, type_) => *type_.clone(), }; @@ -136,7 +136,7 @@ impl ExtraConstantsDef { if extra_constant_attrs.len() > 1 { let msg = "Invalid attribute in pallet::constant_name, only one attribute is expected"; - return Err(syn::Error::new(extra_constant_attrs[1].metadata_name.span(), msg)); + return Err(syn::Error::new(extra_constant_attrs[1].metadata_name.span(), msg)) } let metadata_name = extra_constant_attrs.pop().map(|attr| attr.metadata_name); diff --git a/frame/support/procedural/src/pallet/parse/genesis_build.rs b/frame/support/procedural/src/pallet/parse/genesis_build.rs index 80a41c3dcdd1c..82e297b4e26e8 100644 --- a/frame/support/procedural/src/pallet/parse/genesis_build.rs +++ b/frame/support/procedural/src/pallet/parse/genesis_build.rs @@ -40,7 +40,7 @@ impl GenesisBuildDef { item } else { let msg = "Invalid pallet::genesis_build, expected item impl"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) }; let item_trait = &item diff --git a/frame/support/procedural/src/pallet/parse/genesis_config.rs b/frame/support/procedural/src/pallet/parse/genesis_config.rs index adcec0c625358..a0cf7de1a846b 100644 --- a/frame/support/procedural/src/pallet/parse/genesis_config.rs +++ b/frame/support/procedural/src/pallet/parse/genesis_config.rs @@ -42,8 +42,8 @@ impl GenesisConfigDef { syn::Item::Struct(item) => (&item.vis, &item.ident, &item.generics), _ => { let msg = "Invalid pallet::genesis_config, expected enum or struct"; - return Err(syn::Error::new(item.span(), msg)); - } + return Err(syn::Error::new(item.span(), msg)) + }, }; let mut instances = vec![]; @@ -60,12 +60,12 @@ impl GenesisConfigDef { if !matches!(vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::genesis_config, GenesisConfig must be public"; - return Err(syn::Error::new(item_span, msg)); + return Err(syn::Error::new(item_span, msg)) } if ident != "GenesisConfig" { let msg = "Invalid pallet::genesis_config, ident must `GenesisConfig`"; - return Err(syn::Error::new(ident.span(), msg)); + return Err(syn::Error::new(ident.span(), msg)) } Ok(GenesisConfigDef { index, genesis_config: ident.clone(), instances, gen_kind }) diff --git a/frame/support/procedural/src/pallet/parse/helper.rs b/frame/support/procedural/src/pallet/parse/helper.rs index 4043302437cac..f5a7dc233cacb 100644 --- a/frame/support/procedural/src/pallet/parse/helper.rs +++ b/frame/support/procedural/src/pallet/parse/helper.rs @@ -153,7 +153,7 @@ impl syn::parse::Parse for Unit { syn::parenthesized!(content in input); if !content.is_empty() { let msg = "unexpected tokens, expected nothing inside parenthesis as `()`"; - return Err(syn::Error::new(content.span(), msg)); + return Err(syn::Error::new(content.span(), msg)) } Ok(Self) } @@ -166,7 +166,7 @@ impl syn::parse::Parse for StaticLifetime { let lifetime = input.parse::()?; if lifetime.ident != "static" { let msg = "unexpected tokens, expected `static`"; - return Err(syn::Error::new(lifetime.ident.span(), msg)); + return Err(syn::Error::new(lifetime.ident.span(), msg)) } Ok(Self) } @@ -264,7 +264,7 @@ pub fn check_type_def_optional_gen( impl syn::parse::Parse for Checker { fn parse(input: syn::parse::ParseStream) -> syn::Result { if input.is_empty() { - return Ok(Self(None)); + return Ok(Self(None)) } let mut instance_usage = InstanceUsage { span: input.span(), has_instance: false }; @@ -272,7 +272,7 @@ pub fn check_type_def_optional_gen( input.parse::()?; if input.is_empty() { - return Ok(Self(Some(instance_usage))); + return Ok(Self(Some(instance_usage))) } let lookahead = input.lookahead1(); @@ -289,7 +289,7 @@ pub fn check_type_def_optional_gen( input.parse::()?; if input.is_empty() { - return Ok(Self(Some(instance_usage))); + return Ok(Self(Some(instance_usage))) } instance_usage.has_instance = true; @@ -431,7 +431,7 @@ pub fn check_type_def_gen( input.parse::()?; if input.is_empty() { - return Ok(Self(instance_usage)); + return Ok(Self(instance_usage)) } let lookahead = input.lookahead1(); @@ -448,7 +448,7 @@ pub fn check_type_def_gen( input.parse::()?; if input.is_empty() { - return Ok(Self(instance_usage)); + return Ok(Self(instance_usage)) } instance_usage.has_instance = true; @@ -539,7 +539,7 @@ pub fn check_type_value_gen( impl syn::parse::Parse for Checker { fn parse(input: syn::parse::ParseStream) -> syn::Result { if input.is_empty() { - return Ok(Self(None)); + return Ok(Self(None)) } input.parse::()?; @@ -549,7 +549,7 @@ pub fn check_type_value_gen( let mut instance_usage = InstanceUsage { span: input.span(), has_instance: false }; if input.is_empty() { - return Ok(Self(Some(instance_usage))); + return Ok(Self(Some(instance_usage))) } instance_usage.has_instance = true; diff --git a/frame/support/procedural/src/pallet/parse/hooks.rs b/frame/support/procedural/src/pallet/parse/hooks.rs index 0c9032d5dba65..1dd86498f22d5 100644 --- a/frame/support/procedural/src/pallet/parse/hooks.rs +++ b/frame/support/procedural/src/pallet/parse/hooks.rs @@ -42,7 +42,7 @@ impl HooksDef { item } else { let msg = "Invalid pallet::hooks, expected item impl"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) }; let mut instances = vec![]; @@ -66,7 +66,7 @@ impl HooksDef { quote::quote!(#item_trait) ); - return Err(syn::Error::new(item_trait.span(), msg)); + return Err(syn::Error::new(item_trait.span(), msg)) } let has_runtime_upgrade = item.items.iter().any(|i| match i { diff --git a/frame/support/procedural/src/pallet/parse/inherent.rs b/frame/support/procedural/src/pallet/parse/inherent.rs index 02415afb57737..de5ad8f795db5 100644 --- a/frame/support/procedural/src/pallet/parse/inherent.rs +++ b/frame/support/procedural/src/pallet/parse/inherent.rs @@ -32,22 +32,22 @@ impl InherentDef { item } else { let msg = "Invalid pallet::inherent, expected item impl"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) }; if item.trait_.is_none() { let msg = "Invalid pallet::inherent, expected impl<..> ProvideInherent for Pallet<..>"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) } if let Some(last) = item.trait_.as_ref().unwrap().1.segments.last() { if last.ident != "ProvideInherent" { let msg = "Invalid pallet::inherent, expected trait ProvideInherent"; - return Err(syn::Error::new(last.span(), msg)); + return Err(syn::Error::new(last.span(), msg)) } } else { let msg = "Invalid pallet::inherent, expected impl<..> ProvideInherent for Pallet<..>"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) } let mut instances = vec![]; diff --git a/frame/support/procedural/src/pallet/parse/mod.rs b/frame/support/procedural/src/pallet/parse/mod.rs index da6af5e78f65a..96d4776e805bc 100644 --- a/frame/support/procedural/src/pallet/parse/mod.rs +++ b/frame/support/procedural/src/pallet/parse/mod.rs @@ -95,58 +95,49 @@ impl Def { let pallet_attr: Option = helper::take_first_item_pallet_attr(item)?; match pallet_attr { - Some(PalletAttr::Config(span)) if config.is_none() => { - config = Some(config::ConfigDef::try_from(&frame_system, span, index, item)?) - } + Some(PalletAttr::Config(span)) if config.is_none() => + config = Some(config::ConfigDef::try_from(&frame_system, span, index, item)?), Some(PalletAttr::Pallet(span)) if pallet_struct.is_none() => { let p = pallet_struct::PalletStructDef::try_from(span, index, item)?; pallet_struct = Some(p); - } + }, Some(PalletAttr::Hooks(span)) if hooks.is_none() => { let m = hooks::HooksDef::try_from(span, index, item)?; hooks = Some(m); - } - Some(PalletAttr::Call(span)) if call.is_none() => { - call = Some(call::CallDef::try_from(span, index, item)?) - } - Some(PalletAttr::Error(span)) if error.is_none() => { - error = Some(error::ErrorDef::try_from(span, index, item)?) - } - Some(PalletAttr::Event(span)) if event.is_none() => { - event = Some(event::EventDef::try_from(span, index, item)?) - } + }, + Some(PalletAttr::Call(span)) if call.is_none() => + call = Some(call::CallDef::try_from(span, index, item)?), + Some(PalletAttr::Error(span)) if error.is_none() => + error = Some(error::ErrorDef::try_from(span, index, item)?), + Some(PalletAttr::Event(span)) if event.is_none() => + event = Some(event::EventDef::try_from(span, index, item)?), Some(PalletAttr::GenesisConfig(_)) if genesis_config.is_none() => { let g = genesis_config::GenesisConfigDef::try_from(index, item)?; genesis_config = Some(g); - } + }, Some(PalletAttr::GenesisBuild(span)) if genesis_build.is_none() => { let g = genesis_build::GenesisBuildDef::try_from(span, index, item)?; genesis_build = Some(g); - } - Some(PalletAttr::Origin(_)) if origin.is_none() => { - origin = Some(origin::OriginDef::try_from(index, item)?) - } - Some(PalletAttr::Inherent(_)) if inherent.is_none() => { - inherent = Some(inherent::InherentDef::try_from(index, item)?) - } - Some(PalletAttr::Storage(span)) => { - storages.push(storage::StorageDef::try_from(span, index, item)?) - } + }, + Some(PalletAttr::Origin(_)) if origin.is_none() => + origin = Some(origin::OriginDef::try_from(index, item)?), + Some(PalletAttr::Inherent(_)) if inherent.is_none() => + inherent = Some(inherent::InherentDef::try_from(index, item)?), + Some(PalletAttr::Storage(span)) => + storages.push(storage::StorageDef::try_from(span, index, item)?), Some(PalletAttr::ValidateUnsigned(_)) if validate_unsigned.is_none() => { let v = validate_unsigned::ValidateUnsignedDef::try_from(index, item)?; validate_unsigned = Some(v); - } - Some(PalletAttr::TypeValue(span)) => { - type_values.push(type_value::TypeValueDef::try_from(span, index, item)?) - } - Some(PalletAttr::ExtraConstants(_)) => { + }, + Some(PalletAttr::TypeValue(span)) => + type_values.push(type_value::TypeValueDef::try_from(span, index, item)?), + Some(PalletAttr::ExtraConstants(_)) => extra_constants = - Some(extra_constants::ExtraConstantsDef::try_from(index, item)?) - } + Some(extra_constants::ExtraConstantsDef::try_from(index, item)?), Some(attr) => { let msg = "Invalid duplicated attribute"; - return Err(syn::Error::new(attr.span(), msg)); - } + return Err(syn::Error::new(attr.span(), msg)) + }, None => (), } } @@ -159,7 +150,7 @@ impl Def { genesis_config.as_ref().map_or("unused", |_| "used"), genesis_build.as_ref().map_or("unused", |_| "used"), ); - return Err(syn::Error::new(item_span, msg)); + return Err(syn::Error::new(item_span, msg)) } let def = Def { @@ -199,13 +190,13 @@ impl Def { but enum `Event` is not declared (i.e. no use of `#[pallet::event]`). \ Note that type `Event` in trait is reserved to work alongside pallet event."; Err(syn::Error::new(proc_macro2::Span::call_site(), msg)) - } + }, (false, true) => { let msg = "Invalid usage of Event, `Config` contains no associated type \ `Event`, but enum `Event` is declared (in use of `#[pallet::event]`). \ An Event associated type must be declare on trait `Config`."; Err(syn::Error::new(proc_macro2::Span::call_site(), msg)) - } + }, _ => Ok(()), } } @@ -246,7 +237,7 @@ impl Def { let mut errors = instances.into_iter().filter_map(|instances| { if instances.has_instance == self.config.has_instance { - return None; + return None } let msg = if self.config.has_instance { "Invalid generic declaration, trait is defined with instance but generic use none" @@ -361,7 +352,7 @@ impl GenericKind { GenericKind::Config => quote::quote_spanned!(span => T: Config), GenericKind::ConfigAndInstance => { quote::quote_spanned!(span => T: Config, I: 'static) - } + }, } } diff --git a/frame/support/procedural/src/pallet/parse/origin.rs b/frame/support/procedural/src/pallet/parse/origin.rs index 1135da4dbdd5c..c4e1197ac511c 100644 --- a/frame/support/procedural/src/pallet/parse/origin.rs +++ b/frame/support/procedural/src/pallet/parse/origin.rs @@ -42,8 +42,8 @@ impl OriginDef { syn::Item::Type(item) => (&item.vis, &item.ident, &item.generics), _ => { let msg = "Invalid pallet::origin, expected enum or struct or type"; - return Err(syn::Error::new(item.span(), msg)); - } + return Err(syn::Error::new(item.span(), msg)) + }, }; let has_instance = generics.params.len() == 2; @@ -59,12 +59,12 @@ impl OriginDef { if !matches!(vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::origin, Origin must be public"; - return Err(syn::Error::new(item_span, msg)); + return Err(syn::Error::new(item_span, msg)) } if ident != "Origin" { let msg = "Invalid pallet::origin, ident must `Origin`"; - return Err(syn::Error::new(ident.span(), msg)); + return Err(syn::Error::new(ident.span(), msg)) } Ok(OriginDef { index, has_instance, is_generic, instances }) diff --git a/frame/support/procedural/src/pallet/parse/pallet_struct.rs b/frame/support/procedural/src/pallet/parse/pallet_struct.rs index 6a7e8de314096..278f46e13818e 100644 --- a/frame/support/procedural/src/pallet/parse/pallet_struct.rs +++ b/frame/support/procedural/src/pallet/parse/pallet_struct.rs @@ -113,7 +113,7 @@ impl PalletStructDef { item } else { let msg = "Invalid pallet::pallet, expected struct definition"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) }; let mut store = None; @@ -125,7 +125,7 @@ impl PalletStructDef { match attr { PalletStructAttr::GenerateStore { vis, keyword, .. } if store.is_none() => { store = Some((vis, keyword)); - } + }, PalletStructAttr::GenerateStorageInfoTrait(span) if generate_storage_info.is_none() => { @@ -138,8 +138,8 @@ impl PalletStructDef { } attr => { let msg = "Unexpected duplicated attribute"; - return Err(syn::Error::new(attr.span(), msg)); - } + return Err(syn::Error::new(attr.span(), msg)) + }, } } @@ -147,12 +147,12 @@ impl PalletStructDef { if !matches!(item.vis, syn::Visibility::Public(_)) { let msg = "Invalid pallet::pallet, Pallet must be public"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) } if item.generics.where_clause.is_some() { let msg = "Invalid pallet::pallet, where clause not supported on Pallet declaration"; - return Err(syn::Error::new(item.generics.where_clause.span(), msg)); + return Err(syn::Error::new(item.generics.where_clause.span(), msg)) } let mut instances = vec![]; diff --git a/frame/support/procedural/src/pallet/parse/storage.rs b/frame/support/procedural/src/pallet/parse/storage.rs index 0d67cc5da2af3..cd29baf93d849 100644 --- a/frame/support/procedural/src/pallet/parse/storage.rs +++ b/frame/support/procedural/src/pallet/parse/storage.rs @@ -103,16 +103,14 @@ impl PalletStorageAttrInfo { for attr in attrs { match attr { PalletStorageAttr::Getter(ident, ..) if getter.is_none() => getter = Some(ident), - PalletStorageAttr::StorageName(name, ..) if rename_as.is_none() => { - rename_as = Some(name) - } + PalletStorageAttr::StorageName(name, ..) if rename_as.is_none() => + rename_as = Some(name), PalletStorageAttr::Unbounded(..) if !unbounded => unbounded = true, - attr => { + attr => return Err(syn::Error::new( attr.attr_span(), "Invalid attribute: Duplicate attribute", - )) - } + )), } } @@ -224,9 +222,8 @@ impl StorageGenerics { Self::Map { value, key, .. } => Metadata::Map { value, key }, Self::CountedMap { value, key, .. } => Metadata::CountedMap { value, key }, Self::Value { value, .. } => Metadata::Value { value }, - Self::NMap { keygen, value, .. } => { - Metadata::NMap { keys: collect_keys(&keygen)?, keygen, value } - } + Self::NMap { keygen, value, .. } => + Metadata::NMap { keys: collect_keys(&keygen)?, keygen, value }, }; Ok(res) @@ -235,11 +232,11 @@ impl StorageGenerics { /// Return the query kind from the defined generics fn query_kind(&self) -> Option { match &self { - Self::DoubleMap { query_kind, .. } - | Self::Map { query_kind, .. } - | Self::CountedMap { query_kind, .. } - | Self::Value { query_kind, .. } - | Self::NMap { query_kind, .. } => query_kind.clone(), + Self::DoubleMap { query_kind, .. } | + Self::Map { query_kind, .. } | + Self::CountedMap { query_kind, .. } | + Self::Value { query_kind, .. } | + Self::NMap { query_kind, .. } => query_kind.clone(), } } } @@ -280,8 +277,8 @@ fn check_generics( }; for (gen_name, gen_binding) in map { - if !mandatory_generics.contains(&gen_name.as_str()) - && !optional_generics.contains(&gen_name.as_str()) + if !mandatory_generics.contains(&gen_name.as_str()) && + !optional_generics.contains(&gen_name.as_str()) { let msg = format!( "Invalid pallet::storage, Unexpected generic `{}` for `{}`. {}", @@ -326,7 +323,7 @@ fn process_named_generics( let msg = "Invalid pallet::storage, Duplicated named generic"; let mut err = syn::Error::new(arg.ident.span(), msg); err.combine(syn::Error::new(other.ident.span(), msg)); - return Err(err); + return Err(err) } parsed.insert(arg.ident.to_string(), arg.clone()); } @@ -349,7 +346,7 @@ fn process_named_generics( query_kind: parsed.remove("QueryKind").map(|binding| binding.ty), on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), } - } + }, StorageKind::Map => { check_generics( &parsed, @@ -376,7 +373,7 @@ fn process_named_generics( on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), max_values: parsed.remove("MaxValues").map(|binding| binding.ty), } - } + }, StorageKind::CountedMap => { check_generics( &parsed, @@ -403,7 +400,7 @@ fn process_named_generics( on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), max_values: parsed.remove("MaxValues").map(|binding| binding.ty), } - } + }, StorageKind::DoubleMap => { check_generics( &parsed, @@ -438,7 +435,7 @@ fn process_named_generics( on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), max_values: parsed.remove("MaxValues").map(|binding| binding.ty), } - } + }, StorageKind::NMap => { check_generics( &parsed, @@ -461,7 +458,7 @@ fn process_named_generics( on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty), max_values: parsed.remove("MaxValues").map(|binding| binding.ty), } - } + }, }; let metadata = generics.metadata()?; @@ -498,9 +495,8 @@ fn process_unnamed_generics( })?; let res = match storage { - StorageKind::Value => { - (None, Metadata::Value { value: retrieve_arg(1)? }, retrieve_arg(2).ok()) - } + StorageKind::Value => + (None, Metadata::Value { value: retrieve_arg(1)? }, retrieve_arg(2).ok()), StorageKind::Map => ( None, Metadata::Map { key: retrieve_arg(2)?, value: retrieve_arg(3)? }, @@ -524,7 +520,7 @@ fn process_unnamed_generics( let keygen = retrieve_arg(1)?; let keys = collect_keys(&keygen)?; (None, Metadata::NMap { keys, keygen, value: retrieve_arg(2)? }, retrieve_arg(3).ok()) - } + }, }; Ok(res) @@ -547,8 +543,8 @@ fn process_generics( found `{}`.", found, ); - return Err(syn::Error::new(segment.ident.span(), msg)); - } + return Err(syn::Error::new(segment.ident.span(), msg)) + }, }; let args_span = segment.arguments.span(); @@ -558,8 +554,8 @@ fn process_generics( _ => { let msg = "Invalid pallet::storage, invalid number of generic generic arguments, \ expect more that 0 generic arguments."; - return Err(syn::Error::new(segment.span(), msg)); - } + return Err(syn::Error::new(segment.span(), msg)) + }, }; if args.args.iter().all(|gen| matches!(gen, syn::GenericArgument::Type(_))) { @@ -605,7 +601,7 @@ fn extract_key(ty: &syn::Type) -> syn::Result { typ } else { let msg = "Invalid pallet::storage, expected type path"; - return Err(syn::Error::new(ty.span(), msg)); + return Err(syn::Error::new(ty.span(), msg)) }; let key_struct = typ.path.segments.last().ok_or_else(|| { @@ -614,14 +610,14 @@ fn extract_key(ty: &syn::Type) -> syn::Result { })?; if key_struct.ident != "Key" && key_struct.ident != "NMapKey" { let msg = "Invalid pallet::storage, expected Key or NMapKey struct"; - return Err(syn::Error::new(key_struct.ident.span(), msg)); + return Err(syn::Error::new(key_struct.ident.span(), msg)) } let ty_params = if let syn::PathArguments::AngleBracketed(args) = &key_struct.arguments { args } else { let msg = "Invalid pallet::storage, expected angle bracketed arguments"; - return Err(syn::Error::new(key_struct.arguments.span(), msg)); + return Err(syn::Error::new(key_struct.arguments.span(), msg)) }; if ty_params.args.len() != 2 { @@ -630,15 +626,15 @@ fn extract_key(ty: &syn::Type) -> syn::Result { for Key struct, expected 2 args, found {}", ty_params.args.len() ); - return Err(syn::Error::new(ty_params.span(), msg)); + return Err(syn::Error::new(ty_params.span(), msg)) } let key = match &ty_params.args[1] { syn::GenericArgument::Type(key_ty) => key_ty.clone(), _ => { let msg = "Invalid pallet::storage, expected type"; - return Err(syn::Error::new(ty_params.args[1].span(), msg)); - } + return Err(syn::Error::new(ty_params.args[1].span(), msg)) + }, }; Ok(key) @@ -667,7 +663,7 @@ impl StorageDef { let item = if let syn::Item::Type(item) = item { item } else { - return Err(syn::Error::new(item.span(), "Invalid pallet::storage, expect item type.")); + return Err(syn::Error::new(item.span(), "Invalid pallet::storage, expect item type.")) }; let attrs: Vec = helper::take_item_pallet_attrs(&mut item.attrs)?; @@ -686,12 +682,12 @@ impl StorageDef { typ } else { let msg = "Invalid pallet::storage, expected type path"; - return Err(syn::Error::new(item.ty.span(), msg)); + return Err(syn::Error::new(item.ty.span(), msg)) }; if typ.path.segments.len() != 1 { let msg = "Invalid pallet::storage, expected type path with one segment"; - return Err(syn::Error::new(item.ty.span(), msg)); + return Err(syn::Error::new(item.ty.span(), msg)) } let (named_generics, metadata, query_kind) = process_generics(&typ.path.segments[0])?; @@ -700,14 +696,10 @@ impl StorageDef { .map(|query_kind| match query_kind { syn::Type::Path(path) if path.path.segments.last().map_or(false, |s| s.ident == "OptionQuery") => - { - Some(QueryKind::OptionQuery) - } + Some(QueryKind::OptionQuery), syn::Type::Path(path) if path.path.segments.last().map_or(false, |s| s.ident == "ValueQuery") => - { - Some(QueryKind::ValueQuery) - } + Some(QueryKind::ValueQuery), _ => None, }) .unwrap_or(Some(QueryKind::OptionQuery)); // This value must match the default generic. @@ -716,7 +708,7 @@ impl StorageDef { let msg = "Invalid pallet::storage, cannot generate getter because QueryKind is not \ identifiable. QueryKind must be `OptionQuery`, `ValueQuery`, or default one to be \ identifiable."; - return Err(syn::Error::new(getter.unwrap().span(), msg)); + return Err(syn::Error::new(getter.unwrap().span(), msg)) } Ok(StorageDef { diff --git a/frame/support/procedural/src/pallet/parse/type_value.rs b/frame/support/procedural/src/pallet/parse/type_value.rs index 1d575abf22b42..7b9d57472db4b 100644 --- a/frame/support/procedural/src/pallet/parse/type_value.rs +++ b/frame/support/procedural/src/pallet/parse/type_value.rs @@ -50,12 +50,12 @@ impl TypeValueDef { item } else { let msg = "Invalid pallet::type_value, expected item fn"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) }; if !item.attrs.is_empty() { let msg = "Invalid pallet::type_value, unexpected attribute"; - return Err(syn::Error::new(item.attrs[0].span(), msg)); + return Err(syn::Error::new(item.attrs[0].span(), msg)) } if let Some(span) = item @@ -69,12 +69,12 @@ impl TypeValueDef { .or_else(|| item.sig.variadic.as_ref().map(|t| t.span())) { let msg = "Invalid pallet::type_value, unexpected token"; - return Err(syn::Error::new(span, msg)); + return Err(syn::Error::new(span, msg)) } if !item.sig.inputs.is_empty() { let msg = "Invalid pallet::type_value, unexpected argument"; - return Err(syn::Error::new(item.sig.inputs[0].span(), msg)); + return Err(syn::Error::new(item.sig.inputs[0].span(), msg)) } let vis = item.vis.clone(); @@ -84,8 +84,8 @@ impl TypeValueDef { syn::ReturnType::Type(_, type_) => type_, syn::ReturnType::Default => { let msg = "Invalid pallet::type_value, expected return type"; - return Err(syn::Error::new(item.sig.span(), msg)); - } + return Err(syn::Error::new(item.sig.span(), msg)) + }, }; let mut instances = vec![]; diff --git a/frame/support/procedural/src/pallet/parse/validate_unsigned.rs b/frame/support/procedural/src/pallet/parse/validate_unsigned.rs index a376bb962e96c..87e2a326f1862 100644 --- a/frame/support/procedural/src/pallet/parse/validate_unsigned.rs +++ b/frame/support/procedural/src/pallet/parse/validate_unsigned.rs @@ -32,24 +32,24 @@ impl ValidateUnsignedDef { item } else { let msg = "Invalid pallet::validate_unsigned, expected item impl"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) }; if item.trait_.is_none() { let msg = "Invalid pallet::validate_unsigned, expected impl<..> ValidateUnsigned for \ Pallet<..>"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) } if let Some(last) = item.trait_.as_ref().unwrap().1.segments.last() { if last.ident != "ValidateUnsigned" { let msg = "Invalid pallet::validate_unsigned, expected trait ValidateUnsigned"; - return Err(syn::Error::new(last.span(), msg)); + return Err(syn::Error::new(last.span(), msg)) } } else { let msg = "Invalid pallet::validate_unsigned, expected impl<..> ValidateUnsigned for \ Pallet<..>"; - return Err(syn::Error::new(item.span(), msg)); + return Err(syn::Error::new(item.span(), msg)) } let mut instances = vec![]; diff --git a/frame/support/procedural/src/partial_eq_no_bound.rs b/frame/support/procedural/src/partial_eq_no_bound.rs index 325c8890032d0..3dbabf3f5d39a 100644 --- a/frame/support/procedural/src/partial_eq_no_bound.rs +++ b/frame/support/procedural/src/partial_eq_no_bound.rs @@ -37,7 +37,7 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: .map(|i| quote::quote_spanned!(i.span() => self.#i == other.#i )); quote::quote!( true #( && #fields )* ) - } + }, syn::Fields::Unnamed(unnamed) => { let fields = unnamed .unnamed @@ -47,10 +47,10 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: .map(|i| quote::quote_spanned!(i.span() => self.#i == other.#i )); quote::quote!( true #( && #fields )* ) - } + }, syn::Fields::Unit => { quote::quote!(true) - } + }, }, syn::Data::Enum(enum_) => { let variants = @@ -77,7 +77,7 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: Self::#ident { #( #other_capture, )* }, ) => true #( && #eq )* ) - } + }, syn::Fields::Unnamed(unnamed) => { let names = unnamed .unnamed @@ -97,7 +97,7 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: Self::#ident ( #( #other_names, )* ), ) => true #( && #eq )* ) - } + }, syn::Fields::Unit => quote::quote!( (Self::#ident, Self::#ident) => true ), } }); @@ -119,11 +119,11 @@ pub fn derive_partial_eq_no_bound(input: proc_macro::TokenStream) -> proc_macro: #( #variants, )* #( #different_variants, )* }) - } + }, syn::Data::Union(_) => { let msg = "Union type not supported by `derive(PartialEqNoBound)`"; - return syn::Error::new(input.span(), msg).to_compile_error().into(); - } + return syn::Error::new(input.span(), msg).to_compile_error().into() + }, }; quote::quote!( diff --git a/frame/support/procedural/src/storage/genesis_config/builder_def.rs b/frame/support/procedural/src/storage/genesis_config/builder_def.rs index 31e98f16347d8..001cea0f2b788 100644 --- a/frame/support/procedural/src/storage/genesis_config/builder_def.rs +++ b/frame/support/procedural/src/storage/genesis_config/builder_def.rs @@ -60,7 +60,7 @@ impl BuilderDef { let data = builder(self); let data = Option::as_ref(&data); ) - } + }, _ => quote_spanned!(builder.span() => // NOTE: the type of `data` is specified when used later in the code let builder: fn(&Self) -> _ = #builder; @@ -73,7 +73,7 @@ impl BuilderDef { data = Some(match &line.storage_type { StorageLineTypeDef::Simple(_) if line.is_option => { quote!( let data = Some(&self.#config); ) - } + }, _ => quote!( let data = &self.#config; ), }); }; @@ -88,14 +88,14 @@ impl BuilderDef { <#storage_struct as #scrate::#storage_trait>::put::<&#value_type>(v); } }} - } + }, StorageLineTypeDef::Simple(_) if !line.is_option => { quote! {{ #data let v: &#value_type = data; <#storage_struct as #scrate::#storage_trait>::put::<&#value_type>(v); }} - } + }, StorageLineTypeDef::Simple(_) => unreachable!(), StorageLineTypeDef::Map(map) => { let key = &map.key; @@ -108,7 +108,7 @@ impl BuilderDef { >(k, v); }); }} - } + }, StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; @@ -121,7 +121,7 @@ impl BuilderDef { >(k1, k2, v); }); }} - } + }, StorageLineTypeDef::NMap(map) => { let key_tuple = map.to_key_tuple(); let key_arg = if map.keys.len() == 1 { quote!((k,)) } else { quote!(k) }; @@ -132,7 +132,7 @@ impl BuilderDef { <#storage_struct as #scrate::#storage_trait>::insert(#key_arg, v); }); }} - } + }, }); } } diff --git a/frame/support/procedural/src/storage/genesis_config/genesis_config_def.rs b/frame/support/procedural/src/storage/genesis_config/genesis_config_def.rs index 478da660f2316..fbdaab06b4895 100644 --- a/frame/support/procedural/src/storage/genesis_config/genesis_config_def.rs +++ b/frame/support/procedural/src/storage/genesis_config/genesis_config_def.rs @@ -95,17 +95,17 @@ impl GenesisConfigDef { StorageLineTypeDef::Map(map) => { let key = &map.key; parse_quote!( Vec<(#key, #value_type)> ) - } + }, StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; parse_quote!( Vec<(#key1, #key2, #value_type)> ) - } + }, StorageLineTypeDef::NMap(map) => { let key_tuple = map.to_key_tuple(); parse_quote!( Vec<(#key_tuple, #value_type)> ) - } + }, }; let default = @@ -138,7 +138,7 @@ impl GenesisConfigDef { return Err(syn::Error::new( meta.span(), "extra genesis config items do not support `cfg` attribute", - )); + )) } Ok(meta) }) diff --git a/frame/support/procedural/src/storage/getters.rs b/frame/support/procedural/src/storage/getters.rs index cf33165bbcee0..988e6fa096243 100644 --- a/frame/support/procedural/src/storage/getters.rs +++ b/frame/support/procedural/src/storage/getters.rs @@ -43,7 +43,7 @@ pub fn impl_getters(def: &DeclStorageDefExt) -> TokenStream { <#storage_struct as #scrate::#storage_trait>::get() } } - } + }, StorageLineTypeDef::Map(map) => { let key = &map.key; let value = &map.value; @@ -53,7 +53,7 @@ pub fn impl_getters(def: &DeclStorageDefExt) -> TokenStream { <#storage_struct as #scrate::#storage_trait>::get(key) } } - } + }, StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; @@ -67,7 +67,7 @@ pub fn impl_getters(def: &DeclStorageDefExt) -> TokenStream { <#storage_struct as #scrate::#storage_trait>::get(k1, k2) } } - } + }, StorageLineTypeDef::NMap(map) => { let keygen = map.to_keygen_struct(&def.hidden_crate); let value = &map.value; @@ -82,7 +82,7 @@ pub fn impl_getters(def: &DeclStorageDefExt) -> TokenStream { <#storage_struct as #scrate::#storage_trait>::get(key) } } - } + }, }; getters.extend(getter); } diff --git a/frame/support/procedural/src/storage/metadata.rs b/frame/support/procedural/src/storage/metadata.rs index e685d3d095ffc..a90e5051c5b2e 100644 --- a/frame/support/procedural/src/storage/metadata.rs +++ b/frame/support/procedural/src/storage/metadata.rs @@ -31,7 +31,7 @@ fn storage_line_metadata_type(scrate: &TokenStream, line: &StorageLineDefExt) -> #scrate::scale_info::meta_type::<#value_type>() ) } - } + }, StorageLineTypeDef::Map(map) => { let hasher = map.hasher.into_metadata(); let key = &map.key; @@ -42,7 +42,7 @@ fn storage_line_metadata_type(scrate: &TokenStream, line: &StorageLineDefExt) -> value: #scrate::scale_info::meta_type::<#value_type>(), } } - } + }, StorageLineTypeDef::DoubleMap(map) => { let hasher1 = map.hasher1.into_metadata(); let hasher2 = map.hasher2.into_metadata(); @@ -58,7 +58,7 @@ fn storage_line_metadata_type(scrate: &TokenStream, line: &StorageLineDefExt) -> value: #scrate::scale_info::meta_type::<#value_type>(), } } - } + }, StorageLineTypeDef::NMap(map) => { let key_tuple = &map.to_key_tuple(); let hashers = map @@ -75,7 +75,7 @@ fn storage_line_metadata_type(scrate: &TokenStream, line: &StorageLineDefExt) -> value: #scrate::scale_info::meta_type::<#value_type>(), } } - } + }, } } diff --git a/frame/support/procedural/src/storage/mod.rs b/frame/support/procedural/src/storage/mod.rs index 5d5b19b195a18..27964d7012a28 100644 --- a/frame/support/procedural/src/storage/mod.rs +++ b/frame/support/procedural/src/storage/mod.rs @@ -258,24 +258,20 @@ impl StorageLineDefExt { hidden_crate: &proc_macro2::TokenStream, ) -> Self { let is_generic = match &storage_def.storage_type { - StorageLineTypeDef::Simple(value) => { - ext::type_contains_ident(&value, &def.module_runtime_generic) - } - StorageLineTypeDef::Map(map) => { - ext::type_contains_ident(&map.key, &def.module_runtime_generic) - || ext::type_contains_ident(&map.value, &def.module_runtime_generic) - } - StorageLineTypeDef::DoubleMap(map) => { - ext::type_contains_ident(&map.key1, &def.module_runtime_generic) - || ext::type_contains_ident(&map.key2, &def.module_runtime_generic) - || ext::type_contains_ident(&map.value, &def.module_runtime_generic) - } - StorageLineTypeDef::NMap(map) => { + StorageLineTypeDef::Simple(value) => + ext::type_contains_ident(&value, &def.module_runtime_generic), + StorageLineTypeDef::Map(map) => + ext::type_contains_ident(&map.key, &def.module_runtime_generic) || + ext::type_contains_ident(&map.value, &def.module_runtime_generic), + StorageLineTypeDef::DoubleMap(map) => + ext::type_contains_ident(&map.key1, &def.module_runtime_generic) || + ext::type_contains_ident(&map.key2, &def.module_runtime_generic) || + ext::type_contains_ident(&map.value, &def.module_runtime_generic), + StorageLineTypeDef::NMap(map) => map.keys .iter() - .any(|key| ext::type_contains_ident(key, &def.module_runtime_generic)) - || ext::type_contains_ident(&map.value, &def.module_runtime_generic) - } + .any(|key| ext::type_contains_ident(key, &def.module_runtime_generic)) || + ext::type_contains_ident(&map.value, &def.module_runtime_generic), }; let query_type = match &storage_def.storage_type { @@ -313,20 +309,20 @@ impl StorageLineDefExt { let storage_trait_truncated = match &storage_def.storage_type { StorageLineTypeDef::Simple(_) => { quote!( StorageValue<#value_type> ) - } + }, StorageLineTypeDef::Map(map) => { let key = &map.key; quote!( StorageMap<#key, #value_type> ) - } + }, StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; quote!( StorageDoubleMap<#key1, #key2, #value_type> ) - } + }, StorageLineTypeDef::NMap(map) => { let keygen = map.to_keygen_struct(hidden_crate); quote!( StorageNMap<#keygen, #value_type> ) - } + }, }; let storage_trait = quote!( storage::#storage_trait_truncated ); @@ -398,7 +394,7 @@ impl NMapDef { if self.keys.len() == 1 { let hasher = &self.hashers[0].to_storage_hasher_struct(); let key = &self.keys[0]; - return quote!( #scrate::storage::types::Key<#scrate::#hasher, #key> ); + return quote!( #scrate::storage::types::Key<#scrate::#hasher, #key> ) } let key_hasher = self @@ -416,7 +412,7 @@ impl NMapDef { fn to_key_tuple(&self) -> proc_macro2::TokenStream { if self.keys.len() == 1 { let key = &self.keys[0]; - return quote!(#key); + return quote!(#key) } let tuple = self.keys.iter().map(|key| quote!(#key)).collect::>(); diff --git a/frame/support/procedural/src/storage/parse.rs b/frame/support/procedural/src/storage/parse.rs index cad5bfec25de1..3a11846181a8f 100644 --- a/frame/support/procedural/src/storage/parse.rs +++ b/frame/support/procedural/src/storage/parse.rs @@ -367,17 +367,16 @@ fn get_module_instance( it is now defined at frame_support::traits::Instance. Expect `Instance` found `{}`", instantiable.as_ref().unwrap(), ); - return Err(syn::Error::new(instantiable.span(), msg)); + return Err(syn::Error::new(instantiable.span(), msg)) } match (instance, instantiable, default_instance) { - (Some(instance), Some(instantiable), default_instance) => { + (Some(instance), Some(instantiable), default_instance) => Ok(Some(super::ModuleInstanceDef { instance_generic: instance, instance_trait: instantiable, instance_default: default_instance, - })) - } + })), (None, None, None) => Ok(None), (Some(instance), None, _) => Err(syn::Error::new( instance.span(), @@ -425,17 +424,17 @@ pub fn parse(input: syn::parse::ParseStream) -> syn::Result { if extra_genesis_build.is_some() { return Err(syn::Error::new( def.span(), "Only one build expression allowed for extra genesis", - )); + )) } extra_genesis_build = Some(def.expr.content); - } + }, } } @@ -477,7 +476,7 @@ fn parse_storage_line_defs( "Invalid storage definition, couldn't find config identifier: storage must \ either have a get identifier `get(fn ident)` or a defined config identifier \ `config(ident)`", - )); + )) } } else { None @@ -499,18 +498,16 @@ fn parse_storage_line_defs( } let max_values = match &line.storage_type { - DeclStorageType::Map(_) | DeclStorageType::DoubleMap(_) | DeclStorageType::NMap(_) => { - line.max_values.inner.map(|i| i.expr.content) - } - DeclStorageType::Simple(_) => { + DeclStorageType::Map(_) | DeclStorageType::DoubleMap(_) | DeclStorageType::NMap(_) => + line.max_values.inner.map(|i| i.expr.content), + DeclStorageType::Simple(_) => if let Some(max_values) = line.max_values.inner { let msg = "unexpected max_values attribute for storage value."; let span = max_values.max_values_keyword.span(); - return Err(syn::Error::new(span, msg)); + return Err(syn::Error::new(span, msg)) } else { Some(syn::parse_quote!(1u32)) - } - } + }, }; let span = line.storage_type.span(); @@ -527,15 +524,14 @@ fn parse_storage_line_defs( key: map.key, value: map.value, }), - DeclStorageType::DoubleMap(map) => { + DeclStorageType::DoubleMap(map) => super::StorageLineTypeDef::DoubleMap(Box::new(super::DoubleMapDef { hasher1: map.hasher1.inner.ok_or_else(no_hasher_error)?.into(), hasher2: map.hasher2.inner.ok_or_else(no_hasher_error)?.into(), key1: map.key1, key2: map.key2, value: map.value, - })) - } + })), DeclStorageType::NMap(map) => super::StorageLineTypeDef::NMap(super::NMapDef { hashers: map .storage_keys diff --git a/frame/support/procedural/src/storage/print_pallet_upgrade.rs b/frame/support/procedural/src/storage/print_pallet_upgrade.rs index 3361b65f96516..03f09a7edb48e 100644 --- a/frame/support/procedural/src/storage/print_pallet_upgrade.rs +++ b/frame/support/procedural/src/storage/print_pallet_upgrade.rs @@ -26,7 +26,7 @@ fn to_cleaned_string(t: impl quote::ToTokens) -> String { /// Print an incomplete upgrade from decl_storage macro to new pallet attribute. pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { if !check_print_pallet_upgrade() { - return; + return } let scrate = "e::quote!(frame_support); @@ -58,8 +58,8 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { Ok(g) => g, Err(err) => { println!("Could not print upgrade due compile error: {:?}", err); - return; - } + return + }, }; let genesis_config_impl_gen = @@ -216,7 +216,7 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { comma_query_kind = comma_query_kind, comma_default_value_getter_name = comma_default_value_getter_name, ) - } + }, StorageLineTypeDef::DoubleMap(double_map) => { format!( "StorageDoubleMap<_, {hasher1}, {key1}, {hasher2}, {key2}, {value_type}\ @@ -229,7 +229,7 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { comma_query_kind = comma_query_kind, comma_default_value_getter_name = comma_default_value_getter_name, ) - } + }, StorageLineTypeDef::NMap(map) => { format!( "StorageNMap<_, {keygen}, {value_type}{comma_query_kind}\ @@ -239,7 +239,7 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { comma_query_kind = comma_query_kind, comma_default_value_getter_name = comma_default_value_getter_name, ) - } + }, StorageLineTypeDef::Simple(_) => { format!( "StorageValue<_, {value_type}{comma_query_kind}\ @@ -248,7 +248,7 @@ pub fn maybe_print_pallet_upgrade(def: &super::DeclStorageDefExt) { comma_query_kind = comma_query_kind, comma_default_value_getter_name = comma_default_value_getter_name, ) - } + }, }; let additional_comment = if line.is_option && line.default_value.is_some() { diff --git a/frame/support/procedural/src/storage/storage_struct.rs b/frame/support/procedural/src/storage/storage_struct.rs index 83d4a8ce55283..b318225681c1d 100644 --- a/frame/support/procedural/src/storage/storage_struct.rs +++ b/frame/support/procedural/src/storage/storage_struct.rs @@ -120,7 +120,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, StorageLineTypeDef::Map(map) => { let hasher = map.hasher.to_storage_hasher_struct(); quote!( @@ -159,7 +159,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, StorageLineTypeDef::DoubleMap(map) => { let hasher1 = map.hasher1.to_storage_hasher_struct(); let hasher2 = map.hasher2.to_storage_hasher_struct(); @@ -202,7 +202,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, StorageLineTypeDef::NMap(_) => { quote!( impl<#impl_trait> #scrate::storage::StoragePrefixedMap<#value_type> @@ -239,7 +239,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, }; let max_values = if let Some(max_values) = &line.max_values { @@ -286,7 +286,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, StorageLineTypeDef::Map(map) => { let key = &map.key; quote!( @@ -330,7 +330,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, StorageLineTypeDef::DoubleMap(map) => { let key1 = &map.key1; let key2 = &map.key2; @@ -380,7 +380,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, StorageLineTypeDef::NMap(map) => { let key = &map.to_keygen_struct(scrate); quote!( @@ -423,7 +423,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, } } else { // Implement `__partial_storage_info` which doesn't require MaxEncodedLen on keys and @@ -456,7 +456,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, StorageLineTypeDef::Map(_) => { quote!( impl<#impl_trait> #scrate::traits::PartialStorageInfoTrait @@ -487,7 +487,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, StorageLineTypeDef::DoubleMap(_) => { quote!( impl<#impl_trait> #scrate::traits::PartialStorageInfoTrait @@ -518,7 +518,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, StorageLineTypeDef::NMap(_) => { quote!( impl<#impl_trait> #scrate::traits::PartialStorageInfoTrait @@ -549,7 +549,7 @@ pub fn decl_and_impl(def: &DeclStorageDefExt) -> TokenStream { } } ) - } + }, } }; diff --git a/frame/support/procedural/tools/src/lib.rs b/frame/support/procedural/tools/src/lib.rs index 98e44a7dbe4a8..d7aba4c7cbf1c 100644 --- a/frame/support/procedural/tools/src/lib.rs +++ b/frame/support/procedural/tools/src/lib.rs @@ -54,7 +54,7 @@ pub fn generate_crate_access_2018(def_crate: &str) -> Result Ok(FoundCrate::Itself) => { let name = def_crate.to_string().replace("-", "_"); Ok(syn::Ident::new(&name, Span::call_site())) - } + }, Ok(FoundCrate::Name(name)) => Ok(Ident::new(&name, Span::call_site())), Err(e) => Err(Error::new(Span::call_site(), e)), } @@ -74,11 +74,11 @@ pub fn generate_hidden_includes(unique_id: &str, def_crate: &str) -> TokenStream pub extern crate #name as hidden_include; } ) - } + }, Err(e) => { let err = Error::new(Span::call_site(), e).to_compile_error(); quote!( #err ) - } + }, } } diff --git a/frame/support/procedural/tools/src/syn_ext.rs b/frame/support/procedural/tools/src/syn_ext.rs index b5c9c549f4811..a9e9ef573985f 100644 --- a/frame/support/procedural/tools/src/syn_ext.rs +++ b/frame/support/procedural/tools/src/syn_ext.rs @@ -170,7 +170,7 @@ pub fn extract_type_option(typ: &syn::Type) -> Option { // Option has only one type argument in angle bracket. if let syn::PathArguments::AngleBracketed(a) = &v.arguments { if let syn::GenericArgument::Type(typ) = a.args.last()? { - return Some(typ.clone()); + return Some(typ.clone()) } } } @@ -190,7 +190,7 @@ impl<'ast> ContainsIdent<'ast> { stream.into_iter().for_each(|tt| match tt { TokenTree::Ident(id) => self.visit_ident(&id), TokenTree::Group(ref group) => self.visit_tokenstream(group.stream()), - _ => {} + _ => {}, }) } diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 99fa190d4b11d..a492bc12f6a38 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -2648,7 +2648,7 @@ mod tests { fn index() -> Option { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { - return Some(0); + return Some(0) } None @@ -2656,7 +2656,7 @@ mod tests { fn name() -> Option<&'static str> { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { - return Some("Test"); + return Some("Test") } None @@ -2664,7 +2664,7 @@ mod tests { fn module_name() -> Option<&'static str> { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { - return Some("tests"); + return Some("tests") } None @@ -2672,7 +2672,7 @@ mod tests { fn crate_version() -> Option { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { - return Some(frame_support::crate_to_crate_version!()); + return Some(frame_support::crate_to_crate_version!()) } None diff --git a/frame/support/src/hash.rs b/frame/support/src/hash.rs index 2da6344145cee..f943bcf323090 100644 --- a/frame/support/src/hash.rs +++ b/frame/support/src/hash.rs @@ -111,7 +111,7 @@ impl ReversibleStorageHasher for Twox64Concat { fn reverse(x: &[u8]) -> &[u8] { if x.len() < 8 { log::error!("Invalid reverse: hash length too short"); - return &[]; + return &[] } &x[8..] } @@ -133,7 +133,7 @@ impl ReversibleStorageHasher for Blake2_128Concat { fn reverse(x: &[u8]) -> &[u8] { if x.len() < 16 { log::error!("Invalid reverse: hash length too short"); - return &[]; + return &[] } &x[16..] } diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 34ce21c952eaa..1b93b5fb5975e 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -723,7 +723,7 @@ pub use frame_support_procedural::crate_to_crate_version; #[macro_export] macro_rules! fail { ( $y:expr ) => {{ - return Err($y.into()); + return Err($y.into()) }}; } diff --git a/frame/support/src/storage/bounded_btree_map.rs b/frame/support/src/storage/bounded_btree_map.rs index 4e43d36e1f042..404814cb81693 100644 --- a/frame/support/src/storage/bounded_btree_map.rs +++ b/frame/support/src/storage/bounded_btree_map.rs @@ -44,7 +44,7 @@ where fn decode(input: &mut I) -> Result { let inner = BTreeMap::::decode(input)?; if inner.len() > S::get() as usize { - return Err("BoundedBTreeMap exceeds its limit".into()); + return Err("BoundedBTreeMap exceeds its limit".into()) } Ok(Self(inner, PhantomData)) } diff --git a/frame/support/src/storage/bounded_btree_set.rs b/frame/support/src/storage/bounded_btree_set.rs index 1353c437e9fa7..ecfb0bdbd261f 100644 --- a/frame/support/src/storage/bounded_btree_set.rs +++ b/frame/support/src/storage/bounded_btree_set.rs @@ -43,7 +43,7 @@ where fn decode(input: &mut I) -> Result { let inner = BTreeSet::::decode(input)?; if inner.len() > S::get() as usize { - return Err("BoundedBTreeSet exceeds its limit".into()); + return Err("BoundedBTreeSet exceeds its limit".into()) } Ok(Self(inner, PhantomData)) } diff --git a/frame/support/src/storage/bounded_vec.rs b/frame/support/src/storage/bounded_vec.rs index 8e73a90b9718d..e51c6cd734113 100644 --- a/frame/support/src/storage/bounded_vec.rs +++ b/frame/support/src/storage/bounded_vec.rs @@ -78,7 +78,7 @@ impl> Decode for BoundedVec { fn decode(input: &mut I) -> Result { let inner = Vec::::decode(input)?; if inner.len() > S::get() as usize { - return Err("BoundedVec exceeds its limit".into()); + return Err("BoundedVec exceeds its limit".into()) } Ok(Self(inner, PhantomData)) } diff --git a/frame/support/src/storage/child.rs b/frame/support/src/storage/child.rs index 0b6dc2dc0d740..4b237aaa561fd 100644 --- a/frame/support/src/storage/child.rs +++ b/frame/support/src/storage/child.rs @@ -42,7 +42,7 @@ pub fn get(child_info: &ChildInfo, key: &[u8]) -> Option { None }) }) - } + }, } } @@ -111,10 +111,9 @@ pub fn take_or_else T>( /// Check to see if `key` has an explicit entry in storage. pub fn exists(child_info: &ChildInfo, key: &[u8]) -> bool { match child_info.child_type() { - ChildType::ParentKeyId => { + ChildType::ParentKeyId => sp_io::default_child_storage::read(child_info.storage_key(), key, &mut [0; 0][..], 0) - .is_some() - } + .is_some(), } } @@ -139,9 +138,8 @@ pub fn exists(child_info: &ChildInfo, key: &[u8]) -> bool { /// blocks. pub fn kill_storage(child_info: &ChildInfo, limit: Option) -> KillStorageResult { match child_info.child_type() { - ChildType::ParentKeyId => { - sp_io::default_child_storage::storage_kill(child_info.storage_key(), limit) - } + ChildType::ParentKeyId => + sp_io::default_child_storage::storage_kill(child_info.storage_key(), limit), } } @@ -150,7 +148,7 @@ pub fn kill(child_info: &ChildInfo, key: &[u8]) { match child_info.child_type() { ChildType::ParentKeyId => { sp_io::default_child_storage::clear(child_info.storage_key(), key); - } + }, } } @@ -164,9 +162,8 @@ pub fn get_raw(child_info: &ChildInfo, key: &[u8]) -> Option> { /// Put a raw byte slice into storage. pub fn put_raw(child_info: &ChildInfo, key: &[u8], value: &[u8]) { match child_info.child_type() { - ChildType::ParentKeyId => { - sp_io::default_child_storage::set(child_info.storage_key(), key, value) - } + ChildType::ParentKeyId => + sp_io::default_child_storage::set(child_info.storage_key(), key, value), } } @@ -183,6 +180,6 @@ pub fn len(child_info: &ChildInfo, key: &[u8]) -> Option { ChildType::ParentKeyId => { let mut buffer = [0; 0]; sp_io::default_child_storage::read(child_info.storage_key(), key, &mut buffer, 0) - } + }, } } diff --git a/frame/support/src/storage/generator/double_map.rs b/frame/support/src/storage/generator/double_map.rs index e12eb953954f9..636a10feb1ab3 100644 --- a/frame/support/src/storage/generator/double_map.rs +++ b/frame/support/src/storage/generator/double_map.rs @@ -449,16 +449,16 @@ where Some(value) => value, None => { log::error!("Invalid translate: fail to decode old value"); - continue; - } + continue + }, }; let mut key_material = G::Hasher1::reverse(&previous_key[prefix.len()..]); let key1 = match K1::decode(&mut key_material) { Ok(key1) => key1, Err(_) => { log::error!("Invalid translate: fail to decode key1"); - continue; - } + continue + }, }; let mut key2_material = G::Hasher2::reverse(&key_material); @@ -466,8 +466,8 @@ where Ok(key2) => key2, Err(_) => { log::error!("Invalid translate: fail to decode key2"); - continue; - } + continue + }, }; match f(key1, key2, value) { diff --git a/frame/support/src/storage/generator/map.rs b/frame/support/src/storage/generator/map.rs index ce11e00a6423d..1a4225173c4ae 100644 --- a/frame/support/src/storage/generator/map.rs +++ b/frame/support/src/storage/generator/map.rs @@ -110,12 +110,12 @@ impl Iter Ok(key) => Some((key, value)), Err(_) => continue, } - } + }, None => continue, } - } + }, None => None, - }; + } } } } @@ -188,8 +188,8 @@ where Some(value) => value, None => { log::error!("Invalid translate: fail to decode old value"); - continue; - } + continue + }, }; let mut key_material = G::Hasher::reverse(&previous_key[prefix.len()..]); @@ -197,8 +197,8 @@ where Ok(key) => key, Err(_) => { log::error!("Invalid translate: fail to decode key"); - continue; - } + continue + }, }; match f(key, value) { diff --git a/frame/support/src/storage/generator/nmap.rs b/frame/support/src/storage/generator/nmap.rs index 02b82dc2f2a5e..4845673d3d8c2 100755 --- a/frame/support/src/storage/generator/nmap.rs +++ b/frame/support/src/storage/generator/nmap.rs @@ -408,16 +408,16 @@ impl> Some(value) => value, None => { log::error!("Invalid translate: fail to decode old value"); - continue; - } + continue + }, }; let final_key = match K::decode_final_key(&previous_key[prefix.len()..]) { Ok((final_key, _)) => final_key, Err(_) => { log::error!("Invalid translate: fail to decode key"); - continue; - } + continue + }, }; match f(final_key, value) { diff --git a/frame/support/src/storage/migration.rs b/frame/support/src/storage/migration.rs index 0928c3c6550cb..59422a282aab5 100644 --- a/frame/support/src/storage/migration.rs +++ b/frame/support/src/storage/migration.rs @@ -82,12 +82,12 @@ impl Iterator for StorageIterator { frame_support::storage::unhashed::kill(&next); } Some((self.previous_key[self.prefix.len()..].to_vec(), value)) - } + }, None => continue, } - } + }, None => None, - }; + } } } } @@ -152,15 +152,15 @@ impl Iterator frame_support::storage::unhashed::kill(&next); } Some((key, value)) - } + }, None => continue, } - } + }, Err(_) => continue, } - } + }, None => None, - }; + } } } } @@ -341,7 +341,7 @@ pub fn move_pallet(old_pallet_name: &[u8], new_pallet_name: &[u8]) { /// NOTE: The value at the key `from_prefix` is not moved. pub fn move_prefix(from_prefix: &[u8], to_prefix: &[u8]) { if from_prefix == to_prefix { - return; + return } let iter = PrefixIterator::<_> { diff --git a/frame/support/src/storage/mod.rs b/frame/support/src/storage/mod.rs index 1118f9b1fe6d3..35552e08fef1e 100644 --- a/frame/support/src/storage/mod.rs +++ b/frame/support/src/storage/mod.rs @@ -114,11 +114,11 @@ pub fn with_transaction(f: impl FnOnce() -> TransactionOutcome) -> R { Commit(res) => { commit_transaction(); res - } + }, Rollback(res) => { rollback_transaction(); res - } + }, } } @@ -875,8 +875,8 @@ impl Iterator for PrefixIterator Iterator for PrefixIterator None, - }; + } } } } @@ -973,12 +973,12 @@ impl Iterator for KeyPrefixIterator { Ok(item) => return Some(item), Err(e) => { log::error!("key failed to decode at {:?}: {:?}", self.previous_key, e); - continue; - } + continue + }, } } - return None; + return None } } } @@ -1088,8 +1088,8 @@ impl Iterator for ChildTriePrefixIterator { "next_key returned a key with no value at {:?}", self.previous_key, ); - continue; - } + continue + }, }; if self.drain { child::kill(&self.child_info, &self.previous_key) @@ -1103,14 +1103,14 @@ impl Iterator for ChildTriePrefixIterator { self.previous_key, e, ); - continue; - } + continue + }, }; Some(item) - } + }, None => None, - }; + } } } } @@ -1180,8 +1180,8 @@ pub trait StoragePrefixedMap { }, None => { log::error!("old key failed to decode at {:?}", previous_key); - continue; - } + continue + }, } } } diff --git a/frame/support/src/traits/members.rs b/frame/support/src/traits/members.rs index 3dd2dc6af3851..a59869c2fc9a3 100644 --- a/frame/support/src/traits/members.rs +++ b/frame/support/src/traits/members.rs @@ -213,19 +213,19 @@ pub trait ChangeMembers { (Some(old), Some(new)) if old == new => { old_i = old_iter.next(); new_i = new_iter.next(); - } + }, (Some(old), Some(new)) if old < new => { outgoing.push(old.clone()); old_i = old_iter.next(); - } + }, (Some(old), None) => { outgoing.push(old.clone()); old_i = old_iter.next(); - } + }, (_, Some(new)) => { incoming.push(new.clone()); new_i = new_iter.next(); - } + }, } } (incoming, outgoing) diff --git a/frame/support/src/traits/stored_map.rs b/frame/support/src/traits/stored_map.rs index de56377e095d7..715a5211be430 100644 --- a/frame/support/src/traits/stored_map.rs +++ b/frame/support/src/traits/stored_map.rs @@ -46,7 +46,7 @@ pub trait StoredMap { let r = f(&mut account); *x = Some(account); r - } + }, }) } diff --git a/frame/support/src/traits/tokens/fungible.rs b/frame/support/src/traits/tokens/fungible.rs index effe7ee7dcdd2..b033236d447bb 100644 --- a/frame/support/src/traits/tokens/fungible.rs +++ b/frame/support/src/traits/tokens/fungible.rs @@ -100,7 +100,7 @@ pub trait Mutate: Inspect { let revert = Self::mint_into(source, actual); debug_assert!(revert.is_ok(), "withdrew funds previously; qed"); Err(err) - } + }, } } } diff --git a/frame/support/src/traits/tokens/fungible/balanced.rs b/frame/support/src/traits/tokens/fungible/balanced.rs index e18c0a26611cb..7b33a595a1b55 100644 --- a/frame/support/src/traits/tokens/fungible/balanced.rs +++ b/frame/support/src/traits/tokens/fungible/balanced.rs @@ -133,7 +133,7 @@ pub trait Balanced: Inspect { SameOrOther::Other(rest) => { debug_assert!(false, "ok withdraw return must be at least debt value; qed"); Err(rest) - } + }, } } } diff --git a/frame/support/src/traits/tokens/fungibles.rs b/frame/support/src/traits/tokens/fungibles.rs index 76e5cdd94c3a8..b164a99671658 100644 --- a/frame/support/src/traits/tokens/fungibles.rs +++ b/frame/support/src/traits/tokens/fungibles.rs @@ -151,7 +151,7 @@ pub trait Mutate: Inspect { let revert = Self::mint_into(asset, source, actual); debug_assert!(revert.is_ok(), "withdrew funds previously; qed"); Err(err) - } + }, } } } diff --git a/frame/support/src/traits/tokens/fungibles/balanced.rs b/frame/support/src/traits/tokens/fungibles/balanced.rs index cbb9446cd8fa4..40a65305b87da 100644 --- a/frame/support/src/traits/tokens/fungibles/balanced.rs +++ b/frame/support/src/traits/tokens/fungibles/balanced.rs @@ -149,11 +149,11 @@ pub trait Balanced: Inspect { Ok(SameOrOther::Other(rest)) => { debug_assert!(false, "ok withdraw return must be at least debt value; qed"); Err(rest) - } + }, Err(_) => { debug_assert!(false, "debt.asset is credit.asset; qed"); Ok(CreditOf::::zero(asset)) - } + }, } } } diff --git a/frame/support/src/traits/tokens/imbalance.rs b/frame/support/src/traits/tokens/imbalance.rs index cd507942804b0..0f7b38a65efc8 100644 --- a/frame/support/src/traits/tokens/imbalance.rs +++ b/frame/support/src/traits/tokens/imbalance.rs @@ -83,7 +83,7 @@ pub trait Imbalance: Sized + TryDrop + Default { { let total: u32 = first.saturating_add(second); if total == 0 { - return (Self::zero(), Self::zero()); + return (Self::zero(), Self::zero()) } let amount1 = self.peek().saturating_mul(first.into()) / total.into(); self.split(amount1) diff --git a/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs b/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs index 83ee04089e684..3e76d069f50e7 100644 --- a/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs +++ b/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs @@ -54,19 +54,17 @@ impl< /// both. pub fn merge(self, other: Self) -> Self { match (self, other) { - (SignedImbalance::Positive(one), SignedImbalance::Positive(other)) => { - SignedImbalance::Positive(one.merge(other)) - } - (SignedImbalance::Negative(one), SignedImbalance::Negative(other)) => { - SignedImbalance::Negative(one.merge(other)) - } + (SignedImbalance::Positive(one), SignedImbalance::Positive(other)) => + SignedImbalance::Positive(one.merge(other)), + (SignedImbalance::Negative(one), SignedImbalance::Negative(other)) => + SignedImbalance::Negative(one.merge(other)), (SignedImbalance::Positive(one), SignedImbalance::Negative(other)) => { match one.offset(other) { SameOrOther::Same(positive) => SignedImbalance::Positive(positive), SameOrOther::Other(negative) => SignedImbalance::Negative(negative), SameOrOther::None => SignedImbalance::Positive(P::zero()), } - } + }, (one, other) => other.merge(one), } } diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index 441d90375f5b0..ec5f37823ad47 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -433,7 +433,7 @@ where impl WeighData for Weight { fn weigh_data(&self, _: T) -> Weight { - return *self; + return *self } } @@ -451,7 +451,7 @@ impl PaysFee for Weight { impl WeighData for (Weight, DispatchClass, Pays) { fn weigh_data(&self, _: T) -> Weight { - return self.0; + return self.0 } } @@ -469,7 +469,7 @@ impl PaysFee for (Weight, DispatchClass, Pays) { impl WeighData for (Weight, DispatchClass) { fn weigh_data(&self, _: T) -> Weight { - return self.0; + return self.0 } } @@ -487,7 +487,7 @@ impl PaysFee for (Weight, DispatchClass) { impl WeighData for (Weight, Pays) { fn weigh_data(&self, _: T) -> Weight { - return self.0; + return self.0 } } diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index 16bf623112c8e..dc72be3ebdd49 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -372,7 +372,7 @@ pub mod pallet { T::AccountId::from(SomeType1); // Test for where clause T::AccountId::from(SomeType5); // Test for where clause if matches!(call, Call::foo_transactional { .. }) { - return Ok(ValidTransaction::default()); + return Ok(ValidTransaction::default()) } Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) } diff --git a/frame/support/test/tests/pallet_compatibility.rs b/frame/support/test/tests/pallet_compatibility.rs index 3641cc28e27d1..4523063252ab9 100644 --- a/frame/support/test/tests/pallet_compatibility.rs +++ b/frame/support/test/tests/pallet_compatibility.rs @@ -285,9 +285,8 @@ mod test { fn metadata() { let metadata = Runtime::metadata(); let (pallets, types) = match metadata.1 { - frame_support::metadata::RuntimeMetadata::V14(metadata) => { - (metadata.pallets, metadata.types) - } + frame_support::metadata::RuntimeMetadata::V14(metadata) => + (metadata.pallets, metadata.types), _ => unreachable!(), }; diff --git a/frame/support/test/tests/pallet_compatibility_instance.rs b/frame/support/test/tests/pallet_compatibility_instance.rs index b6c100c5bc193..768b9f28d35f3 100644 --- a/frame/support/test/tests/pallet_compatibility_instance.rs +++ b/frame/support/test/tests/pallet_compatibility_instance.rs @@ -288,9 +288,8 @@ mod test { fn metadata() { let metadata = Runtime::metadata(); let (pallets, types) = match metadata.1 { - frame_support::metadata::RuntimeMetadata::V14(metadata) => { - (metadata.pallets, metadata.types) - } + frame_support::metadata::RuntimeMetadata::V14(metadata) => + (metadata.pallets, metadata.types), _ => unreachable!(), }; diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index da085f962079a..3a1009402d6f2 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -747,25 +747,25 @@ fn metadata() { match example_pallet_instance1_metadata.calls { Some(ref mut calls_meta) => { calls_meta.ty = scale_info::meta_type::>(); - } + }, _ => unreachable!(), } match example_pallet_instance1_metadata.event { Some(ref mut event_meta) => { event_meta.ty = scale_info::meta_type::>(); - } + }, _ => unreachable!(), } match example_pallet_instance1_metadata.error { Some(ref mut error_meta) => { error_meta.ty = scale_info::meta_type::>(); - } + }, _ => unreachable!(), } match example_pallet_instance1_metadata.storage { Some(ref mut storage_meta) => { storage_meta.prefix = "Instance1Example"; - } + }, _ => unreachable!(), } diff --git a/frame/system/src/extensions/check_nonce.rs b/frame/system/src/extensions/check_nonce.rs index f7a39866ec7c9..3c6f9a1b4dbd1 100644 --- a/frame/system/src/extensions/check_nonce.rs +++ b/frame/system/src/extensions/check_nonce.rs @@ -86,7 +86,7 @@ where } else { InvalidTransaction::Future } - .into()); + .into()) } account.nonce += T::Index::one(); crate::Account::::insert(who, account); @@ -103,7 +103,7 @@ where // check index let account = crate::Account::::get(who); if self.0 < account.nonce { - return InvalidTransaction::Stale.into(); + return InvalidTransaction::Stale.into() } let provides = vec![Encode::encode(&(who, self.0))]; diff --git a/frame/system/src/extensions/check_weight.rs b/frame/system/src/extensions/check_weight.rs index 4a9e137b2051f..ca885accd660f 100644 --- a/frame/system/src/extensions/check_weight.rs +++ b/frame/system/src/extensions/check_weight.rs @@ -147,7 +147,7 @@ where Some(max) if per_class > max => return Err(InvalidTransaction::ExhaustsResources.into()), // There is no `max_total` limit (`None`), // or we are below the limit. - _ => {} + _ => {}, } // In cases total block weight is exceeded, we need to fall back @@ -155,12 +155,11 @@ where if all_weight.total() > maximum_weight.max_block { match limit_per_class.reserved { // We are over the limit in reserved pool. - Some(reserved) if per_class > reserved => { - return Err(InvalidTransaction::ExhaustsResources.into()) - } + Some(reserved) if per_class > reserved => + return Err(InvalidTransaction::ExhaustsResources.into()), // There is either no limit in reserved pool (`None`), // or we are below the limit. - _ => {} + _ => {}, } } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index d15c46fc7f7c3..2e7f26eef16f4 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -1149,18 +1149,18 @@ impl Pallet { Pallet::::on_killed_account(who.clone()); Ok(DecRefStatus::Reaped) - } + }, (1, c, _) if c > 0 => { // Cannot remove last provider if there are consumers. Err(DispatchError::ConsumerRemaining) - } + }, (x, _, _) => { // Account will continue to exist as there is either > 1 provider or // > 0 sufficients. account.providers = x - 1; *maybe_account = Some(account); Ok(DecRefStatus::Exists) - } + }, } } else { log::error!( @@ -1204,12 +1204,12 @@ impl Pallet { (0, 0) | (1, 0) => { Pallet::::on_killed_account(who.clone()); DecRefStatus::Reaped - } + }, (x, _) => { account.sufficients = x - 1; *maybe_account = Some(account); DecRefStatus::Exists - } + }, } } else { log::error!( @@ -1301,7 +1301,7 @@ impl Pallet { let block_number = Self::block_number(); // Don't populate events on genesis. if block_number.is_zero() { - return; + return } let phase = ExecutionPhase::::get().unwrap_or_default(); @@ -1573,7 +1573,7 @@ impl Pallet { err, ); Event::ExtrinsicFailed(err.error, info) - } + }, }); let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32; @@ -1707,10 +1707,10 @@ impl StoredMap for Pallet { DecRefStatus::Reaped => return Ok(result), DecRefStatus::Exists => { // Update value as normal... - } + }, } } else if !was_providing && !is_providing { - return Ok(result); + return Ok(result) } Account::::mutate(k, |a| a.data = some_data.unwrap_or_default()); Ok(result) @@ -1726,7 +1726,7 @@ pub fn split_inner( Some(inner) => { let (r, s) = splitter(inner); (Some(r), Some(s)) - } + }, None => (None, None), } } diff --git a/frame/system/src/offchain.rs b/frame/system/src/offchain.rs index fd1ace149b41d..ed758a2556b77 100644 --- a/frame/system/src/offchain.rs +++ b/frame/system/src/offchain.rs @@ -175,7 +175,7 @@ impl, X> Signer }) .filter(move |account| keystore_lookup.contains(&account.public)), ) - } + }, } } @@ -211,7 +211,7 @@ impl> Signer(length: u32) -> (T::AccountId, Vec, T::AccountId) { let caller = whitelisted_caller(); - let value = T::TipReportDepositBase::get() - + T::DataDepositPerByte::get() * length.into() - + T::Currency::minimum_balance(); + let value = T::TipReportDepositBase::get() + + T::DataDepositPerByte::get() * length.into() + + T::Currency::minimum_balance(); let _ = T::Currency::make_free_balance_be(&caller, value); let reason = vec![0; length as usize]; let awesome_person = account("awesome", 0, SEED); diff --git a/frame/tips/src/lib.rs b/frame/tips/src/lib.rs index 9976f1a6c02b7..f4a4edb7b3999 100644 --- a/frame/tips/src/lib.rs +++ b/frame/tips/src/lib.rs @@ -250,8 +250,8 @@ pub mod pallet { let hash = T::Hashing::hash_of(&(&reason_hash, &who)); ensure!(!Tips::::contains_key(&hash), Error::::AlreadyKnown); - let deposit = T::TipReportDepositBase::get() - + T::DataDepositPerByte::get() * (reason.len() as u32).into(); + let deposit = T::TipReportDepositBase::get() + + T::DataDepositPerByte::get() * (reason.len() as u32).into(); T::Currency::reserve(&finder, deposit)?; Reasons::::insert(&reason_hash, &reason); @@ -501,11 +501,11 @@ impl Pallet { Some(m) => { member = members_iter.next(); if m < a { - continue; + continue } else { - break true; + break true } - } + }, } }); } diff --git a/frame/tips/src/migrations/v4.rs b/frame/tips/src/migrations/v4.rs index 4812738a890ec..69df1d08d2c8a 100644 --- a/frame/tips/src/migrations/v4.rs +++ b/frame/tips/src/migrations/v4.rs @@ -49,7 +49,7 @@ pub fn migrate::on_chain_storage_version(); @@ -109,7 +109,7 @@ pub fn pre_migrate< log_migration("pre-migration", storage_prefix_reasons, old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return; + return } let new_pallet_prefix = twox_128(new_pallet_name.as_bytes()); @@ -148,7 +148,7 @@ pub fn post_migrate< log_migration("post-migration", storage_prefix_reasons, old_pallet_name, new_pallet_name); if new_pallet_name == old_pallet_name { - return; + return } // Assert that no `Tips` and `Reasons` storages remains at the old prefix. diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index a4c4d6d072bf4..dd36a0ff162a6 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -349,15 +349,15 @@ pub mod pallet { // loss. use sp_std::convert::TryInto; assert!( - ::max_value() - >= Multiplier::checked_from_integer( + ::max_value() >= + Multiplier::checked_from_integer( T::BlockWeights::get().max_block.try_into().unwrap() ) .unwrap(), ); - let target = T::FeeMultiplierUpdate::target() - * T::BlockWeights::get().get(DispatchClass::Normal).max_total.expect( + let target = T::FeeMultiplierUpdate::target() * + T::BlockWeights::get().get(DispatchClass::Normal).max_total.expect( "Setting `max_total` for `Normal` dispatch class is not compatible with \ `transaction-payment` pallet.", ); @@ -365,7 +365,7 @@ pub mod pallet { let addition = target / 100; if addition == 0 { // this is most likely because in a test setup we set everything to (). - return; + return } #[cfg(any(feature = "std", test))] @@ -645,12 +645,12 @@ where DispatchClass::Normal => { // For normal class we simply take the `tip_per_weight`. scaled_tip - } + }, DispatchClass::Mandatory => { // Mandatory extrinsics should be prohibited (e.g. by the [`CheckWeight`] // extensions), but just to be safe let's return the same priority as `Normal` here. scaled_tip - } + }, DispatchClass::Operational => { // A "virtual tip" value added to an `Operational` extrinsic. // This value should be kept high enough to allow `Operational` extrinsics @@ -662,7 +662,7 @@ where let scaled_virtual_tip = max_reward(virtual_tip); scaled_tip.saturating_add(scaled_virtual_tip) - } + }, } .saturated_into::() } @@ -1319,8 +1319,10 @@ mod tests { )); assert_eq!(Balances::free_balance(2), 0); // Transfer Event - System::assert_has_event(Event::Balances(pallet_balances::Event::Transfer{ - from: 2, to: 3, value: 80, + System::assert_has_event(Event::Balances(pallet_balances::Event::Transfer { + from: 2, + to: 3, + value: 80, })); // Killed Event System::assert_has_event(Event::System(system::Event::KilledAccount(2))); diff --git a/frame/transaction-payment/src/payment.rs b/frame/transaction-payment/src/payment.rs index ae692fac64b03..58e6ef63109a3 100644 --- a/frame/transaction-payment/src/payment.rs +++ b/frame/transaction-payment/src/payment.rs @@ -99,7 +99,7 @@ where tip: Self::Balance, ) -> Result { if fee.is_zero() { - return Ok(None); + return Ok(None) } let withdraw_reason = if tip.is_zero() { diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index 03d75d6f6f826..bc31199d90391 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -198,7 +198,7 @@ pub mod pallet { let mut index = 0; >::mutate(|transactions| { if transactions.len() + 1 > MaxBlockTransactions::::get() as usize { - return Err(Error::::TooManyTransactions); + return Err(Error::::TooManyTransactions) } let total_chunks = transactions.last().map_or(0, |t| t.block_chunks) + chunk_count; index = transactions.len() as u32; @@ -238,7 +238,7 @@ pub mod pallet { let mut index = 0; >::mutate(|transactions| { if transactions.len() + 1 > MaxBlockTransactions::::get() as usize { - return Err(Error::::TooManyTransactions); + return Err(Error::::TooManyTransactions) } let chunks = num_chunks(info.size); let total_chunks = transactions.last().map_or(0, |t| t.block_chunks) + chunks; @@ -291,7 +291,7 @@ pub mod pallet { let chunks = num_chunks(info.size); let prev_chunks = info.block_chunks - chunks; (info, selected_chunk_index - prev_chunks) - } + }, None => Err(Error::::MissingStateData)?, }; ensure!( diff --git a/frame/uniques/src/lib.rs b/frame/uniques/src/lib.rs index 9427a29e931f2..1bf220e4a7876 100644 --- a/frame/uniques/src/lib.rs +++ b/frame/uniques/src/lib.rs @@ -536,10 +536,10 @@ pub mod pallet { if T::Currency::reserve(&class_details.owner, deposit - old).is_err() { // NOTE: No alterations made to class_details in this iteration so far, so // this is OK to do. - continue; + continue } } else { - continue; + continue } class_details.total_deposit.saturating_accrue(deposit); class_details.total_deposit.saturating_reduce(old); @@ -691,7 +691,7 @@ pub mod pallet { let details = maybe_details.as_mut().ok_or(Error::::Unknown)?; ensure!(&origin == &details.owner, Error::::NoPermission); if details.owner == owner { - return Ok(()); + return Ok(()) } // Move the deposit to the new owner. @@ -914,9 +914,8 @@ pub mod pallet { } let maybe_is_frozen = match maybe_instance { None => ClassMetadataOf::::get(class).map(|v| v.is_frozen), - Some(instance) => { - InstanceMetadataOf::::get(class, instance).map(|v| v.is_frozen) - } + Some(instance) => + InstanceMetadataOf::::get(class, instance).map(|v| v.is_frozen), }; ensure!(!maybe_is_frozen.unwrap_or(false), Error::::Frozen); @@ -979,9 +978,8 @@ pub mod pallet { } let maybe_is_frozen = match maybe_instance { None => ClassMetadataOf::::get(class).map(|v| v.is_frozen), - Some(instance) => { - InstanceMetadataOf::::get(class, instance).map(|v| v.is_frozen) - } + Some(instance) => + InstanceMetadataOf::::get(class, instance).map(|v| v.is_frozen), }; ensure!(!maybe_is_frozen.unwrap_or(false), Error::::Frozen); diff --git a/frame/utility/src/lib.rs b/frame/utility/src/lib.rs index 8ce18ab844864..54de87c4740c8 100644 --- a/frame/utility/src/lib.rs +++ b/frame/utility/src/lib.rs @@ -195,7 +195,7 @@ pub mod pallet { // Take the weight of this function itself into account. let base_weight = T::WeightInfo::batch(index.saturating_add(1) as u32); // Return the actual used weight + base_weight of this call. - return Ok(Some(base_weight + weight).into()); + return Ok(Some(base_weight + weight).into()) } Self::deposit_event(Event::ItemCompleted); } diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 09c0e9e9cdeb4..27862a5ca4b72 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -440,7 +440,7 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; if schedule1_index == schedule2_index { - return Ok(()); + return Ok(()) }; let schedule1_index = schedule1_index as usize; let schedule2_index = schedule2_index as usize; @@ -479,7 +479,7 @@ impl Pallet { (true, false) => return Some(schedule2), (false, true) => return Some(schedule1), // If neither schedule has ended don't exit early. - _ => {} + _ => {}, } let locked = schedule1 @@ -517,7 +517,7 @@ impl Pallet { // Validate user inputs. ensure!(schedule.locked() >= T::MinVestedTransfer::get(), Error::::AmountLow); if !schedule.is_valid() { - return Err(Error::::InvalidScheduleParams.into()); + return Err(Error::::InvalidScheduleParams.into()) }; let target = T::Lookup::lookup(target)?; let source = T::Lookup::lookup(source)?; @@ -658,13 +658,13 @@ impl Pallet { } // In the None case there was no new schedule to account for. (schedules, locked_now) - } + }, _ => Self::report_schedule_updates(schedules.to_vec(), action), }; debug_assert!( - locked_now > Zero::zero() && schedules.len() > 0 - || locked_now == Zero::zero() && schedules.len() == 0 + locked_now > Zero::zero() && schedules.len() > 0 || + locked_now == Zero::zero() && schedules.len() == 0 ); Ok((schedules, locked_now)) @@ -710,13 +710,13 @@ where starting_block: T::BlockNumber, ) -> DispatchResult { if locked.is_zero() { - return Ok(()); + return Ok(()) } let vesting_schedule = VestingInfo::new(locked, per_block, starting_block); // Check for `per_block` or `locked` of 0. if !vesting_schedule.is_valid() { - return Err(Error::::InvalidScheduleParams.into()); + return Err(Error::::InvalidScheduleParams.into()) }; let mut schedules = Self::vesting(who).unwrap_or_default(); @@ -744,7 +744,7 @@ where ) -> DispatchResult { // Check for `per_block` or `locked` of 0. if !VestingInfo::new(locked, per_block, starting_block).is_valid() { - return Err(Error::::InvalidScheduleParams.into()); + return Err(Error::::InvalidScheduleParams.into()) } ensure!( diff --git a/frame/vesting/src/tests.rs b/frame/vesting/src/tests.rs index 684246102363e..2a6dd0520c3b0 100644 --- a/frame/vesting/src/tests.rs +++ b/frame/vesting/src/tests.rs @@ -1131,16 +1131,16 @@ fn vested_transfer_less_than_existential_deposit_fails() { ExtBuilder::default().existential_deposit(4 * ED).build().execute_with(|| { // MinVestedTransfer is less the ED. assert!( - ::Currency::minimum_balance() - > ::MinVestedTransfer::get() + ::Currency::minimum_balance() > + ::MinVestedTransfer::get() ); let sched = VestingInfo::new(::MinVestedTransfer::get() as u64, 1u64, 10u64); // The new account balance with the schedule's locked amount would be less than ED. assert!( - Balances::free_balance(&99) + sched.locked() - < ::Currency::minimum_balance() + Balances::free_balance(&99) + sched.locked() < + ::Currency::minimum_balance() ); // vested_transfer fails. diff --git a/frame/vesting/src/vesting_info.rs b/frame/vesting/src/vesting_info.rs index c910a7f48b69b..81bffa199fd72 100644 --- a/frame/vesting/src/vesting_info.rs +++ b/frame/vesting/src/vesting_info.rs @@ -99,8 +99,8 @@ where // the block after starting. One::one() } else { - self.locked / self.per_block() - + if (self.locked % self.per_block()).is_zero() { + self.locked / self.per_block() + + if (self.locked % self.per_block()).is_zero() { Zero::zero() } else { // `per_block` does not perfectly divide `locked`, so we need an extra block to From 8290edd6b082fd83c967f93c59c3294ec9febf6c Mon Sep 17 00:00:00 2001 From: david Date: Mon, 1 Nov 2021 08:49:58 +0100 Subject: [PATCH 07/11] minorfixes --- bin/node/executor/tests/basic.rs | 12 +++---- frame/balances/src/lib.rs | 45 +++++++++++++------------- frame/balances/src/tests.rs | 20 ++++++------ frame/balances/src/tests_local.rs | 6 ++-- frame/balances/src/tests_reentrancy.rs | 18 +++++------ frame/contracts/src/tests.rs | 6 ++-- frame/multisig/src/lib.rs | 7 ++-- frame/offences/benchmarking/src/lib.rs | 4 +-- frame/proxy/src/tests.rs | 2 +- frame/staking/src/slashing.rs | 2 +- frame/staking/src/tests.rs | 4 +-- frame/transaction-payment/src/lib.rs | 2 +- 12 files changed, 63 insertions(+), 65 deletions(-) diff --git a/bin/node/executor/tests/basic.rs b/bin/node/executor/tests/basic.rs index 6923237b3ca92..a40a00c79e8f2 100644 --- a/bin/node/executor/tests/basic.rs +++ b/bin/node/executor/tests/basic.rs @@ -398,7 +398,7 @@ fn full_native_block_import_works() { event: Event::Balances(pallet_balances::Event::Transfer { from: alice().into(), to: bob().into(), - value: 69 * DOLLARS, + amount: 69 * DOLLARS, }), topics: vec![], }, @@ -406,7 +406,7 @@ fn full_native_block_import_works() { phase: Phase::ApplyExtrinsic(1), event: Event::Balances(pallet_balances::Event::Deposit { who: pallet_treasury::Pallet::::account_id(), - deposit: fees * 8 / 10, + amount: fees * 8 / 10, }), topics: vec![], }, @@ -468,7 +468,7 @@ fn full_native_block_import_works() { event: Event::Balances(pallet_balances::Event::Transfer { from: bob().into(), to: alice().into(), - value: 5 * DOLLARS, + amount: 5 * DOLLARS, }), topics: vec![], }, @@ -476,7 +476,7 @@ fn full_native_block_import_works() { phase: Phase::ApplyExtrinsic(1), event: Event::Balances(pallet_balances::Event::Deposit { who: pallet_treasury::Pallet::::account_id(), - deposit: fees * 8 / 10, + amount: fees * 8 / 10, }), topics: vec![], }, @@ -506,7 +506,7 @@ fn full_native_block_import_works() { event: Event::Balances(pallet_balances::Event::Transfer { from: alice().into(), to: bob().into(), - value: 15 * DOLLARS, + amount: 15 * DOLLARS, }), topics: vec![], }, @@ -514,7 +514,7 @@ fn full_native_block_import_works() { phase: Phase::ApplyExtrinsic(2), event: Event::Balances(pallet_balances::Event::Deposit { who: pallet_treasury::Pallet::::account_id(), - deposit: fees * 8 / 10, + amount: fees * 8 / 10, }), topics: vec![], }, diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index d02a57a6cc8ed..cb9ca82d5440f 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -458,30 +458,29 @@ pub mod pallet { Endowed { account: T::AccountId, free_balance: T::Balance }, /// An account was removed whose balance was non-zero but below ExistentialDeposit, /// resulting in an outright loss. - DustLost { account: T::AccountId, balance: T::Balance }, + DustLost { account: T::AccountId, amount: T::Balance }, /// Transfer succeeded. - Transfer { from: T::AccountId, to: T::AccountId, value: T::Balance }, + Transfer { from: T::AccountId, to: T::AccountId, amount: T::Balance }, /// A balance was set by root. BalanceSet { who: T::AccountId, free: T::Balance, reserved: T::Balance }, - /// Some amount was deposited (e.g. for transaction fees). - Deposit { who: T::AccountId, deposit: T::Balance }, - /// Some amount was withdrawn from the account (e.g. for transaction fees). \[who, value\] - Withdraw { who: T::AccountId, amount: T::Balance }, /// Some balance was reserved (moved from free to reserved). - Reserved { who: T::AccountId, value: T::Balance }, + Reserved { who: T::AccountId, amount: T::Balance }, /// Some balance was unreserved (moved from reserved to free). - Unreserved { who: T::AccountId, value: T::Balance }, + Unreserved { who: T::AccountId, amount: T::Balance }, /// Some balance was moved from the reserve of the first account to the second account. /// Final argument indicates the destination balance type. ReserveRepatriated { from: T::AccountId, to: T::AccountId, - balance: T::Balance, + amount: T::Balance, destination_status: Status, }, - /// Some amount was removed from the account (e.g. for misbehavior). \[who, - /// amount_slashed\] - Slashed { who: T::AccountId, amount_slashed: T::Balance }, + /// Some amount was deposited (e.g. for transaction fees). + Deposit { who: T::AccountId, amount: T::Balance }, + /// Some amount was withdrawn from the account (e.g. for transaction fees). + Withdraw { who: T::AccountId, amount: T::Balance }, + /// Some amount was removed from the account (e.g. for misbehavior). + Slashed { who: T::AccountId, amount: T::Balance }, } /// Old name generated by `decl_event`. @@ -745,7 +744,7 @@ pub struct DustCleaner, I: 'static = ()>( impl, I: 'static> Drop for DustCleaner { fn drop(&mut self) { if let Some((who, dust)) = self.0.take() { - Pallet::::deposit_event(Event::DustLost { account: who, balance: dust.peek() }); + Pallet::::deposit_event(Event::DustLost { account: who, amount: dust.peek() }); T::DustRemoval::on_unbalanced(dust); } } @@ -1057,7 +1056,7 @@ impl, I: 'static> Pallet { Self::deposit_event(Event::ReserveRepatriated { from: slashed.clone(), to: beneficiary.clone(), - balance: actual, + amount: actual, destination_status: status, }); Ok(actual) @@ -1112,7 +1111,7 @@ impl, I: 'static> fungible::Mutate for Pallet { Ok(()) })?; TotalIssuance::::mutate(|t| *t += amount); - Self::deposit_event(Event::Deposit { who: who.clone(), deposit: amount }); + Self::deposit_event(Event::Deposit { who: who.clone(), amount: amount }); Ok(()) } @@ -1538,7 +1537,7 @@ where )?; // Emit transfer event. - Self::deposit_event(Event::Transfer { from: transactor.clone(), to: dest.clone(), value }); + Self::deposit_event(Event::Transfer { from: transactor.clone(), to: dest.clone(), amount: value }); Ok(()) } @@ -1604,7 +1603,7 @@ where Ok((imbalance, not_slashed)) => { Self::deposit_event(Event::Slashed { who: who.clone(), - amount_slashed: value.saturating_sub(not_slashed), + amount: value.saturating_sub(not_slashed), }); return (imbalance, not_slashed) }, @@ -1632,7 +1631,7 @@ where |account, is_new| -> Result { ensure!(!is_new, Error::::DeadAccount); account.free = account.free.checked_add(&value).ok_or(ArithmeticError::Overflow)?; - Self::deposit_event(Event::Deposit { who: who.clone(), deposit: value }); + Self::deposit_event(Event::Deposit { who: who.clone(), amount: value }); Ok(PositiveImbalance::new(value)) }, ) @@ -1665,7 +1664,7 @@ where None => return Ok(Self::PositiveImbalance::zero()), }; - Self::deposit_event(Event::Deposit { who: who.clone(), deposit: value }); + Self::deposit_event(Event::Deposit { who: who.clone(), amount: value }); Ok(PositiveImbalance::new(value)) }, ) @@ -1784,7 +1783,7 @@ where Self::ensure_can_withdraw(&who, value.clone(), WithdrawReasons::RESERVE, account.free) })?; - Self::deposit_event(Event::Reserved { who: who.clone(), value }); + Self::deposit_event(Event::Reserved { who: who.clone(), amount: value }); Ok(()) } @@ -1816,7 +1815,7 @@ where }, }; - Self::deposit_event(Event::Unreserved { who: who.clone(), value: actual.clone() }); + Self::deposit_event(Event::Unreserved { who: who.clone(), amount: actual.clone() }); value - actual } @@ -1859,7 +1858,7 @@ where Ok((imbalance, not_slashed)) => { Self::deposit_event(Event::Slashed { who: who.clone(), - amount_slashed: value.saturating_sub(not_slashed), + amount: value.saturating_sub(not_slashed), }); return (imbalance, not_slashed) }, @@ -2005,7 +2004,7 @@ where Self::deposit_event(Event::Slashed { who: who.clone(), - amount_slashed: actual, + amount: actual, }); (imb, value - actual) }, diff --git a/frame/balances/src/tests.rs b/frame/balances/src/tests.rs index 29b4377386861..d833e09215fd2 100644 --- a/frame/balances/src/tests.rs +++ b/frame/balances/src/tests.rs @@ -314,7 +314,7 @@ macro_rules! decl_tests { <$ext_builder>::default().monied(true).build().execute_with(|| { assert_eq!(Balances::total_balance(&1), 10); assert_ok!(Balances::deposit_into_existing(&1, 10).map(drop)); - System::assert_last_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 10})); + System::assert_last_event(Event::Balances(crate::Event::Deposit{who: 1, amount: 10})); assert_eq!(Balances::total_balance(&1), 20); assert_eq!(>::get(), 120); }); @@ -342,7 +342,7 @@ macro_rules! decl_tests { fn balance_works() { <$ext_builder>::default().build().execute_with(|| { let _ = Balances::deposit_creating(&1, 42); - System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, deposit: 42})); + System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, amount: 42})); assert_eq!(Balances::free_balance(1), 42); assert_eq!(Balances::reserved_balance(1), 0); assert_eq!(Balances::total_balance(&1), 42); @@ -505,7 +505,7 @@ macro_rules! decl_tests { assert_ok!(Balances::reserve(&1, 110)); assert_ok!(Balances::repatriate_reserved(&1, &2, 41, Status::Free), 0); System::assert_last_event( - Event::Balances(crate::Event::ReserveRepatriated{from: 1, to: 2, balance: 41, destination_status: Status::Free}) + Event::Balances(crate::Event::ReserveRepatriated{from: 1, to: 2, amount: 41, destination_status: Status::Free}) ); assert_eq!(Balances::reserved_balance(1), 69); assert_eq!(Balances::free_balance(1), 0); @@ -724,18 +724,18 @@ macro_rules! decl_tests { System::set_block_number(2); assert_ok!(Balances::reserve(&1, 10)); - System::assert_last_event(Event::Balances(crate::Event::Reserved{who: 1, value: 10})); + System::assert_last_event(Event::Balances(crate::Event::Reserved{who: 1, amount: 10})); System::set_block_number(3); assert!(Balances::unreserve(&1, 5).is_zero()); - System::assert_last_event(Event::Balances(crate::Event::Unreserved{who: 1, value: 5})); + System::assert_last_event(Event::Balances(crate::Event::Unreserved{who: 1, amount: 5})); System::set_block_number(4); assert_eq!(Balances::unreserve(&1, 6), 1); // should only unreserve 5 - System::assert_last_event(Event::Balances(crate::Event::Unreserved{who: 1, value: 5})); + System::assert_last_event(Event::Balances(crate::Event::Unreserved{who: 1, amount: 5})); }); } @@ -763,8 +763,8 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::KilledAccount(1)), - Event::Balances(crate::Event::DustLost{account: 1, balance: 99}), - Event::Balances(crate::Event::Slashed{who: 1, amount_slashed: 1}), + Event::Balances(crate::Event::DustLost{account: 1, amount: 99}), + Event::Balances(crate::Event::Slashed{who: 1, amount: 1}), ] ); }); @@ -794,7 +794,7 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::KilledAccount(1)), - Event::Balances(crate::Event::Slashed{who: 1, amount_slashed: 100}), + Event::Balances(crate::Event::Slashed{who: 1, amount: 100}), ] ); }); @@ -814,7 +814,7 @@ macro_rules! decl_tests { assert_eq!(Balances::slash(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive assert!(System::account_exists(&1)); - System::assert_last_event(Event::Balances(crate::Event::Slashed{who: 1, amount_slashed: 900})); + System::assert_last_event(Event::Balances(crate::Event::Slashed{who: 1, amount: 900})); // SCENARIO: Slash will kill account because not enough balance left. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index cbeb867638e95..16dcd9481d3b8 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -175,7 +175,7 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { // no events assert_eq!( events(), - [Event::Balances(crate::Event::Slashed { who: 1, amount_slashed: 98 })] + [Event::Balances(crate::Event::Slashed { who: 1, amount: 98 })] ); let res = Balances::slash(&1, 1); @@ -185,8 +185,8 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { events(), [ Event::System(system::Event::KilledAccount(1)), - Event::Balances(crate::Event::DustLost { account: 1, balance: 1 }), - Event::Balances(crate::Event::Slashed { who: 1, amount_slashed: 1 }) + Event::Balances(crate::Event::DustLost { account: 1, amount: 1 }), + Event::Balances(crate::Event::Slashed { who: 1, amount: 1 }) ] ); }); diff --git a/frame/balances/src/tests_reentrancy.rs b/frame/balances/src/tests_reentrancy.rs index 0e23384864222..80716b306e6a6 100644 --- a/frame/balances/src/tests_reentrancy.rs +++ b/frame/balances/src/tests_reentrancy.rs @@ -172,13 +172,13 @@ fn transfer_dust_removal_tst1_should_work() { System::assert_has_event(Event::Balances(crate::Event::Transfer { from: 2, to: 3, - value: 450, + amount: 450, })); System::assert_has_event(Event::Balances(crate::Event::DustLost { account: 2, - balance: 50, + amount: 50, })); - System::assert_has_event(Event::Balances(crate::Event::Deposit { who: 1, deposit: 50 })); + System::assert_has_event(Event::Balances(crate::Event::Deposit { who: 1, amount: 50 })); }); } @@ -207,13 +207,13 @@ fn transfer_dust_removal_tst2_should_work() { System::assert_has_event(Event::Balances(crate::Event::Transfer { from: 2, to: 1, - value: 450, + amount: 450, })); System::assert_has_event(Event::Balances(crate::Event::DustLost { account: 2, - balance: 50, + amount: 50, })); - System::assert_has_event(Event::Balances(crate::Event::Deposit { who: 1, deposit: 50 })); + System::assert_has_event(Event::Balances(crate::Event::Deposit { who: 1, amount: 50 })); }); } @@ -251,14 +251,14 @@ fn repatriating_reserved_balance_dust_removal_should_work() { System::assert_has_event(Event::Balances(crate::Event::ReserveRepatriated { from: 2, to: 1, - balance: 450, + amount: 450, destination_status: Status::Free, })); System::assert_last_event(Event::Balances(crate::Event::DustLost { account: 2, - balance: 50, + amount: 50, })); - System::assert_last_event(Event::Balances(crate::Event::Deposit { who: 1, deposit: 50 })); + System::assert_last_event(Event::Balances(crate::Event::Deposit { who: 1, amount: 50 })); }); } diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 226cc087600b6..8544d966a7324 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -448,7 +448,7 @@ fn instantiate_and_call_and_deposit_event() { phase: Phase::Initialization, event: Event::Balances(pallet_balances::Event::Deposit { who: ALICE, - deposit: 1_000_000 + amount: 1_000_000 }), topics: vec![], }, @@ -483,7 +483,7 @@ fn instantiate_and_call_and_deposit_event() { event: Event::Balances(pallet_balances::Event::Transfer { from: ALICE, to: addr.clone(), - value: subsistence * 100 + amount: subsistence * 100 }), topics: vec![], }, @@ -774,7 +774,7 @@ fn self_destruct_works() { event: Event::Balances(pallet_balances::Event::Transfer { from: addr.clone(), to: DJANGO, - value: 100_000, + amount: 100_000, }), topics: vec![], }, diff --git a/frame/multisig/src/lib.rs b/frame/multisig/src/lib.rs index 65684dd391730..757a99b42dae8 100644 --- a/frame/multisig/src/lib.rs +++ b/frame/multisig/src/lib.rs @@ -205,17 +205,16 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// A new multisig operation has begun. \[approving, multisig, call_hash\] + /// A new multisig operation has begun. NewMultisig { approving: T::AccountId, multisig: T::AccountId, call_hash: CallHash }, /// A multisig operation has been approved by someone. - /// \[approving, timepoint, multisig, call_hash\] MultisigApproval { approving: T::AccountId, timepoint: Timepoint, multisig: T::AccountId, call_hash: CallHash, }, - /// A multisig operation has been executed. \[approving, timepoint, multisig, call_hash\] + /// A multisig operation has been executed. MultisigExecuted { approving: T::AccountId, timepoint: Timepoint, @@ -223,7 +222,7 @@ pub mod pallet { call_hash: CallHash, result: DispatchResult, }, - /// A multisig operation has been cancelled. \[cancelling, timepoint, multisig, call_hash\] + /// A multisig operation has been cancelled. MultisigCancelled { cancelling: T::AccountId, timepoint: Timepoint, diff --git a/frame/offences/benchmarking/src/lib.rs b/frame/offences/benchmarking/src/lib.rs index 5fd58b09d60bd..33ebe23d8d1fd 100644 --- a/frame/offences/benchmarking/src/lib.rs +++ b/frame/offences/benchmarking/src/lib.rs @@ -315,13 +315,13 @@ benchmarks! { ::Event::from(StakingEvent::::Slashed(id, BalanceOf::::from(slash_amount))) ); let balance_slash = |id| core::iter::once( - ::Event::from(pallet_balances::Event::::Slashed{who: id, amount_slashed: slash_amount.into()}) + ::Event::from(pallet_balances::Event::::Slashed{who: id, amount: slash_amount.into()}) ); let chill = |id| core::iter::once( ::Event::from(StakingEvent::::Chilled(id)) ); let balance_deposit = |id, amount: u32| - ::Event::from(pallet_balances::Event::::Deposit{who: id, deposit: amount.into()}); + ::Event::from(pallet_balances::Event::::Deposit{who: id, amount: amount.into()}); let mut first = true; let slash_events = raw_offenders.into_iter() .flat_map(|offender| { diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index 50c64c1f6ee2c..2d39104629fd4 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -407,7 +407,7 @@ fn filtering_works() { ); assert_ok!(Proxy::proxy(Origin::signed(2), 1, None, call.clone())); expect_events(vec![ - BalancesEvent::::Unreserved { who: 1, value: 5 }.into(), + BalancesEvent::::Unreserved { who: 1, amount: 5 }.into(), ProxyEvent::ProxyExecuted { result: Ok(()) }.into(), ]); }); diff --git a/frame/staking/src/slashing.rs b/frame/staking/src/slashing.rs index 68088d0e0d777..414c21aa347f0 100644 --- a/frame/staking/src/slashing.rs +++ b/frame/staking/src/slashing.rs @@ -190,7 +190,7 @@ pub(crate) struct SpanRecord { impl SpanRecord { /// The value of stash balance slashed in this span. #[cfg(test)] - pub(crate) fn amount_slashed(&self) -> &Balance { + pub(crate) fn amount(&self) -> &Balance { &self.slashed } } diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index d6d92d5bd57fc..1ab02f920f8ba 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -2535,7 +2535,7 @@ fn garbage_collection_after_slashing() { assert_eq!(Balances::free_balance(11), 2000 - 200); assert!(::SlashingSpans::get(&11).is_some()); - assert_eq!(::SpanSlash::get(&(11, 0)).amount_slashed(), &200); + assert_eq!(::SpanSlash::get(&(11, 0)).amount(), &200); on_offence_now( &[OffenceDetails { @@ -2562,7 +2562,7 @@ fn garbage_collection_after_slashing() { assert_ok!(Staking::reap_stash(Origin::none(), 11, 2)); assert!(::SlashingSpans::get(&11).is_none()); - assert_eq!(::SpanSlash::get(&(11, 0)).amount_slashed(), &0); + assert_eq!(::SpanSlash::get(&(11, 0)).amount(), &0); }) } diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index dd36a0ff162a6..50e33ba75b073 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -1322,7 +1322,7 @@ mod tests { System::assert_has_event(Event::Balances(pallet_balances::Event::Transfer { from: 2, to: 3, - value: 80, + amount: 80, })); // Killed Event System::assert_has_event(Event::System(system::Event::KilledAccount(2))); From b34a471680f39fa1bfdef51c06324728072c3ec2 Mon Sep 17 00:00:00 2001 From: david Date: Fri, 5 Nov 2021 10:35:24 +0100 Subject: [PATCH 08/11] fix assertion error --- frame/balances/src/tests_reentrancy.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/frame/balances/src/tests_reentrancy.rs b/frame/balances/src/tests_reentrancy.rs index 80716b306e6a6..7062d083b0ccb 100644 --- a/frame/balances/src/tests_reentrancy.rs +++ b/frame/balances/src/tests_reentrancy.rs @@ -219,7 +219,7 @@ fn transfer_dust_removal_tst2_should_work() { #[test] fn repatriating_reserved_balance_dust_removal_should_work() { - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { // Verification of reentrancy in dust removal assert_ok!(Balances::set_balance(RawOrigin::Root.into(), 1, 1000, 0)); assert_ok!(Balances::set_balance(RawOrigin::Root.into(), 2, 500, 0)); @@ -255,10 +255,11 @@ fn repatriating_reserved_balance_dust_removal_should_work() { destination_status: Status::Free, })); - System::assert_last_event(Event::Balances(crate::Event::DustLost { + System::assert_has_event(Event::Balances(crate::Event::DustLost { account: 2, amount: 50, })); + System::assert_last_event(Event::Balances(crate::Event::Deposit { who: 1, amount: 50 })); }); } From cb1731da5474903a50669d9058be8527215a5bbd Mon Sep 17 00:00:00 2001 From: david Date: Fri, 5 Nov 2021 10:56:23 +0100 Subject: [PATCH 09/11] minor fix --- frame/balances/src/tests_reentrancy.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/balances/src/tests_reentrancy.rs b/frame/balances/src/tests_reentrancy.rs index 7062d083b0ccb..43edd16baf3b3 100644 --- a/frame/balances/src/tests_reentrancy.rs +++ b/frame/balances/src/tests_reentrancy.rs @@ -219,7 +219,7 @@ fn transfer_dust_removal_tst2_should_work() { #[test] fn repatriating_reserved_balance_dust_removal_should_work() { - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { // Verification of reentrancy in dust removal assert_ok!(Balances::set_balance(RawOrigin::Root.into(), 1, 1000, 0)); assert_ok!(Balances::set_balance(RawOrigin::Root.into(), 2, 500, 0)); From 0128a1dfcbf6a519e18e25e56282c9bb03fd8348 Mon Sep 17 00:00:00 2001 From: david Date: Thu, 11 Nov 2021 19:22:37 +0100 Subject: [PATCH 10/11] formatting fix --- frame/assets/src/benchmarking.rs | 46 ++++++++++++++-------------- frame/bounties/src/benchmarking.rs | 6 ++-- frame/collective/src/benchmarking.rs | 16 +++++----- frame/democracy/src/benchmarking.rs | 2 +- frame/identity/src/benchmarking.rs | 8 ++--- frame/proxy/src/benchmarking.rs | 8 ++--- 6 files changed, 43 insertions(+), 43 deletions(-) diff --git a/frame/assets/src/benchmarking.rs b/frame/assets/src/benchmarking.rs index 121c9df0344c3..475864bac9430 100644 --- a/frame/assets/src/benchmarking.rs +++ b/frame/assets/src/benchmarking.rs @@ -155,7 +155,7 @@ benchmarks_instance_pallet! { T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup, 1u32.into()) verify { - assert_last_event::(Event::Created{asset_id: Default::default(), creator: caller.clone(), owner: caller}.into()); + assert_last_event::(Event::Created { asset_id: Default::default(), creator: caller.clone(), owner: caller }.into()); } force_create { @@ -163,7 +163,7 @@ benchmarks_instance_pallet! { let caller_lookup = T::Lookup::unlookup(caller.clone()); }: _(SystemOrigin::Root, Default::default(), caller_lookup, true, 1u32.into()) verify { - assert_last_event::(Event::ForceCreated{asset_id: Default::default(), owner: caller}.into()); + assert_last_event::(Event::ForceCreated { asset_id: Default::default(), owner: caller }.into()); } destroy { @@ -177,7 +177,7 @@ benchmarks_instance_pallet! { let witness = Asset::::get(T::AssetId::default()).unwrap().destroy_witness(); }: _(SystemOrigin::Signed(caller), Default::default(), witness) verify { - assert_last_event::(Event::Destroyed{asset_id: Default::default()}.into()); + assert_last_event::(Event::Destroyed { asset_id: Default::default() }.into()); } mint { @@ -185,7 +185,7 @@ benchmarks_instance_pallet! { let amount = T::Balance::from(100u32); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup, amount) verify { - assert_last_event::(Event::Issued{asset_id: Default::default(), owner: caller, total_supply: amount}.into()); + assert_last_event::(Event::Issued { asset_id: Default::default(), owner: caller, total_supply: amount }.into()); } burn { @@ -193,7 +193,7 @@ benchmarks_instance_pallet! { let (caller, caller_lookup) = create_default_minted_asset::(true, amount); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup, amount) verify { - assert_last_event::(Event::Burned{asset_id: Default::default(), owner: caller, balance: amount}.into()); + assert_last_event::(Event::Burned { asset_id: Default::default(), owner: caller, balance: amount }.into()); } transfer { @@ -203,7 +203,7 @@ benchmarks_instance_pallet! { let target_lookup = T::Lookup::unlookup(target.clone()); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), target_lookup, amount) verify { - assert_last_event::(Event::Transferred{asset_id: Default::default(), from: caller, to: target, amount}.into()); + assert_last_event::(Event::Transferred { asset_id: Default::default(), from: caller, to: target, amount }.into()); } transfer_keep_alive { @@ -215,7 +215,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Signed(caller.clone()), Default::default(), target_lookup, amount) verify { assert!(frame_system::Pallet::::account_exists(&caller)); - assert_last_event::(Event::Transferred{asset_id: Default::default(), from: caller, to: target, amount}.into()); + assert_last_event::(Event::Transferred { asset_id: Default::default(), from: caller, to: target, amount }.into()); } force_transfer { @@ -226,7 +226,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup, target_lookup, amount) verify { assert_last_event::( - Event::Transferred{asset_id: Default::default(), from: caller, to: target, amount}.into() + Event::Transferred { asset_id: Default::default(), from: caller, to: target, amount }.into() ); } @@ -234,7 +234,7 @@ benchmarks_instance_pallet! { let (caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup) verify { - assert_last_event::(Event::Frozen{asset_id: Default::default(), who: caller}.into()); + assert_last_event::(Event::Frozen { asset_id: Default::default(), who: caller }.into()); } thaw { @@ -246,14 +246,14 @@ benchmarks_instance_pallet! { )?; }: _(SystemOrigin::Signed(caller.clone()), Default::default(), caller_lookup) verify { - assert_last_event::(Event::Thawed{asset_id: Default::default(), who: caller}.into()); + assert_last_event::(Event::Thawed { asset_id: Default::default(), who: caller }.into()); } freeze_asset { let (caller, caller_lookup) = create_default_minted_asset::(true, 100u32.into()); }: _(SystemOrigin::Signed(caller.clone()), Default::default()) verify { - assert_last_event::(Event::AssetFrozen{asset_id: Default::default()}.into()); + assert_last_event::(Event::AssetFrozen { asset_id: Default::default() }.into()); } thaw_asset { @@ -264,7 +264,7 @@ benchmarks_instance_pallet! { )?; }: _(SystemOrigin::Signed(caller.clone()), Default::default()) verify { - assert_last_event::(Event::AssetThawed{asset_id: Default::default()}.into()); + assert_last_event::(Event::AssetThawed { asset_id: Default::default() }.into()); } transfer_ownership { @@ -273,7 +273,7 @@ benchmarks_instance_pallet! { let target_lookup = T::Lookup::unlookup(target.clone()); }: _(SystemOrigin::Signed(caller), Default::default(), target_lookup) verify { - assert_last_event::(Event::OwnerChanged{asset_id: Default::default(), owner: target}.into()); + assert_last_event::(Event::OwnerChanged { asset_id: Default::default(), owner: target }.into()); } set_team { @@ -283,7 +283,7 @@ benchmarks_instance_pallet! { let target2 = T::Lookup::unlookup(account("target", 2, SEED)); }: _(SystemOrigin::Signed(caller), Default::default(), target0.clone(), target1.clone(), target2.clone()) verify { - assert_last_event::(Event::TeamChanged{ + assert_last_event::(Event::TeamChanged { asset_id: Default::default(), issuer: account("target", 0, SEED), admin: account("target", 1, SEED), @@ -304,7 +304,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Signed(caller), Default::default(), name.clone(), symbol.clone(), decimals) verify { let id = Default::default(); - assert_last_event::(Event::MetadataSet{asset_id: id, name, symbol, decimals, is_frozen: false}.into()); + assert_last_event::(Event::MetadataSet { asset_id: id, name, symbol, decimals, is_frozen: false }.into()); } clear_metadata { @@ -315,7 +315,7 @@ benchmarks_instance_pallet! { Assets::::set_metadata(origin, Default::default(), dummy.clone(), dummy, 12)?; }: _(SystemOrigin::Signed(caller), Default::default()) verify { - assert_last_event::(Event::MetadataCleared{asset_id: Default::default()}.into()); + assert_last_event::(Event::MetadataCleared { asset_id: Default::default() }.into()); } force_set_metadata { @@ -339,7 +339,7 @@ benchmarks_instance_pallet! { }: { call.dispatch_bypass_filter(origin)? } verify { let id = Default::default(); - assert_last_event::(Event::MetadataSet{asset_id: id, name, symbol, decimals, is_frozen: false}.into()); + assert_last_event::(Event::MetadataSet { asset_id: id, name, symbol, decimals, is_frozen: false }.into()); } force_clear_metadata { @@ -353,7 +353,7 @@ benchmarks_instance_pallet! { let call = Call::::force_clear_metadata { id: Default::default() }; }: { call.dispatch_bypass_filter(origin)? } verify { - assert_last_event::(Event::MetadataCleared{asset_id: Default::default()}.into()); + assert_last_event::(Event::MetadataCleared { asset_id: Default::default() }.into()); } force_asset_status { @@ -372,7 +372,7 @@ benchmarks_instance_pallet! { }; }: { call.dispatch_bypass_filter(origin)? } verify { - assert_last_event::(Event::AssetStatusChanged{asset_id: Default::default()}.into()); + assert_last_event::(Event::AssetStatusChanged { asset_id: Default::default() }.into()); } approve_transfer { @@ -385,7 +385,7 @@ benchmarks_instance_pallet! { let amount = 100u32.into(); }: _(SystemOrigin::Signed(caller.clone()), id, delegate_lookup, amount) verify { - assert_last_event::(Event::ApprovedTransfer{asset_id: id, source: caller, delegate, amount}.into()); + assert_last_event::(Event::ApprovedTransfer { asset_id: id, source: caller, delegate, amount }.into()); } transfer_approved { @@ -405,7 +405,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Signed(delegate.clone()), id, owner_lookup, dest_lookup, amount) verify { assert!(T::Currency::reserved_balance(&owner).is_zero()); - assert_event::(Event::Transferred{asset_id: id, from: owner, to: dest, amount}.into()); + assert_event::(Event::Transferred { asset_id: id, from: owner, to: dest, amount }.into()); } cancel_approval { @@ -420,7 +420,7 @@ benchmarks_instance_pallet! { Assets::::approve_transfer(origin, id, delegate_lookup.clone(), amount)?; }: _(SystemOrigin::Signed(caller.clone()), id, delegate_lookup) verify { - assert_last_event::(Event::ApprovalCancelled{asset_id: id, owner: caller, delegate}.into()); + assert_last_event::(Event::ApprovalCancelled { asset_id: id, owner: caller, delegate }.into()); } force_cancel_approval { @@ -435,7 +435,7 @@ benchmarks_instance_pallet! { Assets::::approve_transfer(origin, id, delegate_lookup.clone(), amount)?; }: _(SystemOrigin::Signed(caller.clone()), id, caller_lookup, delegate_lookup) verify { - assert_last_event::(Event::ApprovalCancelled{asset_id: id, owner: caller, delegate}.into()); + assert_last_event::(Event::ApprovalCancelled { asset_id: id, owner: caller, delegate }.into()); } impl_benchmark_test_suite!(Assets, crate::mock::new_test_ext(), crate::mock::Test) diff --git a/frame/bounties/src/benchmarking.rs b/frame/bounties/src/benchmarking.rs index ce805e24d1c8a..341d019c49d47 100644 --- a/frame/bounties/src/benchmarking.rs +++ b/frame/bounties/src/benchmarking.rs @@ -172,7 +172,7 @@ benchmarks! { let bounty_id = BountyCount::::get() - 1; }: close_bounty(RawOrigin::Root, bounty_id) verify { - assert_last_event::(Event::BountyCanceled{index: bounty_id}.into()) + assert_last_event::(Event::BountyCanceled { index: bounty_id }.into()) } extend_bounty_expiry { @@ -184,7 +184,7 @@ benchmarks! { let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; }: _(RawOrigin::Signed(curator), bounty_id, Vec::new()) verify { - assert_last_event::(Event::BountyExtended{index: bounty_id}.into()) + assert_last_event::(Event::BountyExtended { index: bounty_id }.into()) } spend_funds { @@ -207,7 +207,7 @@ benchmarks! { verify { ensure!(budget_remaining < BalanceOf::::max_value(), "Budget not used"); ensure!(missed_any == false, "Missed some"); - assert_last_event::(Event::BountyBecameActive{index: b - 1}.into()) + assert_last_event::(Event::BountyBecameActive { index: b - 1 }.into()) } impl_benchmark_test_suite!(Bounties, crate::tests::new_test_ext(), crate::tests::Test) diff --git a/frame/collective/src/benchmarking.rs b/frame/collective/src/benchmarking.rs index d22e38d8f050f..5ca57cf72e8fc 100644 --- a/frame/collective/src/benchmarking.rs +++ b/frame/collective/src/benchmarking.rs @@ -128,7 +128,7 @@ benchmarks_instance_pallet! { let proposal_hash = T::Hashing::hash_of(&proposal); // Note that execution fails due to mis-matched origin assert_last_event::( - Event::MemberExecuted{proposal_hash, result: Err(DispatchError::BadOrigin)}.into() + Event::MemberExecuted { proposal_hash, result: Err(DispatchError::BadOrigin) }.into() ); } @@ -159,7 +159,7 @@ benchmarks_instance_pallet! { let proposal_hash = T::Hashing::hash_of(&proposal); // Note that execution fails due to mis-matched origin assert_last_event::( - Event::Executed{proposal_hash, result: Err(DispatchError::BadOrigin)}.into() + Event::Executed { proposal_hash, result: Err(DispatchError::BadOrigin) }.into() ); } @@ -203,7 +203,7 @@ benchmarks_instance_pallet! { // New proposal is recorded assert_eq!(Collective::::proposals().len(), p as usize); let proposal_hash = T::Hashing::hash_of(&proposal); - assert_last_event::(Event::Proposed{account: caller, proposal_index: p - 1, proposal_hash, threshold}.into()); + assert_last_event::(Event::Proposed { account: caller, proposal_index: p - 1, proposal_hash, threshold }.into()); } vote { @@ -359,7 +359,7 @@ benchmarks_instance_pallet! { verify { // The last proposal is removed. assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Disapproved{proposal_hash: last_hash}.into()); + assert_last_event::(Event::Disapproved { proposal_hash: last_hash }.into()); } close_early_approved { @@ -440,7 +440,7 @@ benchmarks_instance_pallet! { verify { // The last proposal is removed. assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Executed{proposal_hash: last_hash, result: Err(DispatchError::BadOrigin)}.into()); + assert_last_event::(Event::Executed { proposal_hash: last_hash, result: Err(DispatchError::BadOrigin) }.into()); } close_disapproved { @@ -514,7 +514,7 @@ benchmarks_instance_pallet! { }: close(SystemOrigin::Signed(caller), last_hash, index, Weight::max_value(), bytes_in_storage) verify { assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Disapproved{proposal_hash: last_hash}.into()); + assert_last_event::(Event::Disapproved { proposal_hash: last_hash }.into()); } close_approved { @@ -586,7 +586,7 @@ benchmarks_instance_pallet! { }: close(SystemOrigin::Signed(caller), last_hash, p - 1, Weight::max_value(), bytes_in_storage) verify { assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Executed{proposal_hash: last_hash, result: Err(DispatchError::BadOrigin)}.into()); + assert_last_event::(Event::Executed { proposal_hash: last_hash, result: Err(DispatchError::BadOrigin) }.into()); } disapprove_proposal { @@ -634,7 +634,7 @@ benchmarks_instance_pallet! { }: _(SystemOrigin::Root, last_hash) verify { assert_eq!(Collective::::proposals().len(), (p - 1) as usize); - assert_last_event::(Event::Disapproved{proposal_hash: last_hash}.into()); + assert_last_event::(Event::Disapproved { proposal_hash: last_hash }.into()); } impl_benchmark_test_suite!(Collective, crate::tests::new_test_ext(), crate::tests::Test); diff --git a/frame/democracy/src/benchmarking.rs b/frame/democracy/src/benchmarking.rs index 88cd64cfbebd9..136c2d2a7c9e2 100644 --- a/frame/democracy/src/benchmarking.rs +++ b/frame/democracy/src/benchmarking.rs @@ -774,7 +774,7 @@ benchmarks! { }: enact_proposal(RawOrigin::Root, proposal_hash, 0) verify { // Fails due to mismatched origin - assert_last_event::(Event::::Executed{ref_index: 0, result: Err(BadOrigin.into())}.into()); + assert_last_event::(Event::::Executed { ref_index: 0, result: Err(BadOrigin.into()) }.into()); } #[extra] diff --git a/frame/identity/src/benchmarking.rs b/frame/identity/src/benchmarking.rs index df7aba72fd958..db257fec43a13 100644 --- a/frame/identity/src/benchmarking.rs +++ b/frame/identity/src/benchmarking.rs @@ -153,7 +153,7 @@ benchmarks! { }; }: _(RawOrigin::Signed(caller.clone()), Box::new(create_identity_info::(x))) verify { - assert_last_event::(Event::::IdentitySet{who: caller}.into()); + assert_last_event::(Event::::IdentitySet { who: caller }.into()); } // We need to split `set_subs` into two benchmarks to accurately isolate the potential @@ -237,7 +237,7 @@ benchmarks! { }; }: _(RawOrigin::Signed(caller.clone()), r - 1, 10u32.into()) verify { - assert_last_event::(Event::::JudgementRequested{who: caller, registrar_index: r-1}.into()); + assert_last_event::(Event::::JudgementRequested { who: caller, registrar_index: r-1 }.into()); } cancel_request { @@ -257,7 +257,7 @@ benchmarks! { Identity::::request_judgement(caller_origin, r - 1, 10u32.into())?; }: _(RawOrigin::Signed(caller.clone()), r - 1) verify { - assert_last_event::(Event::::JudgementUnrequested{who: caller, registrar_index: r-1}.into()); + assert_last_event::(Event::::JudgementUnrequested { who: caller, registrar_index: r-1 }.into()); } set_fee { @@ -328,7 +328,7 @@ benchmarks! { Identity::::request_judgement(user_origin.clone(), r, 10u32.into())?; }: _(RawOrigin::Signed(caller), r, user_lookup, Judgement::Reasonable) verify { - assert_last_event::(Event::::JudgementGiven{target: user, registrar_index: r}.into()) + assert_last_event::(Event::::JudgementGiven { target: user, registrar_index: r }.into()) } kill_identity { diff --git a/frame/proxy/src/benchmarking.rs b/frame/proxy/src/benchmarking.rs index 4a0b55b211d35..224610b65185b 100644 --- a/frame/proxy/src/benchmarking.rs +++ b/frame/proxy/src/benchmarking.rs @@ -86,7 +86,7 @@ benchmarks! { let call: ::Call = frame_system::Call::::remark { remark: vec![] }.into(); }: _(RawOrigin::Signed(caller), real, Some(T::ProxyType::default()), Box::new(call)) verify { - assert_last_event::(Event::ProxyExecuted{result: Ok(())}.into()) + assert_last_event::(Event::ProxyExecuted { result: Ok(()) }.into()) } proxy_announced { @@ -107,7 +107,7 @@ benchmarks! { add_announcements::(a, Some(delegate.clone()), None)?; }: _(RawOrigin::Signed(caller), delegate, real, Some(T::ProxyType::default()), Box::new(call)) verify { - assert_last_event::(Event::ProxyExecuted{result: Ok(())}.into()) + assert_last_event::(Event::ProxyExecuted { result: Ok(()) }.into()) } remove_announcement { @@ -165,7 +165,7 @@ benchmarks! { let call_hash = T::CallHasher::hash_of(&call); }: _(RawOrigin::Signed(caller.clone()), real.clone(), call_hash) verify { - assert_last_event::(Event::Announced{real, proxy: caller, call_hash}.into()); + assert_last_event::(Event::Announced { real, proxy: caller, call_hash }.into()); } add_proxy { @@ -216,7 +216,7 @@ benchmarks! { ) verify { let anon_account = Pallet::::anonymous_account(&caller, &T::ProxyType::default(), 0, None); - assert_last_event::(Event::AnonymousCreated{ + assert_last_event::(Event::AnonymousCreated { anonymous: anon_account, who: caller, proxy_type: T::ProxyType::default(), From 510d0531ba79cb4ab0795da3c6d2d4f8f88401ed Mon Sep 17 00:00:00 2001 From: david Date: Fri, 12 Nov 2021 17:30:49 +0100 Subject: [PATCH 11/11] fmt --- frame/balances/src/tests.rs | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/frame/balances/src/tests.rs b/frame/balances/src/tests.rs index d833e09215fd2..1f7f4dd03716d 100644 --- a/frame/balances/src/tests.rs +++ b/frame/balances/src/tests.rs @@ -314,7 +314,7 @@ macro_rules! decl_tests { <$ext_builder>::default().monied(true).build().execute_with(|| { assert_eq!(Balances::total_balance(&1), 10); assert_ok!(Balances::deposit_into_existing(&1, 10).map(drop)); - System::assert_last_event(Event::Balances(crate::Event::Deposit{who: 1, amount: 10})); + System::assert_last_event(Event::Balances(crate::Event::Deposit { who: 1, amount: 10 })); assert_eq!(Balances::total_balance(&1), 20); assert_eq!(>::get(), 120); }); @@ -342,7 +342,7 @@ macro_rules! decl_tests { fn balance_works() { <$ext_builder>::default().build().execute_with(|| { let _ = Balances::deposit_creating(&1, 42); - System::assert_has_event(Event::Balances(crate::Event::Deposit{who: 1, amount: 42})); + System::assert_has_event(Event::Balances(crate::Event::Deposit { who: 1, amount: 42 })); assert_eq!(Balances::free_balance(1), 42); assert_eq!(Balances::reserved_balance(1), 0); assert_eq!(Balances::total_balance(&1), 42); @@ -444,7 +444,7 @@ macro_rules! decl_tests { let _ = Balances::withdraw( &2, 11, WithdrawReasons::TRANSFER, ExistenceRequirement::KeepAlive ); - System::assert_last_event(Event::Balances(crate::Event::Withdraw{who: 2, amount: 11})); + System::assert_last_event(Event::Balances(crate::Event::Withdraw { who: 2, amount: 11 })); assert_eq!(Balances::free_balance(2), 100); assert_eq!(>::get(), 100); }); @@ -505,7 +505,7 @@ macro_rules! decl_tests { assert_ok!(Balances::reserve(&1, 110)); assert_ok!(Balances::repatriate_reserved(&1, &2, 41, Status::Free), 0); System::assert_last_event( - Event::Balances(crate::Event::ReserveRepatriated{from: 1, to: 2, amount: 41, destination_status: Status::Free}) + Event::Balances(crate::Event::ReserveRepatriated { from: 1, to: 2, amount: 41, destination_status: Status::Free }) ); assert_eq!(Balances::reserved_balance(1), 69); assert_eq!(Balances::free_balance(1), 0); @@ -724,18 +724,18 @@ macro_rules! decl_tests { System::set_block_number(2); assert_ok!(Balances::reserve(&1, 10)); - System::assert_last_event(Event::Balances(crate::Event::Reserved{who: 1, amount: 10})); + System::assert_last_event(Event::Balances(crate::Event::Reserved { who: 1, amount: 10 })); System::set_block_number(3); assert!(Balances::unreserve(&1, 5).is_zero()); - System::assert_last_event(Event::Balances(crate::Event::Unreserved{who: 1, amount: 5})); + System::assert_last_event(Event::Balances(crate::Event::Unreserved { who: 1, amount: 5 })); System::set_block_number(4); assert_eq!(Balances::unreserve(&1, 6), 1); // should only unreserve 5 - System::assert_last_event(Event::Balances(crate::Event::Unreserved{who: 1, amount: 5})); + System::assert_last_event(Event::Balances(crate::Event::Unreserved { who: 1, amount: 5 })); }); } @@ -751,8 +751,8 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::NewAccount(1)), - Event::Balances(crate::Event::Endowed{account: 1, free_balance: 100}), - Event::Balances(crate::Event::BalanceSet{who: 1, free: 100, reserved: 0}), + Event::Balances(crate::Event::Endowed { account: 1, free_balance: 100 }), + Event::Balances(crate::Event::BalanceSet { who: 1, free: 100, reserved: 0 }), ] ); @@ -763,8 +763,8 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::KilledAccount(1)), - Event::Balances(crate::Event::DustLost{account: 1, amount: 99}), - Event::Balances(crate::Event::Slashed{who: 1, amount: 1}), + Event::Balances(crate::Event::DustLost { account: 1, amount: 99 }), + Event::Balances(crate::Event::Slashed { who: 1, amount: 1 }), ] ); }); @@ -782,8 +782,8 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::NewAccount(1)), - Event::Balances(crate::Event::Endowed{account: 1, free_balance: 100}), - Event::Balances(crate::Event::BalanceSet{who: 1, free: 100, reserved: 0}), + Event::Balances(crate::Event::Endowed { account: 1, free_balance: 100 }), + Event::Balances(crate::Event::BalanceSet { who: 1, free: 100, reserved: 0 }), ] ); @@ -794,7 +794,7 @@ macro_rules! decl_tests { events(), [ Event::System(system::Event::KilledAccount(1)), - Event::Balances(crate::Event::Slashed{who: 1, amount: 100}), + Event::Balances(crate::Event::Slashed { who: 1, amount: 100 }), ] ); }); @@ -814,7 +814,7 @@ macro_rules! decl_tests { assert_eq!(Balances::slash(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive assert!(System::account_exists(&1)); - System::assert_last_event(Event::Balances(crate::Event::Slashed{who: 1, amount: 900})); + System::assert_last_event(Event::Balances(crate::Event::Slashed { who: 1, amount: 900 })); // SCENARIO: Slash will kill account because not enough balance left. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0));