#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use codec::{Decode, Encode};
use cumulus_primitives_storage_weight_reclaim::get_proof_size;
use derivative::Derivative;
use frame_support::{
dispatch::{DispatchInfo, PostDispatchInfo},
pallet_prelude::Weight,
traits::Defensive,
};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{DispatchInfoOf, Dispatchable, Implication, PostDispatchInfoOf, TransactionExtension},
transaction_validity::{TransactionSource, TransactionValidityError, ValidTransaction},
DispatchResult,
};
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarks;
#[cfg(test)]
mod tests;
mod weights;
pub use pallet::*;
pub use weights::WeightInfo;
const LOG_TARGET: &'static str = "runtime::storage_reclaim_pallet";
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type WeightInfo: WeightInfo;
}
}
#[doc = docify::embed!("./src/tests.rs", Tx)]
#[derive(Encode, Decode, TypeInfo, Derivative)]
#[derivative(
Clone(bound = "S: Clone"),
Eq(bound = "S: Eq"),
PartialEq(bound = "S: PartialEq"),
Default(bound = "S: Default")
)]
#[scale_info(skip_type_params(T))]
pub struct StorageWeightReclaim<T, S>(pub S, core::marker::PhantomData<T>);
impl<T, S> StorageWeightReclaim<T, S> {
pub fn new(s: S) -> Self {
Self(s, Default::default())
}
}
impl<T, S> From<S> for StorageWeightReclaim<T, S> {
fn from(s: S) -> Self {
Self::new(s)
}
}
impl<T, S: core::fmt::Debug> core::fmt::Debug for StorageWeightReclaim<T, S> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
#[cfg(feature = "std")]
let _ = write!(f, "StorageWeightReclaim<{:?}>", self.0);
#[cfg(not(feature = "std"))]
let _ = write!(f, "StorageWeightReclaim<wasm-stripped>");
Ok(())
}
}
impl<T: Config + Send + Sync, S: TransactionExtension<T::RuntimeCall>>
TransactionExtension<T::RuntimeCall> for StorageWeightReclaim<T, S>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
{
const IDENTIFIER: &'static str = "StorageWeightReclaim<Use `metadata()`!>";
type Implicit = S::Implicit;
type Val = (Option<u64>, S::Val);
type Pre = (Option<u64>, S::Pre);
fn implicit(&self) -> Result<Self::Implicit, TransactionValidityError> {
self.0.implicit()
}
fn metadata() -> Vec<sp_runtime::traits::TransactionExtensionMetadata> {
let mut inner = S::metadata();
inner.push(sp_runtime::traits::TransactionExtensionMetadata {
identifier: "StorageWeightReclaim",
ty: scale_info::meta_type::<()>(),
implicit: scale_info::meta_type::<()>(),
});
inner
}
fn weight(&self, call: &T::RuntimeCall) -> Weight {
T::WeightInfo::storage_weight_reclaim().saturating_add(self.0.weight(call))
}
fn validate(
&self,
origin: T::RuntimeOrigin,
call: &T::RuntimeCall,
info: &DispatchInfoOf<T::RuntimeCall>,
len: usize,
self_implicit: Self::Implicit,
inherited_implication: &impl Implication,
source: TransactionSource,
) -> Result<(ValidTransaction, Self::Val, T::RuntimeOrigin), TransactionValidityError> {
let proof_size = get_proof_size();
self.0
.validate(origin, call, info, len, self_implicit, inherited_implication, source)
.map(|(validity, val, origin)| (validity, (proof_size, val), origin))
}
fn prepare(
self,
val: Self::Val,
origin: &T::RuntimeOrigin,
call: &T::RuntimeCall,
info: &DispatchInfoOf<T::RuntimeCall>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
let (proof_size, inner_val) = val;
self.0.prepare(inner_val, origin, call, info, len).map(|pre| (proof_size, pre))
}
fn post_dispatch_details(
pre: Self::Pre,
info: &DispatchInfoOf<T::RuntimeCall>,
post_info: &PostDispatchInfoOf<T::RuntimeCall>,
len: usize,
result: &DispatchResult,
) -> Result<Weight, TransactionValidityError> {
let (proof_size_before_dispatch, inner_pre) = pre;
let mut post_info_with_inner = *post_info;
S::post_dispatch(inner_pre, info, &mut post_info_with_inner, len, result)?;
let inner_refund = if let (Some(before_weight), Some(after_weight)) =
(post_info.actual_weight, post_info_with_inner.actual_weight)
{
before_weight.saturating_sub(after_weight)
} else {
Weight::zero()
};
let Some(proof_size_before_dispatch) = proof_size_before_dispatch else {
return Ok(inner_refund);
};
let Some(proof_size_after_dispatch) = get_proof_size().defensive_proof(
"Proof recording enabled during prepare, now disabled. This should not happen.",
) else {
return Ok(inner_refund)
};
let measured_proof_size =
proof_size_after_dispatch.saturating_sub(proof_size_before_dispatch);
let benchmarked_actual_weight = post_info_with_inner.calc_actual_weight(info);
let benchmarked_actual_proof_size = benchmarked_actual_weight.proof_size();
if benchmarked_actual_proof_size < measured_proof_size {
log::error!(
target: LOG_TARGET,
"Benchmarked storage weight smaller than consumed storage weight. \
benchmarked: {benchmarked_actual_proof_size} consumed: {measured_proof_size}"
);
} else {
log::trace!(
target: LOG_TARGET,
"Reclaiming storage weight. benchmarked: {benchmarked_actual_proof_size},
consumed: {measured_proof_size}"
);
}
let accurate_weight = benchmarked_actual_weight.set_proof_size(measured_proof_size);
let pov_size_missing_from_node = frame_system::BlockWeight::<T>::mutate(|current_weight| {
let already_reclaimed = frame_system::ExtrinsicWeightReclaimed::<T>::get();
current_weight.accrue(already_reclaimed, info.class);
current_weight.reduce(info.total_weight(), info.class);
current_weight.accrue(accurate_weight, info.class);
let extrinsic_len = frame_system::AllExtrinsicsLen::<T>::get().unwrap_or(0);
let node_side_pov_size = proof_size_after_dispatch.saturating_add(extrinsic_len.into());
let block_weight_proof_size = current_weight.total().proof_size();
let pov_size_missing_from_node =
node_side_pov_size.saturating_sub(block_weight_proof_size);
if pov_size_missing_from_node > 0 {
log::warn!(
target: LOG_TARGET,
"Node-side PoV size higher than runtime proof size weight. node-side: \
{node_side_pov_size} extrinsic_len: {extrinsic_len} runtime: \
{block_weight_proof_size}, missing: {pov_size_missing_from_node}. Setting to \
node-side proof size."
);
current_weight
.accrue(Weight::from_parts(0, pov_size_missing_from_node), info.class);
}
pov_size_missing_from_node
});
let accurate_unspent = info
.total_weight()
.saturating_sub(accurate_weight)
.saturating_sub(Weight::from_parts(0, pov_size_missing_from_node));
frame_system::ExtrinsicWeightReclaimed::<T>::put(accurate_unspent);
let already_unspent_in_tx_ext_pipeline = post_info.calc_unspent(info);
Ok(accurate_unspent.saturating_sub(already_unspent_in_tx_ext_pipeline))
}
fn bare_validate(
call: &T::RuntimeCall,
info: &DispatchInfoOf<T::RuntimeCall>,
len: usize,
) -> frame_support::pallet_prelude::TransactionValidity {
S::bare_validate(call, info, len)
}
fn bare_validate_and_prepare(
call: &T::RuntimeCall,
info: &DispatchInfoOf<T::RuntimeCall>,
len: usize,
) -> Result<(), TransactionValidityError> {
S::bare_validate_and_prepare(call, info, len)
}
fn bare_post_dispatch(
info: &DispatchInfoOf<T::RuntimeCall>,
post_info: &mut PostDispatchInfoOf<T::RuntimeCall>,
len: usize,
result: &DispatchResult,
) -> Result<(), TransactionValidityError> {
S::bare_post_dispatch(info, post_info, len, result)?;
frame_system::Pallet::<T>::reclaim_weight(info, post_info)
}
}