diff --git a/frame/alliance/src/lib.rs b/frame/alliance/src/lib.rs index 6cc162f7d2f3d..d50e20ba00c07 100644 --- a/frame/alliance/src/lib.rs +++ b/frame/alliance/src/lib.rs @@ -114,7 +114,7 @@ use frame_support::{ ChangeMembers, Currency, Get, InitializeMembers, IsSubType, OnUnbalanced, ReservableCurrency, }, - weights::{OldWeight, Weight}, + weights::Weight, }; use pallet_identity::IdentityField; @@ -539,36 +539,7 @@ pub mod pallet { Ok(()) } - /// Close a vote that is either approved, disapproved, or whose voting period has ended. - /// - /// Must be called by a Fellow. - #[pallet::call_index(2)] - #[pallet::weight({ - let b = *length_bound; - let m = T::MaxFellows::get(); - let p1 = *proposal_weight_bound; - let p2 = T::MaxProposals::get(); - T::WeightInfo::close_early_approved(b, m, p2) - .max(T::WeightInfo::close_early_disapproved(m, p2)) - .max(T::WeightInfo::close_approved(b, m, p2)) - .max(T::WeightInfo::close_disapproved(m, p2)) - .saturating_add(p1.into()) - })] - #[allow(deprecated)] - #[deprecated(note = "1D weight is used in this extrinsic, please migrate to use `close`")] - pub fn close_old_weight( - origin: OriginFor, - proposal_hash: T::Hash, - #[pallet::compact] index: ProposalIndex, - #[pallet::compact] proposal_weight_bound: OldWeight, - #[pallet::compact] length_bound: u32, - ) -> DispatchResultWithPostInfo { - let proposal_weight_bound: Weight = proposal_weight_bound.into(); - let who = ensure_signed(origin)?; - ensure!(Self::has_voting_rights(&who), Error::::NoVotingRights); - - Self::do_close(proposal_hash, index, proposal_weight_bound, length_bound) - } + // Index 2 was `close_old_weight`; it was removed due to weights v1 deprecation. /// Initialize the Alliance, onboard fellows and allies. /// diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index c58965d2c9199..bde08f08c13b4 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -57,7 +57,7 @@ use frame_support::{ traits::{ Backing, ChangeMembers, EnsureOrigin, Get, GetBacking, InitializeMembers, StorageVersion, }, - weights::{OldWeight, Weight}, + weights::Weight, }; #[cfg(test)] @@ -557,59 +557,7 @@ pub mod pallet { } } - /// Close a vote that is either approved, disapproved or whose voting period has ended. - /// - /// May be called by any signed account in order to finish voting and close the proposal. - /// - /// If called before the end of the voting period it will only close the vote if it is - /// has enough votes to be approved or disapproved. - /// - /// If called after the end of the voting period abstentions are counted as rejections - /// unless there is a prime member set and the prime member cast an approval. - /// - /// If the close operation completes successfully with disapproval, the transaction fee will - /// be waived. Otherwise execution of the approved operation will be charged to the caller. - /// - /// + `proposal_weight_bound`: The maximum amount of weight consumed by executing the closed - /// proposal. - /// + `length_bound`: The upper bound for the length of the proposal in storage. Checked via - /// `storage::read` so it is `size_of::() == 4` larger than the pure length. - /// - /// ## Complexity - /// - `O(B + M + P1 + P2)` where: - /// - `B` is `proposal` size in bytes (length-fee-bounded) - /// - `M` is members-count (code- and governance-bounded) - /// - `P1` is the complexity of `proposal` preimage. - /// - `P2` is proposal-count (code-bounded) - #[pallet::call_index(4)] - #[pallet::weight(( - { - let b = *length_bound; - let m = T::MaxMembers::get(); - let p1 = *proposal_weight_bound; - let p2 = T::MaxProposals::get(); - T::WeightInfo::close_early_approved(b, m, p2) - .max(T::WeightInfo::close_early_disapproved(m, p2)) - .max(T::WeightInfo::close_approved(b, m, p2)) - .max(T::WeightInfo::close_disapproved(m, p2)) - .saturating_add(p1.into()) - }, - DispatchClass::Operational - ))] - #[allow(deprecated)] - #[deprecated(note = "1D weight is used in this extrinsic, please migrate to `close`")] - pub fn close_old_weight( - origin: OriginFor, - proposal_hash: T::Hash, - #[pallet::compact] index: ProposalIndex, - #[pallet::compact] proposal_weight_bound: OldWeight, - #[pallet::compact] length_bound: u32, - ) -> DispatchResultWithPostInfo { - let proposal_weight_bound: Weight = proposal_weight_bound.into(); - let _ = ensure_signed(origin)?; - - Self::do_close(proposal_hash, index, proposal_weight_bound, length_bound) - } + // Index 4 was `close_old_weight`; it was removed due to weights v1 deprecation. /// Disapprove a proposal, close, and remove it from the system, regardless of its current /// state. diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index dc93a7f06ff2d..6b8b85458c40c 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -115,7 +115,7 @@ use frame_support::{ tokens::fungible::Inspect, ConstU32, Contains, Currency, Get, Randomness, ReservableCurrency, Time, }, - weights::{OldWeight, Weight}, + weights::Weight, BoundedVec, WeakBoundedVec, }; use frame_system::Pallet as System; @@ -150,6 +150,12 @@ type RelaxedCodeVec = WeakBoundedVec::MaxCodeLen>; type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; type DebugBufferVec = BoundedVec::MaxDebugBufferLen>; +/// The old weight type. +/// +/// This is a copy of the [`frame_support::weights::OldWeight`] type since the contracts pallet +/// needs to support it indefinitely. +type OldWeight = u64; + /// Used as a sentinel value when reading and writing contract memory. /// /// It is usually used to signal `None` to a contract when only a primitive is allowed @@ -1281,7 +1287,7 @@ impl Pallet { /// Used by backwards compatible extrinsics. We cannot just set the proof_size weight limit to /// zero or an old `Call` will just fail with OutOfGas. fn compat_weight_limit(gas_limit: OldWeight) -> Weight { - Weight::from_parts(gas_limit.0, u64::from(T::MaxCodeLen::get()) * 2) + Weight::from_parts(gas_limit, u64::from(T::MaxCodeLen::get()) * 2) } } diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 5e4ffcfe0a598..e4e8bea7eb04a 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -370,13 +370,11 @@ mod tests { gas::GasMeter, storage::WriteOutcome, tests::{RuntimeCall, Test, ALICE, BOB}, - BalanceOf, CodeHash, Error, Pallet as Contracts, + BalanceOf, CodeHash, Error, OldWeight, Pallet as Contracts, }; use assert_matches::assert_matches; use frame_support::{ - assert_err, assert_ok, - dispatch::DispatchResultWithPostInfo, - weights::{OldWeight, Weight}, + assert_err, assert_ok, dispatch::DispatchResultWithPostInfo, weights::Weight, }; use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pretty_assertions::assert_eq; @@ -1632,13 +1630,24 @@ mod tests { let output = execute(CODE_GAS_LEFT, vec![], &mut ext).unwrap(); - let OldWeight(gas_left) = OldWeight::decode(&mut &*output.data).unwrap(); + let gas_left = OldWeight::decode(&mut &*output.data).unwrap(); let actual_left = ext.gas_meter.gas_left(); // TODO: account for proof size weight assert!(gas_left < gas_limit.ref_time(), "gas_left must be less than initial"); assert!(gas_left > actual_left.ref_time(), "gas_left must be greater than final"); } + /// Test that [`frame_support::weights::OldWeight`] en/decodes the same as our + /// [`crate::OldWeight`]. + #[test] + fn old_weight_decode() { + #![allow(deprecated)] + let sp = frame_support::weights::OldWeight(42).encode(); + let our = crate::OldWeight::decode(&mut &*sp).unwrap(); + + assert_eq!(our, 42); + } + const CODE_VALUE_TRANSFERRED: &str = r#" (module (import "seal0" "seal_value_transferred" (func $seal_value_transferred (param i32 i32))) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 1b87acb4db8dd..9e949ef6d4a21 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -550,27 +550,6 @@ impl ClassifyDispatch for (Weight, DispatchClass, Pays) { // TODO: Eventually remove these -impl From> for PostDispatchInfo { - fn from(maybe_actual_computation: Option) -> Self { - let actual_weight = match maybe_actual_computation { - Some(actual_computation) => Some(Weight::from_parts(actual_computation, 0)), - None => None, - }; - Self { actual_weight, pays_fee: Default::default() } - } -} - -impl From<(Option, Pays)> for PostDispatchInfo { - fn from(post_weight_info: (Option, Pays)) -> Self { - let (maybe_actual_time, pays_fee) = post_weight_info; - let actual_weight = match maybe_actual_time { - Some(actual_time) => Some(Weight::from_parts(actual_time, 0)), - None => None, - }; - Self { actual_weight, pays_fee } - } -} - impl ClassifyDispatch for u64 { fn classify_dispatch(&self, _: T) -> DispatchClass { DispatchClass::Normal @@ -730,7 +709,7 @@ impl PaysFee for (u64, Pays) { /// ``` /// # #[macro_use] /// # extern crate frame_support; -/// # use frame_support::{weights::Weight, dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo}}; +/// # use frame_support::{weights::Weight, dispatch::{DispatchResultWithPostInfo, WithPostDispatchInfo, PostDispatchInfo}}; /// # use frame_system::{Config, ensure_signed}; /// decl_module! { /// pub struct Module for enum Call where origin: T::RuntimeOrigin { @@ -744,7 +723,7 @@ impl PaysFee for (u64, Pays) { /// return Ok(None::.into()); /// } /// // expensive calculation not executed: use only a portion of the weight -/// Ok(Some(100_000).into()) +/// Ok(PostDispatchInfo { actual_weight: Some(Weight::from_parts(100_000, 0)), ..Default::default() }) /// } /// } /// } @@ -3214,7 +3193,7 @@ mod tests { OnInitialize, OnRuntimeUpgrade, PalletInfo, }, }; - use sp_weights::RuntimeDbWeight; + use sp_weights::{RuntimeDbWeight, Weight}; pub trait Config: system::Config + Sized where @@ -3535,13 +3514,24 @@ mod tests { fn test_new_call_variant() { Call::::new_call_variant_aux_0(); } + + pub fn from_actual_ref_time(ref_time: Option) -> PostDispatchInfo { + PostDispatchInfo { + actual_weight: ref_time.map(|t| Weight::from_all(t)), + pays_fee: Default::default(), + } + } + + pub fn from_post_weight_info(ref_time: Option, pays_fee: Pays) -> PostDispatchInfo { + PostDispatchInfo { actual_weight: ref_time.map(|t| Weight::from_all(t)), pays_fee } + } } #[cfg(test)] // Do not complain about unused `dispatch` and `dispatch_aux`. #[allow(dead_code)] mod weight_tests { - use super::*; + use super::{tests::*, *}; use sp_core::{parameter_types, Get}; use sp_weights::RuntimeDbWeight; @@ -3655,9 +3645,12 @@ mod weight_tests { #[test] fn extract_actual_weight_works() { let pre = DispatchInfo { weight: Weight::from_parts(1000, 0), ..Default::default() }; - assert_eq!(extract_actual_weight(&Ok(Some(7).into()), &pre), Weight::from_parts(7, 0)); assert_eq!( - extract_actual_weight(&Ok(Some(1000).into()), &pre), + extract_actual_weight(&Ok(from_actual_ref_time(Some(7))), &pre), + Weight::from_parts(7, 0) + ); + assert_eq!( + extract_actual_weight(&Ok(from_actual_ref_time(Some(1000))), &pre), Weight::from_parts(1000, 0) ); assert_eq!( @@ -3673,7 +3666,7 @@ mod weight_tests { fn extract_actual_weight_caps_at_pre_weight() { let pre = DispatchInfo { weight: Weight::from_parts(1000, 0), ..Default::default() }; assert_eq!( - extract_actual_weight(&Ok(Some(1250).into()), &pre), + extract_actual_weight(&Ok(from_actual_ref_time(Some(1250))), &pre), Weight::from_parts(1000, 0) ); assert_eq!( @@ -3688,10 +3681,19 @@ mod weight_tests { #[test] fn extract_actual_pays_fee_works() { let pre = DispatchInfo { weight: Weight::from_parts(1000, 0), ..Default::default() }; - assert_eq!(extract_actual_pays_fee(&Ok(Some(7).into()), &pre), Pays::Yes); - assert_eq!(extract_actual_pays_fee(&Ok(Some(1000).into()), &pre), Pays::Yes); - assert_eq!(extract_actual_pays_fee(&Ok((Some(1000), Pays::Yes).into()), &pre), Pays::Yes); - assert_eq!(extract_actual_pays_fee(&Ok((Some(1000), Pays::No).into()), &pre), Pays::No); + assert_eq!(extract_actual_pays_fee(&Ok(from_actual_ref_time(Some(7))), &pre), Pays::Yes); + assert_eq!( + extract_actual_pays_fee(&Ok(from_actual_ref_time(Some(1000)).into()), &pre), + Pays::Yes + ); + assert_eq!( + extract_actual_pays_fee(&Ok(from_post_weight_info(Some(1000), Pays::Yes)), &pre), + Pays::Yes + ); + assert_eq!( + extract_actual_pays_fee(&Ok(from_post_weight_info(Some(1000), Pays::No)), &pre), + Pays::No + ); assert_eq!( extract_actual_pays_fee( &Err(DispatchError::BadOrigin.with_weight(Weight::from_parts(9, 0))), @@ -3715,9 +3717,12 @@ mod weight_tests { pays_fee: Pays::No, ..Default::default() }; - assert_eq!(extract_actual_pays_fee(&Ok(Some(7).into()), &pre), Pays::No); - assert_eq!(extract_actual_pays_fee(&Ok(Some(1000).into()), &pre), Pays::No); - assert_eq!(extract_actual_pays_fee(&Ok((Some(1000), Pays::Yes).into()), &pre), Pays::No); + assert_eq!(extract_actual_pays_fee(&Ok(from_actual_ref_time(Some(7))), &pre), Pays::No); + assert_eq!(extract_actual_pays_fee(&Ok(from_actual_ref_time(Some(1000))), &pre), Pays::No); + assert_eq!( + extract_actual_pays_fee(&Ok(from_post_weight_info(Some(1000), Pays::Yes)), &pre), + Pays::No + ); } } diff --git a/frame/system/src/tests.rs b/frame/system/src/tests.rs index 9b60c6915ab1c..fc388800e13b4 100644 --- a/frame/system/src/tests.rs +++ b/frame/system/src/tests.rs @@ -236,17 +236,23 @@ fn deposit_event_uses_actual_weight_and_pays_fee() { .get(DispatchClass::Normal) .base_extrinsic; let pre_info = DispatchInfo { weight: Weight::from_parts(1000, 0), ..Default::default() }; - System::note_applied_extrinsic(&Ok(Some(300).into()), pre_info); - System::note_applied_extrinsic(&Ok(Some(1000).into()), pre_info); + System::note_applied_extrinsic(&Ok(from_actual_ref_time(Some(300))), pre_info); + System::note_applied_extrinsic(&Ok(from_actual_ref_time(Some(1000))), pre_info); System::note_applied_extrinsic( // values over the pre info should be capped at pre dispatch value - &Ok(Some(1200).into()), + &Ok(from_actual_ref_time(Some(1200))), + pre_info, + ); + System::note_applied_extrinsic( + &Ok(from_post_weight_info(Some(2_500_000), Pays::Yes)), pre_info, ); - System::note_applied_extrinsic(&Ok((Some(2_500_000), Pays::Yes).into()), pre_info); System::note_applied_extrinsic(&Ok(Pays::No.into()), pre_info); - System::note_applied_extrinsic(&Ok((Some(2_500_000), Pays::No).into()), pre_info); - System::note_applied_extrinsic(&Ok((Some(500), Pays::No).into()), pre_info); + System::note_applied_extrinsic( + &Ok(from_post_weight_info(Some(2_500_000), Pays::No)), + pre_info, + ); + System::note_applied_extrinsic(&Ok(from_post_weight_info(Some(500), Pays::No)), pre_info); System::note_applied_extrinsic( &Err(DispatchError::BadOrigin.with_weight(Weight::from_parts(999, 0))), pre_info, @@ -289,7 +295,7 @@ fn deposit_event_uses_actual_weight_and_pays_fee() { class: DispatchClass::Operational, ..Default::default() }; - System::note_applied_extrinsic(&Ok(Some(300).into()), pre_info); + System::note_applied_extrinsic(&Ok(from_actual_ref_time(Some(300))), pre_info); let got = System::events(); let want = vec![ @@ -691,3 +697,14 @@ fn ensure_signed_stuff_works() { assert_ok!(EnsureSignedBy::::try_origin(successful_origin)); } } + +pub fn from_actual_ref_time(ref_time: Option) -> PostDispatchInfo { + PostDispatchInfo { + actual_weight: ref_time.map(|t| Weight::from_all(t)), + pays_fee: Default::default(), + } +} + +pub fn from_post_weight_info(ref_time: Option, pays_fee: Pays) -> PostDispatchInfo { + PostDispatchInfo { actual_weight: ref_time.map(|t| Weight::from_all(t)), pays_fee } +} diff --git a/frame/transaction-payment/rpc/runtime-api/src/lib.rs b/frame/transaction-payment/rpc/runtime-api/src/lib.rs index ae4a25bf1711d..0d9c3338250e7 100644 --- a/frame/transaction-payment/rpc/runtime-api/src/lib.rs +++ b/frame/transaction-payment/rpc/runtime-api/src/lib.rs @@ -25,12 +25,10 @@ use sp_runtime::traits::MaybeDisplay; pub use pallet_transaction_payment::{FeeDetails, InclusionFee, RuntimeDispatchInfo}; sp_api::decl_runtime_apis! { - #[api_version(3)] + #[api_version(4)] pub trait TransactionPaymentApi where Balance: Codec + MaybeDisplay, { - #[changed_in(2)] - fn query_info(uxt: Block::Extrinsic, len: u32) -> RuntimeDispatchInfo; fn query_info(uxt: Block::Extrinsic, len: u32) -> RuntimeDispatchInfo; fn query_fee_details(uxt: Block::Extrinsic, len: u32) -> FeeDetails; fn query_weight_to_fee(weight: sp_weights::Weight) -> Balance; diff --git a/frame/transaction-payment/rpc/src/lib.rs b/frame/transaction-payment/rpc/src/lib.rs index 1207a8cbf747a..7f8ed4b802675 100644 --- a/frame/transaction-payment/rpc/src/lib.rs +++ b/frame/transaction-payment/rpc/src/lib.rs @@ -26,7 +26,7 @@ use jsonrpsee::{ types::error::{CallError, ErrorCode, ErrorObject}, }; use pallet_transaction_payment_rpc_runtime_api::{FeeDetails, InclusionFee, RuntimeDispatchInfo}; -use sp_api::{ApiExt, ProvideRuntimeApi}; +use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_core::Bytes; use sp_rpc::number::NumberOrHex; @@ -81,7 +81,7 @@ impl From for i32 { impl TransactionPaymentApiServer< ::Hash, - RuntimeDispatchInfo, + RuntimeDispatchInfo, > for TransactionPayment where Block: BlockT, @@ -93,7 +93,7 @@ where &self, encoded_xt: Bytes, at: Option, - ) -> RpcResult> { + ) -> RpcResult> { let api = self.client.runtime_api(); let at_hash = at.unwrap_or_else(|| self.client.info().best_hash); @@ -115,32 +115,15 @@ where )) } - let api_version = api - .api_version::>(at_hash) - .map_err(|e| map_err(e, "Failed to get transaction payment runtime api version"))? - .ok_or_else(|| { - CallError::Custom(ErrorObject::owned( - Error::RuntimeError.into(), - "Transaction payment runtime api wasn't found in the runtime", - None::, - )) - })?; - - if api_version < 2 { - #[allow(deprecated)] - api.query_info_before_version_2(at_hash, uxt, encoded_len) - .map_err(|e| map_err(e, "Unable to query dispatch info.").into()) - } else { - let res = api - .query_info(at_hash, uxt, encoded_len) - .map_err(|e| map_err(e, "Unable to query dispatch info."))?; - - Ok(RuntimeDispatchInfo { - weight: sp_weights::OldWeight(res.weight.ref_time()), - class: res.class, - partial_fee: res.partial_fee, - }) - } + let res = api + .query_info(at_hash, uxt, encoded_len) + .map_err(|e| map_err(e, "Unable to query dispatch info."))?; + + Ok(RuntimeDispatchInfo { + weight: res.weight, + class: res.class, + partial_fee: res.partial_fee, + }) } fn query_fee_details( diff --git a/primitives/weights/src/lib.rs b/primitives/weights/src/lib.rs index faa641a0f0c53..55d9104b00b77 100644 --- a/primitives/weights/src/lib.rs +++ b/primitives/weights/src/lib.rs @@ -18,6 +18,9 @@ //! # Primitives for transaction weighting. #![cfg_attr(not(feature = "std"), no_std)] +// TODO remove once `OldWeight` is gone. I dont know why this is needed, maybe by one of the macros +// of `OldWeight`. +#![allow(deprecated)] extern crate self as sp_weights; @@ -68,6 +71,7 @@ pub mod constants { )] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(transparent))] +#[deprecated(note = "Will be removed soon; use `Weight` instead.")] pub struct OldWeight(pub u64); /// The weight of database operations that the runtime can invoke. diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index ca137145920bb..cb1cedf18ce87 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -35,12 +35,6 @@ pub struct Weight { proof_size: u64, } -impl From for Weight { - fn from(old: OldWeight) -> Self { - Weight::from_parts(old.0, 0) - } -} - impl Weight { /// Set the reference time part of the weight. pub const fn set_ref_time(mut self, c: u64) -> Self { @@ -74,6 +68,7 @@ impl Weight { &mut self.proof_size } + /// The maximal weight in all dimensions. pub const MAX: Self = Self { ref_time: u64::MAX, proof_size: u64::MAX }; /// Get the conservative min of `self` and `other` weight.