Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions frame/support/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@
//!
//! NOTE: If you're looking for `parameter_types`, it has moved in to the top-level module.

use sp_std::{prelude::*, result, marker::PhantomData, ops::Div, fmt::Debug};
use codec::{FullCodec, Codec, Encode, Decode};
use codec::{Codec, Decode, Encode, FullCodec};
use sp_core::u32_trait::Value as U32;
use sp_runtime::{
RuntimeDebug,
ConsensusEngineId, DispatchResult, DispatchError,
traits::{MaybeSerializeDeserialize, AtLeast32Bit, Saturating, TrailingZeroInput},
traits::{AtLeast32Bit, MaybeSerializeDeserialize, Saturating, TrailingZeroInput},
ConsensusEngineId, DispatchError, DispatchResult, RuntimeDebug,
};
use sp_std::{fmt::Debug, marker::PhantomData, ops::Div, prelude::*, result};

use crate::dispatch::Parameter;
use crate::storage::StorageMap;
Expand Down
67 changes: 66 additions & 1 deletion frame/system/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ use sp_runtime::{
self, CheckEqual, AtLeast32Bit, Zero, SignedExtension, Lookup, LookupError,
SimpleBitOps, Hash, Member, MaybeDisplay, EnsureOrigin, BadOrigin, SaturatedConversion,
MaybeSerialize, MaybeSerializeDeserialize, MaybeMallocSizeOf, StaticLookup, One, Bounded,
Dispatchable
},
};

Expand All @@ -118,7 +119,7 @@ use frame_support::{
Contains, Get, ModuleToIndex, OnNewAccount, OnKilledAccount, IsDeadAccount, Happened,
StoredMap
},
weights::{Weight, DispatchInfo, DispatchClass, SimpleDispatchInfo, FunctionOf},
weights::{Weight, DispatchInfo, GetDispatchInfo, DispatchClass, SimpleDispatchInfo, FunctionOf},
};
use codec::{Encode, Decode, FullCodec, EncodeLike};

Expand Down Expand Up @@ -348,6 +349,9 @@ decl_storage! {
/// Total weight for all extrinsics put together, for the current block.
AllExtrinsicsWeight: Option<Weight>;

/// The weight taken by the current executing disptachable.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo: disptachable

CurrentDispatchableWeight: Option<Weight>;

/// Total length (in bytes) for all extrinsics put together, for the current block.
AllExtrinsicsLen: Option<u32>;

Expand Down Expand Up @@ -1022,6 +1026,57 @@ impl<T: Trait> Module<T> {
}
}

impl<T: Trait> Module<T> {
pub fn spent_weight() -> Option<Weight> {
CurrentDispatchableWeight::get()
}

/// Decrease the amount of weight consumed by the current dispatchable.
///
/// This function can only meaningfully called within `Self::dispatch`. Otherwise,
/// it does nothing and returns `Err`.
///
/// The total weight returned from the dispatchable cannot exceed its total requested weight.
pub fn return_unspent_weight(unspent: Weight) -> Result<(), ()> {
let weight = CurrentDispatchableWeight::take().ok_or(())?;
let next_weight = weight.checked_sub(unspent).ok_or(())?;
CurrentDispatchableWeight::put(next_weight);
Ok(())
}
}

impl<T: Trait> Module<T>
where
<T as Trait>::Call: GetDispatchInfo + Dispatchable,
{
/// Dispatch a given `T::Call` with a given origin.
///
/// Returns how much weight was actually unspent by the call.
pub fn dispatch_call(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub fn dispatch_call(
pub fn note_dispatch_call(

There should really be an emphasis on the fact that this some bookkeeping for you. Chose some other name if you want, but dispatch_call is too simple.

origin: <T::Call as Dispatchable>::Origin,
call: T::Call,
) -> (Weight, sp_runtime::DispatchResult) {
// First, replace the current weight counter with the incoming call weight.
let prev_weight = CurrentDispatchableWeight::get();
let call_weight = call.get_dispatch_info().weight;
CurrentDispatchableWeight::put(call_weight);

// Then, dispatch the call.
let result = call.dispatch(origin);

// Finally, get the actual spent weight.
let spent_weight = CurrentDispatchableWeight::take().unwrap_or_default();
if let Some(prev_weight) = prev_weight {
CurrentDispatchableWeight::put(prev_weight);
} else {
CurrentDispatchableWeight::kill();
}

let unspent_weight = call_weight.saturating_sub(spent_weight);
(unspent_weight, result)
}
}

/// Event handler which calls on_created_account when it happens.
pub struct CallOnCreatedAccount<T>(PhantomData<T>);
impl<T: Trait> Happened<T::AccountId> for CallOnCreatedAccount<T> {
Expand Down Expand Up @@ -1246,6 +1301,16 @@ impl<T: Trait + Send + Sync> SignedExtension for CheckWeight<T> {
) -> TransactionValidity {
Self::do_validate(info, len)
}

fn post_dispatch(_pre: Self::Pre, info: Self::DispatchInfo, _len: usize) {
let spent = CurrentDispatchableWeight::get().unwrap_or(info.weight);
let reserved = info.weight;
let unspent = spent - reserved;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a comment why unchecked math is OK here is in order.

AllExtrinsicsWeight::mutate(|weight| {
let next_weight = weight.map(|weight| weight - unspent);
*weight = next_weight;
});
}
}

impl<T: Trait + Send + Sync> Debug for CheckWeight<T> {
Expand Down
Loading