Use named events in cumulus pallets (#1260)

* Use named events

* For now standardise on message_id

* cargo fmt

* reverting xcm changes

* remove superfluous comments

* renaming

* updating benches
This commit is contained in:
Squirrel
2022-05-23 09:23:27 +01:00
committed by GitHub
parent 12221cb534
commit c7ef5f6a6b
5 changed files with 68 additions and 58 deletions
@@ -117,7 +117,7 @@ benchmarks! {
); );
} }
verify { verify {
assert_last_event::<T>(Event::NewInvulnerables(new_invulnerables).into()); assert_last_event::<T>(Event::NewInvulnerables{invulnerables: new_invulnerables}.into());
} }
set_desired_candidates { set_desired_candidates {
@@ -129,19 +129,19 @@ benchmarks! {
); );
} }
verify { verify {
assert_last_event::<T>(Event::NewDesiredCandidates(max).into()); assert_last_event::<T>(Event::NewDesiredCandidates{desired_candidates: max}.into());
} }
set_candidacy_bond { set_candidacy_bond {
let bond: BalanceOf<T> = T::Currency::minimum_balance() * 10u32.into(); let bond_amount: BalanceOf<T> = T::Currency::minimum_balance() * 10u32.into();
let origin = T::UpdateOrigin::successful_origin(); let origin = T::UpdateOrigin::successful_origin();
}: { }: {
assert_ok!( assert_ok!(
<CollatorSelection<T>>::set_candidacy_bond(origin, bond.clone()) <CollatorSelection<T>>::set_candidacy_bond(origin, bond_amount.clone())
); );
} }
verify { verify {
assert_last_event::<T>(Event::NewCandidacyBond(bond).into()); assert_last_event::<T>(Event::NewCandidacyBond{bond_amount}.into());
} }
// worse case is when we have all the max-candidate slots filled except one, and we fill that // worse case is when we have all the max-candidate slots filled except one, and we fill that
@@ -167,7 +167,7 @@ benchmarks! {
}: _(RawOrigin::Signed(caller.clone())) }: _(RawOrigin::Signed(caller.clone()))
verify { verify {
assert_last_event::<T>(Event::CandidateAdded(caller, bond / 2u32.into()).into()); assert_last_event::<T>(Event::CandidateAdded{account_id: caller, deposit: bond / 2u32.into()}.into());
} }
// worse case is the last candidate leaving. // worse case is the last candidate leaving.
@@ -183,7 +183,7 @@ benchmarks! {
whitelist!(leaving); whitelist!(leaving);
}: _(RawOrigin::Signed(leaving.clone())) }: _(RawOrigin::Signed(leaving.clone()))
verify { verify {
assert_last_event::<T>(Event::CandidateRemoved(leaving).into()); assert_last_event::<T>(Event::CandidateRemoved{account_id: leaving}.into());
} }
// worse case is paying a non-existing candidate account. // worse case is paying a non-existing candidate account.
+10 -10
View File
@@ -248,11 +248,11 @@ pub mod pallet {
#[pallet::event] #[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> { pub enum Event<T: Config> {
NewInvulnerables(Vec<T::AccountId>), NewInvulnerables { invulnerables: Vec<T::AccountId> },
NewDesiredCandidates(u32), NewDesiredCandidates { desired_candidates: u32 },
NewCandidacyBond(BalanceOf<T>), NewCandidacyBond { bond_amount: BalanceOf<T> },
CandidateAdded(T::AccountId, BalanceOf<T>), CandidateAdded { account_id: T::AccountId, deposit: BalanceOf<T> },
CandidateRemoved(T::AccountId), CandidateRemoved { account_id: T::AccountId },
} }
// Errors inform users that something went wrong. // Errors inform users that something went wrong.
@@ -308,7 +308,7 @@ pub mod pallet {
} }
<Invulnerables<T>>::put(&new); <Invulnerables<T>>::put(&new);
Self::deposit_event(Event::NewInvulnerables(new)); Self::deposit_event(Event::NewInvulnerables { invulnerables: new });
Ok(().into()) Ok(().into())
} }
@@ -326,7 +326,7 @@ pub mod pallet {
log::warn!("max > T::MaxCandidates; you might need to run benchmarks again"); log::warn!("max > T::MaxCandidates; you might need to run benchmarks again");
} }
<DesiredCandidates<T>>::put(&max); <DesiredCandidates<T>>::put(&max);
Self::deposit_event(Event::NewDesiredCandidates(max)); Self::deposit_event(Event::NewDesiredCandidates { desired_candidates: max });
Ok(().into()) Ok(().into())
} }
@@ -338,7 +338,7 @@ pub mod pallet {
) -> DispatchResultWithPostInfo { ) -> DispatchResultWithPostInfo {
T::UpdateOrigin::ensure_origin(origin)?; T::UpdateOrigin::ensure_origin(origin)?;
<CandidacyBond<T>>::put(&bond); <CandidacyBond<T>>::put(&bond);
Self::deposit_event(Event::NewCandidacyBond(bond)); Self::deposit_event(Event::NewCandidacyBond { bond_amount: bond });
Ok(().into()) Ok(().into())
} }
@@ -381,7 +381,7 @@ pub mod pallet {
} }
})?; })?;
Self::deposit_event(Event::CandidateAdded(who, deposit)); Self::deposit_event(Event::CandidateAdded { account_id: who, deposit });
Ok(Some(T::WeightInfo::register_as_candidate(current_count as u32)).into()) Ok(Some(T::WeightInfo::register_as_candidate(current_count as u32)).into())
} }
@@ -423,7 +423,7 @@ pub mod pallet {
<LastAuthoredBlock<T>>::remove(who.clone()); <LastAuthoredBlock<T>>::remove(who.clone());
Ok(candidates.len()) Ok(candidates.len())
})?; })?;
Self::deposit_event(Event::CandidateRemoved(who.clone())); Self::deposit_event(Event::CandidateRemoved { account_id: who.clone() });
Ok(current_count) Ok(current_count)
} }
+34 -30
View File
@@ -149,11 +149,11 @@ pub mod pallet {
T::ExecuteOverweightOrigin::ensure_origin(origin)?; T::ExecuteOverweightOrigin::ensure_origin(origin)?;
let (sent_at, data) = Overweight::<T>::get(index).ok_or(Error::<T>::Unknown)?; let (sent_at, data) = Overweight::<T>::get(index).ok_or(Error::<T>::Unknown)?;
let used = Self::try_service_message(weight_limit, sent_at, &data[..]) let weight_used = Self::try_service_message(weight_limit, sent_at, &data[..])
.map_err(|_| Error::<T>::OverLimit)?; .map_err(|_| Error::<T>::OverLimit)?;
Overweight::<T>::remove(index); Overweight::<T>::remove(index);
Self::deposit_event(Event::OverweightServiced(index, used)); Self::deposit_event(Event::OverweightServiced { overweight_index: index, weight_used });
Ok(Some(used.saturating_add(1_000_000)).into()) Ok(Some(weight_used.saturating_add(1_000_000)).into())
} }
} }
@@ -161,23 +161,21 @@ pub mod pallet {
#[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> { pub enum Event<T: Config> {
/// Downward message is invalid XCM. /// Downward message is invalid XCM.
/// \[ id \] InvalidFormat { message_id: MessageId },
InvalidFormat(MessageId),
/// Downward message is unsupported version of XCM. /// Downward message is unsupported version of XCM.
/// \[ id \] UnsupportedVersion { message_id: MessageId },
UnsupportedVersion(MessageId),
/// Downward message executed with the given outcome. /// Downward message executed with the given outcome.
/// \[ id, outcome \] ExecutedDownward { message_id: MessageId, outcome: Outcome },
ExecutedDownward(MessageId, Outcome),
/// The weight limit for handling downward messages was reached. /// The weight limit for handling downward messages was reached.
/// \[ id, remaining, required \] WeightExhausted { message_id: MessageId, remaining_weight: Weight, required_weight: Weight },
WeightExhausted(MessageId, Weight, Weight),
/// Downward message is overweight and was placed in the overweight queue. /// Downward message is overweight and was placed in the overweight queue.
/// \[ id, index, required \] OverweightEnqueued {
OverweightEnqueued(MessageId, OverweightIndex, Weight), message_id: MessageId,
overweight_index: OverweightIndex,
required_weight: Weight,
},
/// Downward message from the overweight queue was executed. /// Downward message from the overweight queue was executed.
/// \[ index, used \] OverweightServiced { overweight_index: OverweightIndex, weight_used: Weight },
OverweightServiced(OverweightIndex, Weight),
} }
impl<T: Config> Pallet<T> { impl<T: Config> Pallet<T> {
@@ -225,7 +223,7 @@ pub mod pallet {
_sent_at: RelayBlockNumber, _sent_at: RelayBlockNumber,
mut data: &[u8], mut data: &[u8],
) -> Result<Weight, (MessageId, Weight)> { ) -> Result<Weight, (MessageId, Weight)> {
let id = sp_io::hashing::blake2_256(data); let message_id = sp_io::hashing::blake2_256(data);
let maybe_msg = VersionedXcm::<T::Call>::decode_all_with_depth_limit( let maybe_msg = VersionedXcm::<T::Call>::decode_all_with_depth_limit(
MAX_XCM_DECODE_DEPTH, MAX_XCM_DECODE_DEPTH,
&mut data, &mut data,
@@ -233,21 +231,21 @@ pub mod pallet {
.map(Xcm::<T::Call>::try_from); .map(Xcm::<T::Call>::try_from);
match maybe_msg { match maybe_msg {
Err(_) => { Err(_) => {
Self::deposit_event(Event::InvalidFormat(id)); Self::deposit_event(Event::InvalidFormat { message_id });
Ok(0) Ok(0)
}, },
Ok(Err(())) => { Ok(Err(())) => {
Self::deposit_event(Event::UnsupportedVersion(id)); Self::deposit_event(Event::UnsupportedVersion { message_id });
Ok(0) Ok(0)
}, },
Ok(Ok(x)) => { Ok(Ok(x)) => {
let outcome = T::XcmExecutor::execute_xcm(Parent, x, limit); let outcome = T::XcmExecutor::execute_xcm(Parent, x, limit);
match outcome { match outcome {
Outcome::Error(XcmError::WeightLimitReached(required)) => Outcome::Error(XcmError::WeightLimitReached(required)) =>
Err((id, required)), Err((message_id, required)),
outcome => { outcome => {
let weight_used = outcome.weight_used(); let weight_used = outcome.weight_used();
Self::deposit_event(Event::ExecutedDownward(id, outcome)); Self::deposit_event(Event::ExecutedDownward { message_id, outcome });
Ok(weight_used) Ok(weight_used)
}, },
} }
@@ -283,18 +281,22 @@ pub mod pallet {
for (i, (sent_at, data)) in iter.enumerate() { for (i, (sent_at, data)) in iter.enumerate() {
if maybe_enqueue_page.is_none() { if maybe_enqueue_page.is_none() {
// We're not currently enqueuing - try to execute inline. // We're not currently enqueuing - try to execute inline.
let remaining = limit.saturating_sub(used); let remaining_weight = limit.saturating_sub(used);
match Self::try_service_message(remaining, sent_at, &data[..]) { match Self::try_service_message(remaining_weight, sent_at, &data[..]) {
Ok(consumed) => used += consumed, Ok(consumed) => used += consumed,
Err((id, required)) => Err((message_id, required_weight)) =>
// Too much weight required right now. // Too much weight required right now.
{ {
if required > config.max_individual { if required_weight > config.max_individual {
// overweight - add to overweight queue and continue with // overweight - add to overweight queue and continue with
// message execution. // message execution.
let index = page_index.overweight_count; let overweight_index = page_index.overweight_count;
Overweight::<T>::insert(index, (sent_at, data)); Overweight::<T>::insert(overweight_index, (sent_at, data));
Self::deposit_event(Event::OverweightEnqueued(id, index, required)); Self::deposit_event(Event::OverweightEnqueued {
message_id,
overweight_index,
required_weight,
});
page_index.overweight_count += 1; page_index.overweight_count += 1;
// Not needed for control flow, but only to ensure that the compiler // Not needed for control flow, but only to ensure that the compiler
// understands that we won't attempt to re-use `data` later. // understands that we won't attempt to re-use `data` later.
@@ -304,9 +306,11 @@ pub mod pallet {
// from here on. // from here on.
let item_count_left = item_count.saturating_sub(i); let item_count_left = item_count.saturating_sub(i);
maybe_enqueue_page = Some(Vec::with_capacity(item_count_left)); maybe_enqueue_page = Some(Vec::with_capacity(item_count_left));
Self::deposit_event(Event::WeightExhausted( Self::deposit_event(Event::WeightExhausted {
id, remaining, required, message_id,
)); remaining_weight,
required_weight,
});
} }
}, },
} }
+13 -10
View File
@@ -330,7 +330,9 @@ pub mod pallet {
Self::put_parachain_code(&validation_code); Self::put_parachain_code(&validation_code);
<T::OnSystemEvent as OnSystemEvent>::on_validation_code_applied(); <T::OnSystemEvent as OnSystemEvent>::on_validation_code_applied();
Self::deposit_event(Event::ValidationFunctionApplied(vfp.relay_parent_number)); Self::deposit_event(Event::ValidationFunctionApplied {
relay_chain_block_num: vfp.relay_parent_number,
});
}, },
Some(relay_chain::v2::UpgradeGoAhead::Abort) => { Some(relay_chain::v2::UpgradeGoAhead::Abort) => {
<PendingValidationCode<T>>::kill(); <PendingValidationCode<T>>::kill();
@@ -389,7 +391,7 @@ pub mod pallet {
AuthorizedUpgrade::<T>::put(&code_hash); AuthorizedUpgrade::<T>::put(&code_hash);
Self::deposit_event(Event::UpgradeAuthorized(code_hash)); Self::deposit_event(Event::UpgradeAuthorized { code_hash });
Ok(()) Ok(())
} }
@@ -411,17 +413,15 @@ pub mod pallet {
/// The validation function has been scheduled to apply. /// The validation function has been scheduled to apply.
ValidationFunctionStored, ValidationFunctionStored,
/// The validation function was applied as of the contained relay chain block number. /// The validation function was applied as of the contained relay chain block number.
ValidationFunctionApplied(RelayChainBlockNumber), ValidationFunctionApplied { relay_chain_block_num: RelayChainBlockNumber },
/// The relay-chain aborted the upgrade process. /// The relay-chain aborted the upgrade process.
ValidationFunctionDiscarded, ValidationFunctionDiscarded,
/// An upgrade has been authorized. /// An upgrade has been authorized.
UpgradeAuthorized(T::Hash), UpgradeAuthorized { code_hash: T::Hash },
/// Some downward messages have been received and will be processed. /// Some downward messages have been received and will be processed.
/// \[ count \] DownwardMessagesReceived { count: u32 },
DownwardMessagesReceived(u32),
/// Downward messages were processed using the given weight. /// Downward messages were processed using the given weight.
/// \[ weight_used, result_mqc_head \] DownwardMessagesProcessed { weight_used: Weight, dmq_head: relay_chain::Hash },
DownwardMessagesProcessed(Weight, relay_chain::Hash),
} }
#[pallet::error] #[pallet::error]
@@ -750,7 +750,7 @@ impl<T: Config> Pallet<T> {
let mut weight_used = 0; let mut weight_used = 0;
if dm_count != 0 { if dm_count != 0 {
Self::deposit_event(Event::DownwardMessagesReceived(dm_count)); Self::deposit_event(Event::DownwardMessagesReceived { count: dm_count });
let max_weight = let max_weight =
<ReservedDmpWeightOverride<T>>::get().unwrap_or_else(T::ReservedDmpWeight::get); <ReservedDmpWeightOverride<T>>::get().unwrap_or_else(T::ReservedDmpWeight::get);
@@ -763,7 +763,10 @@ impl<T: Config> Pallet<T> {
weight_used += T::DmpMessageHandler::handle_dmp_messages(message_iter, max_weight); weight_used += T::DmpMessageHandler::handle_dmp_messages(message_iter, max_weight);
<LastDmqMqcHead<T>>::put(&dmq_head); <LastDmqMqcHead<T>>::put(&dmq_head);
Self::deposit_event(Event::DownwardMessagesProcessed(weight_used, dmq_head.head())); Self::deposit_event(Event::DownwardMessagesProcessed {
weight_used,
dmq_head: dmq_head.head(),
});
} }
// After hashing each message in the message queue chain submitted by the collator, we // After hashing each message in the message queue chain submitted by the collator, we
@@ -415,7 +415,10 @@ fn events() {
let events = System::events(); let events = System::events();
assert_eq!( assert_eq!(
events[0].event, events[0].event,
Event::ParachainSystem(crate::Event::ValidationFunctionApplied(1234).into()) Event::ParachainSystem(
crate::Event::ValidationFunctionApplied { relay_chain_block_num: 1234 }
.into()
)
); );
}, },
); );