From f8c395edb42ffd17a397cd2126abecd433c31906 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 15 Sep 2022 18:46:05 +0800 Subject: [PATCH 01/38] Add storage size component to weights --- primitives/weights/src/weight_v2.rs | 189 ++++++++++++++++++++-------- 1 file changed, 140 insertions(+), 49 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index a4e4da4f8a7b3..9db0ef2f766ff 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use codec::{CompactAs, Decode, Encode, MaxEncodedLen}; +use codec::{Decode, Encode, MaxEncodedLen}; use core::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign}; use sp_arithmetic::traits::{Bounded, CheckedAdd, CheckedSub, Zero}; use sp_debug_derive::RuntimeDebug; @@ -33,12 +33,15 @@ use super::*; Clone, RuntimeDebug, Default, - CompactAs, )] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct Weight { + #[codec(compact)] /// The weight of computational time used based on some reference hardware. ref_time: u64, + #[codec(compact)] + /// The weight of storage space used. + storage_size: u64, } impl Weight { @@ -48,71 +51,118 @@ impl Weight { self } + /// Set the storage size part of the weight. + pub const fn set_storage_size(mut self, c: u64) -> Self { + self.storage_size = c; + self + } + /// Return the reference time part of the weight. pub const fn ref_time(&self) -> u64 { self.ref_time } - /// Return a mutable reference time part of the weight. + /// Return the storage size part of the weight. + pub const fn storage_size(&self) -> u64 { + self.storage_size + } + + /// Return a mutable reference to the reference time part of the weight. pub fn ref_time_mut(&mut self) -> &mut u64 { &mut self.ref_time } - pub const MAX: Self = Self { ref_time: u64::MAX }; + /// Return a mutable reference to the storage size part of the weight. + pub fn storage_size_mut(&mut self) -> &mut u64 { + &mut self.storage_size + } + + pub const MAX: Self = Self { ref_time: u64::MAX, storage_size: u64::MAX }; /// Get the conservative min of `self` and `other` weight. pub fn min(&self, other: Self) -> Self { - Self { ref_time: self.ref_time.min(other.ref_time) } + Self { + ref_time: self.ref_time.min(other.ref_time), + storage_size: self.storage_size.min(other.storage_size), + } } /// Get the aggressive max of `self` and `other` weight. pub fn max(&self, other: Self) -> Self { - Self { ref_time: self.ref_time.max(other.ref_time) } + Self { + ref_time: self.ref_time.max(other.ref_time), + storage_size: self.storage_size.max(other.storage_size), + } } /// Try to add some `other` weight while upholding the `limit`. pub fn try_add(&self, other: &Self, limit: &Self) -> Option { let total = self.checked_add(other)?; - if total.ref_time > limit.ref_time { + if total.ref_time > limit.ref_time || total.storage_size > limit.storage_size { None } else { Some(total) } } - /// Construct [`Weight`] with reference time weight. + /// Construct [`Weight`] with reference time weight and 0 storage size weight. pub const fn from_ref_time(ref_time: u64) -> Self { - Self { ref_time } + Self { ref_time, storage_size: 0 } } + /// Construct [`Weight`] with storage size weight and 0 reference time weight. + pub const fn from_storage_size(storage_size: u64) -> Self { + Self { ref_time: 0, storage_size } + } + + /// Construct [`Weight`] with weight components, namely reference time and storage size weights. + pub const fn from_components(ref_time: u64, storage_size: u64) -> Self { + Self { ref_time, storage_size } + } + /// Saturating [`Weight`] addition. Computes `self + rhs`, saturating at the numeric bounds of /// all fields instead of overflowing. pub const fn saturating_add(self, rhs: Self) -> Self { - Self { ref_time: self.ref_time.saturating_add(rhs.ref_time) } + Self { + ref_time: self.ref_time.saturating_add(rhs.ref_time), + storage_size: self.storage_size.saturating_add(rhs.storage_size), + } } /// Saturating [`Weight`] subtraction. Computes `self - rhs`, saturating at the numeric bounds /// of all fields instead of overflowing. pub const fn saturating_sub(self, rhs: Self) -> Self { - Self { ref_time: self.ref_time.saturating_sub(rhs.ref_time) } + Self { + ref_time: self.ref_time.saturating_sub(rhs.ref_time), + storage_size: self.storage_size.saturating_sub(rhs.storage_size), + } } /// Saturating [`Weight`] scalar multiplication. Computes `self.field * scalar` for all fields, /// saturating at the numeric bounds of all fields instead of overflowing. pub const fn saturating_mul(self, scalar: u64) -> Self { - Self { ref_time: self.ref_time.saturating_mul(scalar) } + Self { + ref_time: self.ref_time.saturating_mul(scalar), + storage_size: self.storage_size.saturating_mul(scalar), + } } /// Saturating [`Weight`] scalar division. Computes `self.field / scalar` for all fields, /// saturating at the numeric bounds of all fields instead of overflowing. pub const fn saturating_div(self, scalar: u64) -> Self { - Self { ref_time: self.ref_time.saturating_div(scalar) } + Self { + ref_time: self.ref_time.saturating_div(scalar), + storage_size: self.storage_size.saturating_div(scalar), + } } /// Saturating [`Weight`] scalar exponentiation. Computes `self.field.pow(exp)` for all fields, /// saturating at the numeric bounds of all fields instead of overflowing. pub const fn saturating_pow(self, exp: u32) -> Self { - Self { ref_time: self.ref_time.saturating_pow(exp) } + Self { + ref_time: self.ref_time.saturating_pow(exp), + storage_size: self.storage_size.saturating_pow(exp), + } } /// Increment [`Weight`] by `amount` via saturating addition. @@ -122,96 +172,116 @@ impl Weight { /// Checked [`Weight`] addition. Computes `self + rhs`, returning `None` if overflow occurred. pub const fn checked_add(&self, rhs: &Self) -> Option { - match self.ref_time.checked_add(rhs.ref_time) { - Some(ref_time) => Some(Self { ref_time }), - None => None, - } + let ref_time = match self.ref_time.checked_add(rhs.ref_time) { + Some(t) => t, + None => return None, + }; + let storage_size = match self.storage_size.checked_add(rhs.storage_size) { + Some(s) => s, + None => return None, + }; + Some(Self { ref_time, storage_size }) } /// Checked [`Weight`] subtraction. Computes `self - rhs`, returning `None` if overflow /// occurred. pub const fn checked_sub(&self, rhs: &Self) -> Option { - match self.ref_time.checked_sub(rhs.ref_time) { - Some(ref_time) => Some(Self { ref_time }), - None => None, - } + let ref_time = match self.ref_time.checked_sub(rhs.ref_time) { + Some(t) => t, + None => return None, + }; + let storage_size = match self.storage_size.checked_sub(rhs.storage_size) { + Some(s) => s, + None => return None, + }; + Some(Self { ref_time, storage_size }) } /// Checked [`Weight`] scalar multiplication. Computes `self.field * scalar` for each field, /// returning `None` if overflow occurred. pub const fn checked_mul(self, scalar: u64) -> Option { - match self.ref_time.checked_mul(scalar) { - Some(ref_time) => Some(Self { ref_time }), - None => None, - } + let ref_time = match self.ref_time.checked_mul(scalar) { + Some(t) => t, + None => return None, + }; + let storage_size = match self.storage_size.checked_mul(scalar) { + Some(s) => s, + None => return None, + }; + Some(Self { ref_time, storage_size }) } /// Checked [`Weight`] scalar division. Computes `self.field / scalar` for each field, returning /// `None` if overflow occurred. pub const fn checked_div(self, scalar: u64) -> Option { - match self.ref_time.checked_div(scalar) { - Some(ref_time) => Some(Self { ref_time }), - None => None, - } + let ref_time = match self.ref_time.checked_div(scalar) { + Some(t) => t, + None => return None, + }; + let storage_size = match self.storage_size.checked_div(scalar) { + Some(s) => s, + None => return None, + }; + Some(Self { ref_time, storage_size }) } /// Return a [`Weight`] where all fields are zero. pub const fn zero() -> Self { - Self { ref_time: 0 } + Self { ref_time: 0, storage_size: 0 } } /// Returns true if any of `self`'s constituent weights is strictly greater than that of the /// `other`'s, otherwise returns false. pub const fn any_gt(self, other: Self) -> bool { - self.ref_time > other.ref_time + self.ref_time > other.ref_time || self.storage_size > other.storage_size } /// Returns true if all of `self`'s constituent weights is strictly greater than that of the /// `other`'s, otherwise returns false. pub const fn all_gt(self, other: Self) -> bool { - self.ref_time > other.ref_time + self.ref_time > other.ref_time && self.storage_size > other.storage_size } /// Returns true if any of `self`'s constituent weights is strictly less than that of the /// `other`'s, otherwise returns false. pub const fn any_lt(self, other: Self) -> bool { - self.ref_time < other.ref_time + self.ref_time < other.ref_time || self.storage_size < other.storage_size } /// Returns true if all of `self`'s constituent weights is strictly less than that of the /// `other`'s, otherwise returns false. pub const fn all_lt(self, other: Self) -> bool { - self.ref_time < other.ref_time + self.ref_time < other.ref_time && self.storage_size < other.storage_size } /// Returns true if any of `self`'s constituent weights is greater than or equal to that of the /// `other`'s, otherwise returns false. pub const fn any_gte(self, other: Self) -> bool { - self.ref_time >= other.ref_time + self.ref_time >= other.ref_time || self.storage_size >= other.storage_size } /// Returns true if all of `self`'s constituent weights is greater than or equal to that of the /// `other`'s, otherwise returns false. pub const fn all_gte(self, other: Self) -> bool { - self.ref_time >= other.ref_time + self.ref_time >= other.ref_time && self.storage_size >= other.storage_size } /// Returns true if any of `self`'s constituent weights is less than or equal to that of the /// `other`'s, otherwise returns false. pub const fn any_lte(self, other: Self) -> bool { - self.ref_time <= other.ref_time + self.ref_time <= other.ref_time || self.storage_size <= other.storage_size } /// Returns true if all of `self`'s constituent weights is less than or equal to that of the /// `other`'s, otherwise returns false. pub const fn all_lte(self, other: Self) -> bool { - self.ref_time <= other.ref_time + self.ref_time <= other.ref_time && self.storage_size <= other.storage_size } /// Returns true if any of `self`'s constituent weights is equal to that of the `other`'s, /// otherwise returns false. pub const fn any_eq(self, other: Self) -> bool { - self.ref_time == other.ref_time + self.ref_time == other.ref_time || self.storage_size == other.storage_size } // NOTE: `all_eq` does not exist, as it's simply the `eq` method from the `PartialEq` trait. @@ -230,14 +300,20 @@ impl Zero for Weight { impl Add for Weight { type Output = Self; fn add(self, rhs: Self) -> Self { - Self { ref_time: self.ref_time + rhs.ref_time } + Self { + ref_time: self.ref_time + rhs.ref_time, + storage_size: self.storage_size + rhs.storage_size, + } } } impl Sub for Weight { type Output = Self; fn sub(self, rhs: Self) -> Self { - Self { ref_time: self.ref_time - rhs.ref_time } + Self { + ref_time: self.ref_time - rhs.ref_time, + storage_size: self.storage_size - rhs.storage_size, + } } } @@ -247,7 +323,10 @@ where { type Output = Self; fn mul(self, b: T) -> Self { - Self { ref_time: b * self.ref_time } + Self { + ref_time: b * self.ref_time, + storage_size: b * self.storage_size, + } } } @@ -257,7 +336,10 @@ macro_rules! weight_mul_per_impl { impl Mul for $t { type Output = Weight; fn mul(self, b: Weight) -> Weight { - Weight { ref_time: self * b.ref_time } + Weight { + ref_time: self * b.ref_time, + storage_size: self * b.storage_size, + } } } )* @@ -277,7 +359,10 @@ macro_rules! weight_mul_primitive_impl { impl Mul for $t { type Output = Weight; fn mul(self, b: Weight) -> Weight { - Weight { ref_time: u64::from(self) * b.ref_time } + Weight { + ref_time: u64::from(self) * b.ref_time, + storage_size: u64::from(self) * b.storage_size, + } } } )* @@ -292,7 +377,7 @@ where { type Output = Self; fn div(self, b: T) -> Self { - Self { ref_time: self.ref_time / b } + Self { ref_time: self.ref_time / b, storage_size: self.storage_size / b } } } @@ -310,7 +395,7 @@ impl CheckedSub for Weight { impl core::fmt::Display for Weight { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "Weight(ref_time: {})", self.ref_time) + write!(f, "Weight(ref_time: {}, storage_size: {})", self.ref_time, self.storage_size) } } @@ -325,12 +410,18 @@ impl Bounded for Weight { impl AddAssign for Weight { fn add_assign(&mut self, other: Self) { - *self = Self { ref_time: self.ref_time + other.ref_time }; + *self = Self { + ref_time: self.ref_time + other.ref_time, + storage_size: self.storage_size + other.storage_size, + }; } } impl SubAssign for Weight { fn sub_assign(&mut self, other: Self) { - *self = Self { ref_time: self.ref_time - other.ref_time }; + *self = Self { + ref_time: self.ref_time - other.ref_time, + storage_size: self.storage_size - other.storage_size, + }; } } From 779b815c54e549e50149cb20bb36c14afd993df3 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 15 Sep 2022 19:32:09 +0800 Subject: [PATCH 02/38] Rename storage_size to proof_size --- primitives/weights/src/weight_v2.rs | 98 ++++++++++++++--------------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index 9db0ef2f766ff..6b60cc94471a3 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -40,8 +40,8 @@ pub struct Weight { /// The weight of computational time used based on some reference hardware. ref_time: u64, #[codec(compact)] - /// The weight of storage space used. - storage_size: u64, + /// The weight of storage space used by proof of validity. + proof_size: u64, } impl Weight { @@ -52,8 +52,8 @@ impl Weight { } /// Set the storage size part of the weight. - pub const fn set_storage_size(mut self, c: u64) -> Self { - self.storage_size = c; + pub const fn set_proof_size(mut self, c: u64) -> Self { + self.proof_size = c; self } @@ -63,8 +63,8 @@ impl Weight { } /// Return the storage size part of the weight. - pub const fn storage_size(&self) -> u64 { - self.storage_size + pub const fn proof_size(&self) -> u64 { + self.proof_size } /// Return a mutable reference to the reference time part of the weight. @@ -73,17 +73,17 @@ impl Weight { } /// Return a mutable reference to the storage size part of the weight. - pub fn storage_size_mut(&mut self) -> &mut u64 { - &mut self.storage_size + pub fn proof_size_mut(&mut self) -> &mut u64 { + &mut self.proof_size } - pub const MAX: Self = Self { ref_time: u64::MAX, storage_size: u64::MAX }; + pub const MAX: Self = Self { ref_time: u64::MAX, proof_size: u64::MAX }; /// Get the conservative min of `self` and `other` weight. pub fn min(&self, other: Self) -> Self { Self { ref_time: self.ref_time.min(other.ref_time), - storage_size: self.storage_size.min(other.storage_size), + proof_size: self.proof_size.min(other.proof_size), } } @@ -91,14 +91,14 @@ impl Weight { pub fn max(&self, other: Self) -> Self { Self { ref_time: self.ref_time.max(other.ref_time), - storage_size: self.storage_size.max(other.storage_size), + proof_size: self.proof_size.max(other.proof_size), } } /// Try to add some `other` weight while upholding the `limit`. pub fn try_add(&self, other: &Self, limit: &Self) -> Option { let total = self.checked_add(other)?; - if total.ref_time > limit.ref_time || total.storage_size > limit.storage_size { + if total.ref_time > limit.ref_time || total.proof_size > limit.proof_size { None } else { Some(total) @@ -107,17 +107,17 @@ impl Weight { /// Construct [`Weight`] with reference time weight and 0 storage size weight. pub const fn from_ref_time(ref_time: u64) -> Self { - Self { ref_time, storage_size: 0 } + Self { ref_time, proof_size: 0 } } /// Construct [`Weight`] with storage size weight and 0 reference time weight. - pub const fn from_storage_size(storage_size: u64) -> Self { - Self { ref_time: 0, storage_size } + pub const fn from_proof_size(proof_size: u64) -> Self { + Self { ref_time: 0, proof_size } } /// Construct [`Weight`] with weight components, namely reference time and storage size weights. - pub const fn from_components(ref_time: u64, storage_size: u64) -> Self { - Self { ref_time, storage_size } + pub const fn from_components(ref_time: u64, proof_size: u64) -> Self { + Self { ref_time, proof_size } } /// Saturating [`Weight`] addition. Computes `self + rhs`, saturating at the numeric bounds of @@ -125,7 +125,7 @@ impl Weight { pub const fn saturating_add(self, rhs: Self) -> Self { Self { ref_time: self.ref_time.saturating_add(rhs.ref_time), - storage_size: self.storage_size.saturating_add(rhs.storage_size), + proof_size: self.proof_size.saturating_add(rhs.proof_size), } } @@ -134,7 +134,7 @@ impl Weight { pub const fn saturating_sub(self, rhs: Self) -> Self { Self { ref_time: self.ref_time.saturating_sub(rhs.ref_time), - storage_size: self.storage_size.saturating_sub(rhs.storage_size), + proof_size: self.proof_size.saturating_sub(rhs.proof_size), } } @@ -143,7 +143,7 @@ impl Weight { pub const fn saturating_mul(self, scalar: u64) -> Self { Self { ref_time: self.ref_time.saturating_mul(scalar), - storage_size: self.storage_size.saturating_mul(scalar), + proof_size: self.proof_size.saturating_mul(scalar), } } @@ -152,7 +152,7 @@ impl Weight { pub const fn saturating_div(self, scalar: u64) -> Self { Self { ref_time: self.ref_time.saturating_div(scalar), - storage_size: self.storage_size.saturating_div(scalar), + proof_size: self.proof_size.saturating_div(scalar), } } @@ -161,7 +161,7 @@ impl Weight { pub const fn saturating_pow(self, exp: u32) -> Self { Self { ref_time: self.ref_time.saturating_pow(exp), - storage_size: self.storage_size.saturating_pow(exp), + proof_size: self.proof_size.saturating_pow(exp), } } @@ -176,11 +176,11 @@ impl Weight { Some(t) => t, None => return None, }; - let storage_size = match self.storage_size.checked_add(rhs.storage_size) { + let proof_size = match self.proof_size.checked_add(rhs.proof_size) { Some(s) => s, None => return None, }; - Some(Self { ref_time, storage_size }) + Some(Self { ref_time, proof_size }) } /// Checked [`Weight`] subtraction. Computes `self - rhs`, returning `None` if overflow @@ -190,11 +190,11 @@ impl Weight { Some(t) => t, None => return None, }; - let storage_size = match self.storage_size.checked_sub(rhs.storage_size) { + let proof_size = match self.proof_size.checked_sub(rhs.proof_size) { Some(s) => s, None => return None, }; - Some(Self { ref_time, storage_size }) + Some(Self { ref_time, proof_size }) } /// Checked [`Weight`] scalar multiplication. Computes `self.field * scalar` for each field, @@ -204,11 +204,11 @@ impl Weight { Some(t) => t, None => return None, }; - let storage_size = match self.storage_size.checked_mul(scalar) { + let proof_size = match self.proof_size.checked_mul(scalar) { Some(s) => s, None => return None, }; - Some(Self { ref_time, storage_size }) + Some(Self { ref_time, proof_size }) } /// Checked [`Weight`] scalar division. Computes `self.field / scalar` for each field, returning @@ -218,70 +218,70 @@ impl Weight { Some(t) => t, None => return None, }; - let storage_size = match self.storage_size.checked_div(scalar) { + let proof_size = match self.proof_size.checked_div(scalar) { Some(s) => s, None => return None, }; - Some(Self { ref_time, storage_size }) + Some(Self { ref_time, proof_size }) } /// Return a [`Weight`] where all fields are zero. pub const fn zero() -> Self { - Self { ref_time: 0, storage_size: 0 } + Self { ref_time: 0, proof_size: 0 } } /// Returns true if any of `self`'s constituent weights is strictly greater than that of the /// `other`'s, otherwise returns false. pub const fn any_gt(self, other: Self) -> bool { - self.ref_time > other.ref_time || self.storage_size > other.storage_size + self.ref_time > other.ref_time || self.proof_size > other.proof_size } /// Returns true if all of `self`'s constituent weights is strictly greater than that of the /// `other`'s, otherwise returns false. pub const fn all_gt(self, other: Self) -> bool { - self.ref_time > other.ref_time && self.storage_size > other.storage_size + self.ref_time > other.ref_time && self.proof_size > other.proof_size } /// Returns true if any of `self`'s constituent weights is strictly less than that of the /// `other`'s, otherwise returns false. pub const fn any_lt(self, other: Self) -> bool { - self.ref_time < other.ref_time || self.storage_size < other.storage_size + self.ref_time < other.ref_time || self.proof_size < other.proof_size } /// Returns true if all of `self`'s constituent weights is strictly less than that of the /// `other`'s, otherwise returns false. pub const fn all_lt(self, other: Self) -> bool { - self.ref_time < other.ref_time && self.storage_size < other.storage_size + self.ref_time < other.ref_time && self.proof_size < other.proof_size } /// Returns true if any of `self`'s constituent weights is greater than or equal to that of the /// `other`'s, otherwise returns false. pub const fn any_gte(self, other: Self) -> bool { - self.ref_time >= other.ref_time || self.storage_size >= other.storage_size + self.ref_time >= other.ref_time || self.proof_size >= other.proof_size } /// Returns true if all of `self`'s constituent weights is greater than or equal to that of the /// `other`'s, otherwise returns false. pub const fn all_gte(self, other: Self) -> bool { - self.ref_time >= other.ref_time && self.storage_size >= other.storage_size + self.ref_time >= other.ref_time && self.proof_size >= other.proof_size } /// Returns true if any of `self`'s constituent weights is less than or equal to that of the /// `other`'s, otherwise returns false. pub const fn any_lte(self, other: Self) -> bool { - self.ref_time <= other.ref_time || self.storage_size <= other.storage_size + self.ref_time <= other.ref_time || self.proof_size <= other.proof_size } /// Returns true if all of `self`'s constituent weights is less than or equal to that of the /// `other`'s, otherwise returns false. pub const fn all_lte(self, other: Self) -> bool { - self.ref_time <= other.ref_time && self.storage_size <= other.storage_size + self.ref_time <= other.ref_time && self.proof_size <= other.proof_size } /// Returns true if any of `self`'s constituent weights is equal to that of the `other`'s, /// otherwise returns false. pub const fn any_eq(self, other: Self) -> bool { - self.ref_time == other.ref_time || self.storage_size == other.storage_size + self.ref_time == other.ref_time || self.proof_size == other.proof_size } // NOTE: `all_eq` does not exist, as it's simply the `eq` method from the `PartialEq` trait. @@ -302,7 +302,7 @@ impl Add for Weight { fn add(self, rhs: Self) -> Self { Self { ref_time: self.ref_time + rhs.ref_time, - storage_size: self.storage_size + rhs.storage_size, + proof_size: self.proof_size + rhs.proof_size, } } } @@ -312,7 +312,7 @@ impl Sub for Weight { fn sub(self, rhs: Self) -> Self { Self { ref_time: self.ref_time - rhs.ref_time, - storage_size: self.storage_size - rhs.storage_size, + proof_size: self.proof_size - rhs.proof_size, } } } @@ -325,7 +325,7 @@ where fn mul(self, b: T) -> Self { Self { ref_time: b * self.ref_time, - storage_size: b * self.storage_size, + proof_size: b * self.proof_size, } } } @@ -338,7 +338,7 @@ macro_rules! weight_mul_per_impl { fn mul(self, b: Weight) -> Weight { Weight { ref_time: self * b.ref_time, - storage_size: self * b.storage_size, + proof_size: self * b.proof_size, } } } @@ -361,7 +361,7 @@ macro_rules! weight_mul_primitive_impl { fn mul(self, b: Weight) -> Weight { Weight { ref_time: u64::from(self) * b.ref_time, - storage_size: u64::from(self) * b.storage_size, + proof_size: u64::from(self) * b.proof_size, } } } @@ -377,7 +377,7 @@ where { type Output = Self; fn div(self, b: T) -> Self { - Self { ref_time: self.ref_time / b, storage_size: self.storage_size / b } + Self { ref_time: self.ref_time / b, proof_size: self.proof_size / b } } } @@ -395,7 +395,7 @@ impl CheckedSub for Weight { impl core::fmt::Display for Weight { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "Weight(ref_time: {}, storage_size: {})", self.ref_time, self.storage_size) + write!(f, "Weight(ref_time: {}, proof_size: {})", self.ref_time, self.proof_size) } } @@ -412,7 +412,7 @@ impl AddAssign for Weight { fn add_assign(&mut self, other: Self) { *self = Self { ref_time: self.ref_time + other.ref_time, - storage_size: self.storage_size + other.storage_size, + proof_size: self.proof_size + other.proof_size, }; } } @@ -421,7 +421,7 @@ impl SubAssign for Weight { fn sub_assign(&mut self, other: Self) { *self = Self { ref_time: self.ref_time - other.ref_time, - storage_size: self.storage_size - other.storage_size, + proof_size: self.proof_size - other.proof_size, }; } } From f7b9346fe16670dc993ad41d71c10974d3236352 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 16 Sep 2022 00:31:05 +0800 Subject: [PATCH 03/38] Update primitives/weights/src/weight_v2.rs Co-authored-by: Oliver Tale-Yazdi --- primitives/weights/src/weight_v2.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index 6b60cc94471a3..fe60b37cd75b9 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -98,7 +98,7 @@ impl Weight { /// Try to add some `other` weight while upholding the `limit`. pub fn try_add(&self, other: &Self, limit: &Self) -> Option { let total = self.checked_add(other)?; - if total.ref_time > limit.ref_time || total.proof_size > limit.proof_size { + if total.any_gt(limit) { None } else { Some(total) From 6c84cbda518306a438ad94c9d59913ea9b4b0317 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 16 Sep 2022 13:37:19 +0800 Subject: [PATCH 04/38] Fixes --- primitives/weights/src/weight_v2.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index fe60b37cd75b9..8b90741f058ea 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -98,7 +98,7 @@ impl Weight { /// Try to add some `other` weight while upholding the `limit`. pub fn try_add(&self, other: &Self, limit: &Self) -> Option { let total = self.checked_add(other)?; - if total.any_gt(limit) { + if total.any_gt(*limit) { None } else { Some(total) From 96aa1226693ed9d9733d780386183015572df358 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 16 Sep 2022 13:38:13 +0800 Subject: [PATCH 05/38] cargo fmt --- primitives/weights/src/weight_v2.rs | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index 8b90741f058ea..d4ef8768ea555 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -23,16 +23,7 @@ use sp_debug_derive::RuntimeDebug; use super::*; #[derive( - Encode, - Decode, - MaxEncodedLen, - TypeInfo, - Eq, - PartialEq, - Copy, - Clone, - RuntimeDebug, - Default, + Encode, Decode, MaxEncodedLen, TypeInfo, Eq, PartialEq, Copy, Clone, RuntimeDebug, Default, )] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct Weight { @@ -118,7 +109,7 @@ impl Weight { /// Construct [`Weight`] with weight components, namely reference time and storage size weights. pub const fn from_components(ref_time: u64, proof_size: u64) -> Self { Self { ref_time, proof_size } - } + } /// Saturating [`Weight`] addition. Computes `self + rhs`, saturating at the numeric bounds of /// all fields instead of overflowing. @@ -323,10 +314,7 @@ where { type Output = Self; fn mul(self, b: T) -> Self { - Self { - ref_time: b * self.ref_time, - proof_size: b * self.proof_size, - } + Self { ref_time: b * self.ref_time, proof_size: b * self.proof_size } } } From 36c2d959be991ac65f3cfeee0c4515c75968d847 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 16 Sep 2022 14:30:33 +0800 Subject: [PATCH 06/38] Implement custom Decode and CompactAs --- primitives/weights/src/weight_v2.rs | 40 ++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index d4ef8768ea555..eff7c0419ff0a 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -15,16 +15,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -use codec::{Decode, Encode, MaxEncodedLen}; +use codec::{Compact, Decode, Encode, MaxEncodedLen}; use core::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign}; use sp_arithmetic::traits::{Bounded, CheckedAdd, CheckedSub, Zero}; use sp_debug_derive::RuntimeDebug; use super::*; -#[derive( - Encode, Decode, MaxEncodedLen, TypeInfo, Eq, PartialEq, Copy, Clone, RuntimeDebug, Default, -)] +#[derive(Encode, MaxEncodedLen, TypeInfo, Eq, PartialEq, Copy, Clone, RuntimeDebug, Default)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct Weight { #[codec(compact)] @@ -35,6 +33,40 @@ pub struct Weight { proof_size: u64, } +// Custom Decode implementation for the purposes of migrating from 1D weights. +impl Decode for Weight { + fn decode(input: &mut I) -> Result { + let compact_ref_time = match Compact::::decode(input) { + Ok(r) => r, + Err(_) => { + // Try decoding it in the old way where we only had a non-compact ref time weight + let ref_time = u64::decode(input) + .map_err(|e| e.chain("Could not decode `Weight::ref_time`"))?; + return Ok(Self { ref_time, proof_size: 0 }) + }, + }; + let compact_proof_size = Compact::::decode(input) + .map_err(|e| e.chain("Could not decode `Weight::proof_size`"))?; + Ok(Self { ref_time: compact_ref_time.0, proof_size: compact_proof_size.0 }) + } +} + +impl CompactAs for Weight { + type As = (Compact, Compact); + fn encode_as(&self) -> &(Compact, Compact) { + &(Compact(self.ref_time), Compact(self.proof_size)) + } + fn decode_from((r, s): (Compact, Compact)) -> Result { + Ok(Weight { ref_time: r.0, proof_size: s.0 }) + } +} + +impl From> for Weight { + fn from(x: Compact) -> Weight { + x.0 + } +} + impl Weight { /// Set the reference time part of the weight. pub const fn set_ref_time(mut self, c: u64) -> Self { From 52c9d0546e825f443345c3e71f6884259da77c48 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 16 Sep 2022 14:53:53 +0800 Subject: [PATCH 07/38] Add missing import --- primitives/weights/src/weight_v2.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index eff7c0419ff0a..9fd6ddac791c8 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use codec::{Compact, Decode, Encode, MaxEncodedLen}; +use codec::{Compact, CompactAs, Decode, Encode, MaxEncodedLen}; use core::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign}; use sp_arithmetic::traits::{Bounded, CheckedAdd, CheckedSub, Zero}; use sp_debug_derive::RuntimeDebug; From 9b1f37e84cb0dd1b55e5ffd258596ebe9a5c7be3 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 16 Sep 2022 22:22:45 +0800 Subject: [PATCH 08/38] Fixes --- primitives/weights/src/weight_v2.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index 9fd6ddac791c8..939b55aba132c 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -52,12 +52,12 @@ impl Decode for Weight { } impl CompactAs for Weight { - type As = (Compact, Compact); - fn encode_as(&self) -> &(Compact, Compact) { - &(Compact(self.ref_time), Compact(self.proof_size)) + type As = Weight; + fn encode_as(&self) -> &Weight { + self } - fn decode_from((r, s): (Compact, Compact)) -> Result { - Ok(Weight { ref_time: r.0, proof_size: s.0 }) + fn decode_from(w: Weight) -> Result { + Ok(w) } } From 3438ada6d84396ac2937cb39a73edf0bee57ee4d Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 16 Sep 2022 22:33:52 +0800 Subject: [PATCH 09/38] Remove CompactAs implementation --- primitives/weights/src/weight_v2.rs | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index 939b55aba132c..a0c802c4ed610 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use codec::{Compact, CompactAs, Decode, Encode, MaxEncodedLen}; +use codec::{Compact, Decode, Encode, MaxEncodedLen}; use core::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign}; use sp_arithmetic::traits::{Bounded, CheckedAdd, CheckedSub, Zero}; use sp_debug_derive::RuntimeDebug; @@ -51,22 +51,6 @@ impl Decode for Weight { } } -impl CompactAs for Weight { - type As = Weight; - fn encode_as(&self) -> &Weight { - self - } - fn decode_from(w: Weight) -> Result { - Ok(w) - } -} - -impl From> for Weight { - fn from(x: Compact) -> Weight { - x.0 - } -} - impl Weight { /// Set the reference time part of the weight. pub const fn set_ref_time(mut self, c: u64) -> Self { From 3b36396b79a66a90135e1656bd043b42e8b79eaa Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 17 Sep 2022 00:13:08 +0800 Subject: [PATCH 10/38] Properly migrate from 1D weight --- primitives/weights/src/weight_v2.rs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index a0c802c4ed610..89e42b6ca1bdc 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -36,17 +36,11 @@ pub struct Weight { // Custom Decode implementation for the purposes of migrating from 1D weights. impl Decode for Weight { fn decode(input: &mut I) -> Result { - let compact_ref_time = match Compact::::decode(input) { - Ok(r) => r, - Err(_) => { - // Try decoding it in the old way where we only had a non-compact ref time weight - let ref_time = u64::decode(input) - .map_err(|e| e.chain("Could not decode `Weight::ref_time`"))?; - return Ok(Self { ref_time, proof_size: 0 }) - }, - }; + let compact_ref_time = Compact::::decode(input) + .map_err(|e| e.chain("Could not decode `Weight::ref_time`"))?; let compact_proof_size = Compact::::decode(input) - .map_err(|e| e.chain("Could not decode `Weight::proof_size`"))?; + // Likely coming from 1D weight -- migrate to 2D by defaulting the proof size to 0 + .unwrap_or(Compact(0)); Ok(Self { ref_time: compact_ref_time.0, proof_size: compact_proof_size.0 }) } } From 7af788c04625a72c4e82fc805e7b4c351c3321f7 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 17 Sep 2022 00:22:44 +0800 Subject: [PATCH 11/38] Remove #[pallet::compact] from Weight parameters --- frame/collective/src/lib.rs | 2 +- frame/contracts/src/lib.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 49da641e3e204..16790b0a16b0a 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -626,7 +626,7 @@ pub mod pallet { origin: OriginFor, proposal_hash: T::Hash, #[pallet::compact] index: ProposalIndex, - #[pallet::compact] proposal_weight_bound: Weight, + proposal_weight_bound: Weight, #[pallet::compact] length_bound: u32, ) -> DispatchResultWithPostInfo { let _ = ensure_signed(origin)?; diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index 48f1668440387..90c1ebfeebac6 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -438,7 +438,7 @@ pub mod pallet { origin: OriginFor, dest: AccountIdLookupOf, #[pallet::compact] value: BalanceOf, - #[pallet::compact] gas_limit: Weight, + gas_limit: Weight, storage_deposit_limit: Option< as codec::HasCompact>::Type>, data: Vec, ) -> DispatchResultWithPostInfo { @@ -494,7 +494,7 @@ pub mod pallet { pub fn instantiate_with_code( origin: OriginFor, #[pallet::compact] value: BalanceOf, - #[pallet::compact] gas_limit: Weight, + gas_limit: Weight, storage_deposit_limit: Option< as codec::HasCompact>::Type>, code: Vec, data: Vec, @@ -535,7 +535,7 @@ pub mod pallet { pub fn instantiate( origin: OriginFor, #[pallet::compact] value: BalanceOf, - #[pallet::compact] gas_limit: Weight, + gas_limit: Weight, storage_deposit_limit: Option< as codec::HasCompact>::Type>, code_hash: CodeHash, data: Vec, From f4b98aa0cb483643c2a81cd6f9257c1e7edd28a0 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sun, 18 Sep 2022 13:08:31 +0800 Subject: [PATCH 12/38] More #[pallet::compact] removals --- frame/alliance/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/alliance/src/lib.rs b/frame/alliance/src/lib.rs index 9d320c4215a70..ab9327faba0f6 100644 --- a/frame/alliance/src/lib.rs +++ b/frame/alliance/src/lib.rs @@ -626,7 +626,7 @@ pub mod pallet { origin: OriginFor, proposal_hash: T::Hash, #[pallet::compact] index: ProposalIndex, - #[pallet::compact] proposal_weight_bound: Weight, + proposal_weight_bound: Weight, #[pallet::compact] length_bound: u32, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; From eefc1d7002714991f46802f34c2b4747243b8fbf Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sun, 18 Sep 2022 13:11:54 +0800 Subject: [PATCH 13/38] Add unit tests --- primitives/weights/src/weight_v2.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index 89e42b6ca1bdc..6db5caae4c0a5 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -423,3 +423,21 @@ impl SubAssign for Weight { }; } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compact_weight_v1_can_be_decoded_as_v2() { + type WeightV1 = u64; + + let weight_v1: WeightV1 = 12345; + let compact_weight_v1 = Compact(weight_v1); + let encoded = compact_weight_v1.encode(); + + // Decode as weight v2 + let decoded: Weight = Decode::decode(&mut &encoded[..]).unwrap(); + assert_eq!(decoded, Weight { ref_time: weight_v1, proof_size: 0 }); + } +} From 109be741cd23593cc308e991c3431cdb5bf1167a Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 19 Sep 2022 22:42:51 +0800 Subject: [PATCH 14/38] Set appropriate default block proof size --- frame/system/src/limits.rs | 2 +- primitives/weights/src/lib.rs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/frame/system/src/limits.rs b/frame/system/src/limits.rs index e182eb626424d..77a55ee1c62a7 100644 --- a/frame/system/src/limits.rs +++ b/frame/system/src/limits.rs @@ -207,7 +207,7 @@ pub struct BlockWeights { impl Default for BlockWeights { fn default() -> Self { - Self::with_sensible_defaults(1u32 * constants::WEIGHT_PER_SECOND, DEFAULT_NORMAL_RATIO) + Self::with_sensible_defaults(constants::WEIGHT_PER_SECOND + constants::MAX_PROOF_SIZE_WEIGHT, DEFAULT_NORMAL_RATIO) } } diff --git a/primitives/weights/src/lib.rs b/primitives/weights/src/lib.rs index d260f73d41268..57af5b90c6221 100644 --- a/primitives/weights/src/lib.rs +++ b/primitives/weights/src/lib.rs @@ -51,6 +51,8 @@ pub mod constants { pub const WEIGHT_PER_MILLIS: Weight = Weight::from_ref_time(1_000_000_000); pub const WEIGHT_PER_MICROS: Weight = Weight::from_ref_time(1_000_000); pub const WEIGHT_PER_NANOS: Weight = Weight::from_ref_time(1_000); + + pub const MAX_PROOF_SIZE_WEIGHT: Weight = Weight::from_proof_size(u64::MAX); } /// The weight of database operations that the runtime can invoke. From bbf072d822cd2a263f397fa4f181362b4daa0789 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 19 Sep 2022 22:53:01 +0800 Subject: [PATCH 15/38] cargo fmt --- frame/system/src/limits.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frame/system/src/limits.rs b/frame/system/src/limits.rs index 77a55ee1c62a7..6652c0d355712 100644 --- a/frame/system/src/limits.rs +++ b/frame/system/src/limits.rs @@ -207,7 +207,10 @@ pub struct BlockWeights { impl Default for BlockWeights { fn default() -> Self { - Self::with_sensible_defaults(constants::WEIGHT_PER_SECOND + constants::MAX_PROOF_SIZE_WEIGHT, DEFAULT_NORMAL_RATIO) + Self::with_sensible_defaults( + constants::WEIGHT_PER_SECOND + constants::MAX_PROOF_SIZE_WEIGHT, + DEFAULT_NORMAL_RATIO, + ) } } From 1a072869c879e09cdc9ea2d0b9fe191e6ffe1a87 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 20 Sep 2022 01:51:51 +0800 Subject: [PATCH 16/38] Remove nonsensical weight constant --- frame/system/src/limits.rs | 5 +---- primitives/weights/src/lib.rs | 2 -- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/frame/system/src/limits.rs b/frame/system/src/limits.rs index 6652c0d355712..641efc8f6bea7 100644 --- a/frame/system/src/limits.rs +++ b/frame/system/src/limits.rs @@ -207,10 +207,7 @@ pub struct BlockWeights { impl Default for BlockWeights { fn default() -> Self { - Self::with_sensible_defaults( - constants::WEIGHT_PER_SECOND + constants::MAX_PROOF_SIZE_WEIGHT, - DEFAULT_NORMAL_RATIO, - ) + Self::with_sensible_defaults(1u64 * constants::WEIGHT_PER_SECOND, DEFAULT_NORMAL_RATIO) } } diff --git a/primitives/weights/src/lib.rs b/primitives/weights/src/lib.rs index 57af5b90c6221..d260f73d41268 100644 --- a/primitives/weights/src/lib.rs +++ b/primitives/weights/src/lib.rs @@ -51,8 +51,6 @@ pub mod constants { pub const WEIGHT_PER_MILLIS: Weight = Weight::from_ref_time(1_000_000_000); pub const WEIGHT_PER_MICROS: Weight = Weight::from_ref_time(1_000_000); pub const WEIGHT_PER_NANOS: Weight = Weight::from_ref_time(1_000); - - pub const MAX_PROOF_SIZE_WEIGHT: Weight = Weight::from_proof_size(u64::MAX); } /// The weight of database operations that the runtime can invoke. From 10aed4c2eb778f0e2900ddd23d83102ac2c982f5 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 20 Sep 2022 01:59:40 +0800 Subject: [PATCH 17/38] Test only for the reference time weight in frame_system::limits --- frame/system/src/limits.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/frame/system/src/limits.rs b/frame/system/src/limits.rs index 641efc8f6bea7..abcaf0e3eda7b 100644 --- a/frame/system/src/limits.rs +++ b/frame/system/src/limits.rs @@ -224,6 +224,7 @@ impl BlockWeights { } let mut error = ValidationErrors::default(); + // TODO: Account for proof size weight in the assertions below for class in DispatchClass::all() { let weights = self.per_class.get(*class); let max_for_class = or_max(weights.max_total); @@ -232,18 +233,16 @@ impl BlockWeights { // Make sure that if total is set it's greater than base_block && // base_for_class error_assert!( - (max_for_class.all_gt(self.base_block) && max_for_class.all_gt(base_for_class)) - || max_for_class == Weight::zero(), + (max_for_class.ref_time() > self.base_block.ref_time() && max_for_class.ref_time() > base_for_class.ref_time()) + || max_for_class.ref_time() == 0, &mut error, "[{:?}] {:?} (total) has to be greater than {:?} (base block) & {:?} (base extrinsic)", class, max_for_class, self.base_block, base_for_class, ); // Max extrinsic can't be greater than max_for_class. error_assert!( - weights - .max_extrinsic - .unwrap_or(Weight::zero()) - .all_lte(max_for_class.saturating_sub(base_for_class)), + weights.max_extrinsic.unwrap_or(Weight::zero()).ref_time() <= + max_for_class.saturating_sub(base_for_class).ref_time(), &mut error, "[{:?}] {:?} (max_extrinsic) can't be greater than {:?} (max for class)", class, @@ -252,14 +251,14 @@ impl BlockWeights { ); // Max extrinsic should not be 0 error_assert!( - weights.max_extrinsic.unwrap_or_else(Weight::max_value).all_gt(Weight::zero()), + weights.max_extrinsic.unwrap_or_else(Weight::max_value).ref_time() > 0, &mut error, "[{:?}] {:?} (max_extrinsic) must not be 0. Check base cost and average initialization cost.", class, weights.max_extrinsic, ); // Make sure that if reserved is set it's greater than base_for_class. error_assert!( - reserved.all_gt(base_for_class) || reserved == Weight::zero(), + reserved.ref_time() > base_for_class.ref_time() || reserved.ref_time() == 0, &mut error, "[{:?}] {:?} (reserved) has to be greater than {:?} (base extrinsic) if set", class, @@ -268,7 +267,7 @@ impl BlockWeights { ); // Make sure max block is greater than max_total if it's set. error_assert!( - self.max_block.all_gte(weights.max_total.unwrap_or(Weight::zero())), + self.max_block.ref_time() >= weights.max_total.unwrap_or(Weight::zero()).ref_time(), &mut error, "[{:?}] {:?} (max block) has to be greater than {:?} (max for class)", class, @@ -277,7 +276,7 @@ impl BlockWeights { ); // Make sure we can fit at least one extrinsic. error_assert!( - self.max_block.all_gt(base_for_class + self.base_block), + self.max_block.ref_time() > (base_for_class + self.base_block).ref_time(), &mut error, "[{:?}] {:?} (max block) must fit at least one extrinsic {:?} (base weight)", class, From be3d2f6c89efcb1667a61f03442e655e2559cdc0 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 20 Sep 2022 15:40:41 +0800 Subject: [PATCH 18/38] Only check for reference time weight on idle --- frame/executive/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 96e71512e54bc..ed045b8e4c95b 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -462,7 +462,8 @@ where let max_weight = >::get().max_block; let remaining_weight = max_weight.saturating_sub(weight.total()); - if remaining_weight.all_gt(Weight::zero()) { + // TODO: account for proof size weight + if remaining_weight.ref_time() > 0 { let used_weight = >::on_idle( block_number, remaining_weight, From 79087137c93bf3a6f0e686fc84eb32b0176e5b4d Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 22 Sep 2022 17:02:03 +0800 Subject: [PATCH 19/38] Use destructuring syntax --- primitives/weights/src/weight_v2.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index 6db5caae4c0a5..6d85e41c15076 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -36,12 +36,12 @@ pub struct Weight { // Custom Decode implementation for the purposes of migrating from 1D weights. impl Decode for Weight { fn decode(input: &mut I) -> Result { - let compact_ref_time = Compact::::decode(input) + let Compact(ref_time) = Compact::::decode(input) .map_err(|e| e.chain("Could not decode `Weight::ref_time`"))?; - let compact_proof_size = Compact::::decode(input) + let Compact(proof_size) = Compact::::decode(input) // Likely coming from 1D weight -- migrate to 2D by defaulting the proof size to 0 .unwrap_or(Compact(0)); - Ok(Self { ref_time: compact_ref_time.0, proof_size: compact_proof_size.0 }) + Ok(Self { ref_time, proof_size }) } } From e313544460d6d3ef08f9786c411bd7052fb84f65 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 22 Sep 2022 21:43:48 +0800 Subject: [PATCH 20/38] Update test expectations --- frame/executive/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 1464672d039bf..79d1a0518667a 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -948,11 +948,11 @@ mod tests { fn block_import_works() { block_import_works_inner( new_test_ext_v0(1), - hex!("1039e1a4bd0cf5deefe65f313577e70169c41c7773d6acf31ca8d671397559f5").into(), + hex!("0d786e24c1f9e6ce237806a22c005bbbc7dee4edd6692b6c5442843d164392de").into(), ); block_import_works_inner( new_test_ext(1), - hex!("75e7d8f360d375bbe91bcf8019c01ab6362448b4a89e3b329717eb9d910340e5").into(), + hex!("348485a4ab856467b440167e45f99b491385e8528e09b0e51f85f814a3021c93").into(), ); } fn block_import_works_inner(mut ext: sp_io::TestExternalities, state_root: H256) { From 91a03b237b65a03f788e4327732e0f2b4607fc02 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 22 Sep 2022 23:33:50 +0800 Subject: [PATCH 21/38] Fixes --- frame/babe/src/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frame/babe/src/tests.rs b/frame/babe/src/tests.rs index 8d2a9b326cd0f..68c60f51cd3bc 100644 --- a/frame/babe/src/tests.rs +++ b/frame/babe/src/tests.rs @@ -852,7 +852,8 @@ fn valid_equivocation_reports_dont_pay_fees() { .get_dispatch_info(); // it should have non-zero weight and the fee has to be paid. - assert!(info.weight.all_gt(Weight::zero())); + // TODO: maybe factor in proof size weight + assert!(info.weight.ref_time() > 0); assert_eq!(info.pays_fee, Pays::Yes); // report the equivocation. From e93dd457b9a0ae46b86f7a0603aa3e931c4483bd Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 22 Sep 2022 23:50:36 +0800 Subject: [PATCH 22/38] Fixes --- frame/contracts/src/wasm/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 126a37e9401ec..2e2b0910dcec1 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -1547,8 +1547,9 @@ mod tests { let gas_left = Weight::decode(&mut &*output.data).unwrap(); let actual_left = ext.gas_meter.gas_left(); - assert!(gas_left.all_lt(gas_limit), "gas_left must be less than initial"); - assert!(gas_left.all_gt(actual_left), "gas_left must be greater than final"); + // TODO: maybe factor in proof size weight + assert!(gas_left.ref_time() < gas_limit, "gas_left must be less than initial"); + assert!(gas_left.ref_time() > actual_left, "gas_left must be greater than final"); } const CODE_VALUE_TRANSFERRED: &str = r#" From 9fe54f9d93d0b5857fa0cdd8f635aeafa40c7cad Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 23 Sep 2022 00:10:24 +0800 Subject: [PATCH 23/38] Fixes --- frame/contracts/src/wasm/mod.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 2e2b0910dcec1..526f80a777889 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -1548,8 +1548,11 @@ mod tests { let gas_left = Weight::decode(&mut &*output.data).unwrap(); let actual_left = ext.gas_meter.gas_left(); // TODO: maybe factor in proof size weight - assert!(gas_left.ref_time() < gas_limit, "gas_left must be less than initial"); - assert!(gas_left.ref_time() > actual_left, "gas_left must be greater than final"); + assert!(gas_left.ref_time() < gas_limit.ref_time(), "gas_left must be less than initial"); + assert!( + gas_left.ref_time() > actual_left.ref_time(), + "gas_left must be greater than final" + ); } const CODE_VALUE_TRANSFERRED: &str = r#" @@ -1947,7 +1950,7 @@ mod tests { )] ); - assert!(mock_ext.gas_meter.gas_left().all_gt(Weight::zero())); + assert!(mock_ext.gas_meter.gas_left().ref_time() > 0); } const CODE_DEPOSIT_EVENT_MAX_TOPICS: &str = r#" From acd6d4b0d2811e8412e31630fccae003aeaede97 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 23 Sep 2022 01:48:13 +0800 Subject: [PATCH 24/38] Correctly migrate from 1D weights --- primitives/weights/src/weight_v2.rs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index 6d85e41c15076..d4894904d80aa 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -36,12 +36,19 @@ pub struct Weight { // Custom Decode implementation for the purposes of migrating from 1D weights. impl Decode for Weight { fn decode(input: &mut I) -> Result { - let Compact(ref_time) = Compact::::decode(input) - .map_err(|e| e.chain("Could not decode `Weight::ref_time`"))?; - let Compact(proof_size) = Compact::::decode(input) - // Likely coming from 1D weight -- migrate to 2D by defaulting the proof size to 0 - .unwrap_or(Compact(0)); - Ok(Self { ref_time, proof_size }) + // Try and decode as V1 first... + let ref_time = match u64::decode(input) { + Ok(r) => r, + // ...and if it fails, decode as V2 + Err(_) => { + let Compact(ref_time) = Compact::::decode(input) + .map_err(|e| e.chain("Could not decode `Weight::ref_time`"))?; + let Compact(proof_size) = Compact::::decode(input) + .map_err(|e| e.chain("Could not decode `Weight::proof_size`"))?; + return Ok(Self { ref_time, proof_size }) + } + }; + Ok(Self { ref_time, proof_size: 0 }) } } @@ -433,8 +440,7 @@ mod tests { type WeightV1 = u64; let weight_v1: WeightV1 = 12345; - let compact_weight_v1 = Compact(weight_v1); - let encoded = compact_weight_v1.encode(); + let encoded = weight_v1.encode(); // Decode as weight v2 let decoded: Weight = Decode::decode(&mut &encoded[..]).unwrap(); From 386d4854f14c0f4a20cd3812948e78c9021bb02a Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 23 Sep 2022 02:36:06 +0800 Subject: [PATCH 25/38] cargo fmt --- primitives/weights/src/weight_v2.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index d4894904d80aa..cba179a62a583 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -46,7 +46,7 @@ impl Decode for Weight { let Compact(proof_size) = Compact::::decode(input) .map_err(|e| e.chain("Could not decode `Weight::proof_size`"))?; return Ok(Self { ref_time, proof_size }) - } + }, }; Ok(Self { ref_time, proof_size: 0 }) } From e85c05e5e855d751781cf466790fa4838d7d82ad Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 26 Sep 2022 18:16:32 +0800 Subject: [PATCH 26/38] Migrate using extra extrinsics instead of custom Decode --- frame/alliance/src/lib.rs | 62 ++++++++-- frame/collective/src/lib.rs | 69 ++++++++++- frame/contracts/src/lib.rs | 179 ++++++++++++++++++++++++++-- primitives/weights/src/lib.rs | 21 +++- primitives/weights/src/weight_v2.rs | 42 ++----- 5 files changed, 312 insertions(+), 61 deletions(-) diff --git a/frame/alliance/src/lib.rs b/frame/alliance/src/lib.rs index 8922c774cd49a..0164d450dfd6c 100644 --- a/frame/alliance/src/lib.rs +++ b/frame/alliance/src/lib.rs @@ -120,7 +120,7 @@ use frame_support::{ ChangeMembers, Currency, Get, InitializeMembers, IsSubType, OnUnbalanced, ReservableCurrency, }, - weights::Weight, + weights::{OldWeight, Weight}, }; use pallet_identity::IdentityField; @@ -620,25 +620,22 @@ pub mod pallet { .max(T::WeightInfo::close_early_disapproved(x, y, p2)) .max(T::WeightInfo::close_approved(b, x, y, p2)) .max(T::WeightInfo::close_disapproved(x, y, p2)) - .saturating_add(p1) + .saturating_add(p1.into()) })] - pub fn close( + #[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, - proposal_weight_bound: Weight, + #[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); - let info = T::ProposalProvider::close_proposal( - proposal_hash, - index, - proposal_weight_bound, - length_bound, - )?; - Ok(info.into()) + Self::do_close(proposal_hash, index, proposal_weight_bound, length_bound) } /// Initialize the Alliance, onboard founders, fellows, and allies. @@ -985,6 +982,34 @@ pub mod pallet { Self::deposit_event(Event::UnscrupulousItemRemoved { items }); Ok(()) } + + /// Close a vote that is either approved, disapproved, or whose voting period has ended. + /// + /// Requires the sender to be a founder or fellow. + #[pallet::weight({ + let b = *length_bound; + let x = T::MaxFounders::get(); + let y = T::MaxFellows::get(); + let p1 = *proposal_weight_bound; + let p2 = T::MaxProposals::get(); + T::WeightInfo::close_early_approved(b, x, y, p2) + .max(T::WeightInfo::close_early_disapproved(x, y, p2)) + .max(T::WeightInfo::close_approved(b, x, y, p2)) + .max(T::WeightInfo::close_disapproved(x, y, p2)) + .saturating_add(p1) + })] + pub fn close( + origin: OriginFor, + proposal_hash: T::Hash, + #[pallet::compact] index: ProposalIndex, + proposal_weight_bound: Weight, + #[pallet::compact] length_bound: u32, + ) -> DispatchResultWithPostInfo { + let who = ensure_signed(origin)?; + ensure!(Self::has_voting_rights(&who), Error::::NoVotingRights); + + Self::do_close(proposal_hash, index, proposal_weight_bound, length_bound) + } } } @@ -1197,4 +1222,19 @@ impl, I: 'static> Pallet { } res } + + fn do_close( + proposal_hash: T::Hash, + index: ProposalIndex, + proposal_weight_bound: Weight, + length_bound: u32, + ) -> DispatchResultWithPostInfo { + let info = T::ProposalProvider::close_proposal( + proposal_hash, + index, + proposal_weight_bound, + length_bound, + )?; + Ok(info.into()) + } } diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 4ecbc527e113e..0ee1af52f0175 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::Weight, + weights::{OldWeight, Weight}, }; #[cfg(test)] @@ -620,17 +620,20 @@ pub mod pallet { .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) + .saturating_add(p1.into()) }, DispatchClass::Operational ))] - pub fn close( + #[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, - proposal_weight_bound: Weight, + #[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) @@ -659,6 +662,64 @@ pub mod pallet { let proposal_count = Self::do_disapprove_proposal(proposal_hash); Ok(Some(T::WeightInfo::disapprove_proposal(proposal_count)).into()) } + + /// 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. + /// + /// # + /// ## Weight + /// - `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) + /// - DB: + /// - 2 storage reads (`Members`: codec `O(M)`, `Prime`: codec `O(1)`) + /// - 3 mutations (`Voting`: codec `O(M)`, `ProposalOf`: codec `O(B)`, `Proposals`: codec + /// `O(P2)`) + /// - any mutations done while executing `proposal` (`P1`) + /// - up to 3 events + /// # + #[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) + }, + DispatchClass::Operational + ))] + pub fn close( + origin: OriginFor, + proposal_hash: T::Hash, + #[pallet::compact] index: ProposalIndex, + proposal_weight_bound: Weight, + #[pallet::compact] length_bound: u32, + ) -> DispatchResultWithPostInfo { + let _ = ensure_signed(origin)?; + + Self::do_close(proposal_hash, index, proposal_weight_bound, length_bound) + } } } diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index 83935cc6fdcec..f9a1c8decf042 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -113,7 +113,7 @@ use frame_support::{ tokens::fungible::Inspect, ConstU32, Contains, Currency, Get, Randomness, ReservableCurrency, Time, }, - weights::Weight, + weights::{OldWeight, Weight}, BoundedVec, WeakBoundedVec, }; use frame_system::{limits::BlockWeights, Pallet as System}; @@ -429,15 +429,18 @@ pub mod pallet { /// * If the account is a regular account, any value will be transferred. /// * If no account exists and the call value is not less than `existential_deposit`, /// a regular account will be created and any value will be transferred. - #[pallet::weight(T::WeightInfo::call().saturating_add(*gas_limit))] - pub fn call( + #[pallet::weight(T::WeightInfo::call().saturating_add((*gas_limit).into()))] + #[allow(deprecated)] + #[deprecated(note = "1D weight is used in this extrinsic, please migrate to `call`")] + pub fn call_old_weight( origin: OriginFor, dest: AccountIdLookupOf, #[pallet::compact] value: BalanceOf, - gas_limit: Weight, + #[pallet::compact] gas_limit: OldWeight, storage_deposit_limit: Option< as codec::HasCompact>::Type>, data: Vec, ) -> DispatchResultWithPostInfo { + let gas_limit: Weight = gas_limit.into(); let origin = ensure_signed(origin)?; let dest = T::Lookup::lookup(dest)?; let mut output = Self::internal_call( @@ -485,17 +488,22 @@ pub mod pallet { /// - The `deploy` function is executed in the context of the newly-created account. #[pallet::weight( T::WeightInfo::instantiate_with_code(code.len() as u32, salt.len() as u32) - .saturating_add(*gas_limit) + .saturating_add((*gas_limit).into()) )] - pub fn instantiate_with_code( + #[allow(deprecated)] + #[deprecated( + note = "1D weight is used in this extrinsic, please migrate to `instantiate_with_code`" + )] + pub fn instantiate_with_code_old_weight( origin: OriginFor, #[pallet::compact] value: BalanceOf, - gas_limit: Weight, + #[pallet::compact] gas_limit: OldWeight, storage_deposit_limit: Option< as codec::HasCompact>::Type>, code: Vec, data: Vec, salt: Vec, ) -> DispatchResultWithPostInfo { + let gas_limit: Weight = gas_limit.into(); let origin = ensure_signed(origin)?; let code_len = code.len() as u32; let salt_len = salt.len() as u32; @@ -526,17 +534,20 @@ pub mod pallet { /// code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary /// must be supplied. #[pallet::weight( - T::WeightInfo::instantiate(salt.len() as u32).saturating_add(*gas_limit) + T::WeightInfo::instantiate(salt.len() as u32).saturating_add((*gas_limit).into()) )] - pub fn instantiate( + #[allow(deprecated)] + #[deprecated(note = "1D weight is used in this extrinsic, please migrate to `instantiate`")] + pub fn instantiate_old_weight( origin: OriginFor, #[pallet::compact] value: BalanceOf, - gas_limit: Weight, + #[pallet::compact] gas_limit: OldWeight, storage_deposit_limit: Option< as codec::HasCompact>::Type>, code_hash: CodeHash, data: Vec, salt: Vec, ) -> DispatchResultWithPostInfo { + let gas_limit: Weight = gas_limit.into(); let origin = ensure_signed(origin)?; let salt_len = salt.len() as u32; let mut output = Self::internal_instantiate( @@ -639,6 +650,154 @@ pub mod pallet { Ok(()) }) } + + /// Makes a call to an account, optionally transferring some balance. + /// + /// # Parameters + /// + /// * `dest`: Address of the contract to call. + /// * `value`: The balance to transfer from the `origin` to `dest`. + /// * `gas_limit`: The gas limit enforced when executing the constructor. + /// * `storage_deposit_limit`: The maximum amount of balance that can be charged from the + /// caller to pay for the storage consumed. + /// * `data`: The input data to pass to the contract. + /// + /// * If the account is a smart-contract account, the associated code will be + /// executed and any value will be transferred. + /// * If the account is a regular account, any value will be transferred. + /// * If no account exists and the call value is not less than `existential_deposit`, + /// a regular account will be created and any value will be transferred. + #[pallet::weight(T::WeightInfo::call().saturating_add(*gas_limit))] + pub fn call( + origin: OriginFor, + dest: AccountIdLookupOf, + #[pallet::compact] value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + data: Vec, + ) -> DispatchResultWithPostInfo { + let gas_limit: Weight = gas_limit.into(); + let origin = ensure_signed(origin)?; + let dest = T::Lookup::lookup(dest)?; + let mut output = Self::internal_call( + origin, + dest, + value, + gas_limit, + storage_deposit_limit.map(Into::into), + data, + None, + ); + if let Ok(retval) = &output.result { + if retval.did_revert() { + output.result = Err(>::ContractReverted.into()); + } + } + output.gas_meter.into_dispatch_result(output.result, T::WeightInfo::call()) + } + + /// Instantiates a new contract from the supplied `code` optionally transferring + /// some balance. + /// + /// This dispatchable has the same effect as calling [`Self::upload_code`] + + /// [`Self::instantiate`]. Bundling them together provides efficiency gains. Please + /// also check the documentation of [`Self::upload_code`]. + /// + /// # Parameters + /// + /// * `value`: The balance to transfer from the `origin` to the newly created contract. + /// * `gas_limit`: The gas limit enforced when executing the constructor. + /// * `storage_deposit_limit`: The maximum amount of balance that can be charged/reserved + /// from the caller to pay for the storage consumed. + /// * `code`: The contract code to deploy in raw bytes. + /// * `data`: The input data to pass to the contract constructor. + /// * `salt`: Used for the address derivation. See [`Pallet::contract_address`]. + /// + /// Instantiation is executed as follows: + /// + /// - The supplied `code` is instrumented, deployed, and a `code_hash` is created for that + /// code. + /// - If the `code_hash` already exists on the chain the underlying `code` will be shared. + /// - The destination address is computed based on the sender, code_hash and the salt. + /// - The smart-contract account is created at the computed address. + /// - The `value` is transferred to the new account. + /// - The `deploy` function is executed in the context of the newly-created account. + #[pallet::weight( + T::WeightInfo::instantiate_with_code(code.len() as u32, salt.len() as u32) + .saturating_add(*gas_limit) + )] + pub fn instantiate_with_code( + origin: OriginFor, + #[pallet::compact] value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + code: Vec, + data: Vec, + salt: Vec, + ) -> DispatchResultWithPostInfo { + let origin = ensure_signed(origin)?; + let code_len = code.len() as u32; + let salt_len = salt.len() as u32; + let mut output = Self::internal_instantiate( + origin, + value, + gas_limit, + storage_deposit_limit.map(Into::into), + Code::Upload(Bytes(code)), + data, + salt, + None, + ); + if let Ok(retval) = &output.result { + if retval.1.did_revert() { + output.result = Err(>::ContractReverted.into()); + } + } + output.gas_meter.into_dispatch_result( + output.result.map(|(_address, result)| result), + T::WeightInfo::instantiate_with_code(code_len, salt_len), + ) + } + + /// Instantiates a contract from a previously deployed wasm binary. + /// + /// This function is identical to [`Self::instantiate_with_code`] but without the + /// code deployment step. Instead, the `code_hash` of an on-chain deployed wasm binary + /// must be supplied. + #[pallet::weight( + T::WeightInfo::instantiate(salt.len() as u32).saturating_add(*gas_limit) + )] + pub fn instantiate( + origin: OriginFor, + #[pallet::compact] value: BalanceOf, + gas_limit: Weight, + storage_deposit_limit: Option< as codec::HasCompact>::Type>, + code_hash: CodeHash, + data: Vec, + salt: Vec, + ) -> DispatchResultWithPostInfo { + let origin = ensure_signed(origin)?; + let salt_len = salt.len() as u32; + let mut output = Self::internal_instantiate( + origin, + value, + gas_limit, + storage_deposit_limit.map(Into::into), + Code::Existing(code_hash), + data, + salt, + None, + ); + if let Ok(retval) = &output.result { + if retval.1.did_revert() { + output.result = Err(>::ContractReverted.into()); + } + } + output.gas_meter.into_dispatch_result( + output.result.map(|(_address, output)| output), + T::WeightInfo::instantiate(salt_len), + ) + } } #[pallet::event] diff --git a/primitives/weights/src/lib.rs b/primitives/weights/src/lib.rs index d260f73d41268..ca004757c83b3 100644 --- a/primitives/weights/src/lib.rs +++ b/primitives/weights/src/lib.rs @@ -30,7 +30,7 @@ extern crate self as sp_weights; mod weight_v2; -use codec::{Decode, Encode}; +use codec::{CompactAs, Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; @@ -53,6 +53,25 @@ pub mod constants { pub const WEIGHT_PER_NANOS: Weight = Weight::from_ref_time(1_000); } +/// The old weight type. +/// +/// NOTE: This type exists purely for compatibility purposes! Use [`weight_v2::Weight`] in all other +/// cases. +#[derive( + Decode, + Encode, + CompactAs, + PartialEq, + Eq, + Clone, + Copy, + RuntimeDebug, + Default, + MaxEncodedLen, + TypeInfo, +)] +pub struct OldWeight(u64); + /// The weight of database operations that the runtime can invoke. /// /// NOTE: This is currently only measured in computational time, and will probably diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index cba179a62a583..72ee13662ee04 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -15,14 +15,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -use codec::{Compact, Decode, Encode, MaxEncodedLen}; +use codec::{Decode, Encode, MaxEncodedLen}; use core::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign}; use sp_arithmetic::traits::{Bounded, CheckedAdd, CheckedSub, Zero}; use sp_debug_derive::RuntimeDebug; use super::*; -#[derive(Encode, MaxEncodedLen, TypeInfo, Eq, PartialEq, Copy, Clone, RuntimeDebug, Default)] +#[derive( + Encode, Decode, MaxEncodedLen, TypeInfo, Eq, PartialEq, Copy, Clone, RuntimeDebug, Default, +)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct Weight { #[codec(compact)] @@ -33,22 +35,9 @@ pub struct Weight { proof_size: u64, } -// Custom Decode implementation for the purposes of migrating from 1D weights. -impl Decode for Weight { - fn decode(input: &mut I) -> Result { - // Try and decode as V1 first... - let ref_time = match u64::decode(input) { - Ok(r) => r, - // ...and if it fails, decode as V2 - Err(_) => { - let Compact(ref_time) = Compact::::decode(input) - .map_err(|e| e.chain("Could not decode `Weight::ref_time`"))?; - let Compact(proof_size) = Compact::::decode(input) - .map_err(|e| e.chain("Could not decode `Weight::proof_size`"))?; - return Ok(Self { ref_time, proof_size }) - }, - }; - Ok(Self { ref_time, proof_size: 0 }) +impl From for Weight { + fn from(old: OldWeight) -> Self { + Weight::from_ref_time(old.0) } } @@ -430,20 +419,3 @@ impl SubAssign for Weight { }; } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn compact_weight_v1_can_be_decoded_as_v2() { - type WeightV1 = u64; - - let weight_v1: WeightV1 = 12345; - let encoded = weight_v1.encode(); - - // Decode as weight v2 - let decoded: Weight = Decode::decode(&mut &encoded[..]).unwrap(); - assert_eq!(decoded, Weight { ref_time: weight_v1, proof_size: 0 }); - } -} From f541cb2f55bc1ba1029e0c221576396cc4a4004c Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 26 Sep 2022 18:55:02 +0800 Subject: [PATCH 27/38] Fixes --- primitives/weights/src/weight_v2.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/primitives/weights/src/weight_v2.rs b/primitives/weights/src/weight_v2.rs index 2cfd8e2c4c90a..a8eaf79a28711 100644 --- a/primitives/weights/src/weight_v2.rs +++ b/primitives/weights/src/weight_v2.rs @@ -231,28 +231,28 @@ impl Weight { /// /// Is only overflow safe when evaluated at compile-time. pub const fn add(self, scalar: u64) -> Self { - Self { ref_time: self.ref_time + scalar } + Self { ref_time: self.ref_time + scalar, proof_size: self.proof_size + scalar } } /// Constant version of Sub with u64. /// /// Is only overflow safe when evaluated at compile-time. pub const fn sub(self, scalar: u64) -> Self { - Self { ref_time: self.ref_time - scalar } + Self { ref_time: self.ref_time - scalar, proof_size: self.proof_size - scalar } } /// Constant version of Div with u64. /// /// Is only overflow safe when evaluated at compile-time. pub const fn div(self, scalar: u64) -> Self { - Self { ref_time: self.ref_time / scalar } + Self { ref_time: self.ref_time / scalar, proof_size: self.proof_size / scalar } } /// Constant version of Mul with u64. /// /// Is only overflow safe when evaluated at compile-time. pub const fn mul(self, scalar: u64) -> Self { - Self { ref_time: self.ref_time * scalar } + Self { ref_time: self.ref_time * scalar, proof_size: self.proof_size * scalar } } /// Returns true if any of `self`'s constituent weights is strictly greater than that of the From b34b49de34671b336af99ecac04f2c6ce87ac0cd Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 27 Sep 2022 00:40:16 +0800 Subject: [PATCH 28/38] Silence dispatch call warnings that were previously allowed --- .../procedural/src/pallet/expand/call.rs | 20 +++++++++++++++++++ .../procedural/src/pallet/parse/call.rs | 3 +++ 2 files changed, 23 insertions(+) diff --git a/frame/support/procedural/src/pallet/expand/call.rs b/frame/support/procedural/src/pallet/expand/call.rs index 18d5adee63ad6..39d16109aa8fa 100644 --- a/frame/support/procedural/src/pallet/expand/call.rs +++ b/frame/support/procedural/src/pallet/expand/call.rs @@ -16,6 +16,7 @@ // limitations under the License. use crate::{pallet::Def, COUNTER}; +use quote::ToTokens; use syn::spanned::Spanned; /// @@ -158,6 +159,24 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { }); } + // Extracts #[allow] attributes, necessary so that we don't run into compiler warnings + let maybe_allow_attrs = methods + .iter() + .map(|method| { + method + .attrs + .iter() + .find(|attr| { + if let Ok(syn::Meta::List(syn::MetaList { path, .. })) = attr.parse_meta() { + path.segments.last().map(|seg| seg.ident == "allow").unwrap_or(false) + } else { + false + } + }) + .map_or(proc_macro2::TokenStream::new(), |attr| attr.to_token_stream()) + }) + .collect::>(); + quote::quote_spanned!(span => #[doc(hidden)] pub mod __substrate_call_check { @@ -289,6 +308,7 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { #frame_support::sp_tracing::enter_span!( #frame_support::sp_tracing::trace_span!(stringify!(#fn_name)) ); + #maybe_allow_attrs <#pallet_ident<#type_use_gen>>::#fn_name(origin, #( #args_name, )* ) .map(Into::into).map_err(Into::into) }, diff --git a/frame/support/procedural/src/pallet/parse/call.rs b/frame/support/procedural/src/pallet/parse/call.rs index 336e08c3d39b7..f7b2c9544d831 100644 --- a/frame/support/procedural/src/pallet/parse/call.rs +++ b/frame/support/procedural/src/pallet/parse/call.rs @@ -61,6 +61,8 @@ pub struct CallVariantDef { pub call_index: u8, /// Docs, used for metadata. pub docs: Vec, + /// Attributes annotated at the top of the dispatchable function. + pub attrs: Vec, } /// Attributes for functions in call impl block. @@ -287,6 +289,7 @@ impl CallDef { call_index: final_index, args, docs, + attrs: method.attrs.clone(), }); } else { let msg = "Invalid pallet::call, only method accepted"; From 000ccad336af9df1668a385a116ffa699afb9f67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Thei=C3=9Fen?= Date: Mon, 26 Sep 2022 19:16:52 +0200 Subject: [PATCH 29/38] Fix gas_left test --- frame/contracts/src/wasm/mod.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 526f80a777889..d7115c2a1807d 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -1545,14 +1545,11 @@ mod tests { let output = execute(CODE_GAS_LEFT, vec![], &mut ext).unwrap(); - let gas_left = Weight::decode(&mut &*output.data).unwrap(); + let gas_left = u64::decode(&mut &*output.data).unwrap(); let actual_left = ext.gas_meter.gas_left(); // TODO: maybe factor in proof size weight - assert!(gas_left.ref_time() < gas_limit.ref_time(), "gas_left must be less than initial"); - assert!( - gas_left.ref_time() > actual_left.ref_time(), - "gas_left must be greater than final" - ); + 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"); } const CODE_VALUE_TRANSFERRED: &str = r#" From 3c4ce9487ea97d2f3aa6909b1d7e93ca92c9bd12 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 27 Sep 2022 01:28:00 +0800 Subject: [PATCH 30/38] Use OldWeight instead of u64 --- frame/contracts/src/wasm/mod.rs | 4 ++-- primitives/weights/src/lib.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index d7115c2a1807d..20965fdd49fa7 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -35,7 +35,7 @@ use crate::{ Schedule, }; use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::dispatch::{DispatchError, DispatchResult}; +use frame_support::{dispatch::{DispatchError, DispatchResult}, weights::OldWeight}; use sp_core::crypto::UncheckedFrom; use sp_sandbox::{SandboxEnvironmentBuilder, SandboxInstance, SandboxMemory}; use sp_std::prelude::*; @@ -1545,7 +1545,7 @@ mod tests { let output = execute(CODE_GAS_LEFT, vec![], &mut ext).unwrap(); - let gas_left = u64::decode(&mut &*output.data).unwrap(); + let OldWeight(gas_left) = OldWeight::decode(&mut &*output.data).unwrap(); let actual_left = ext.gas_meter.gas_left(); // TODO: maybe factor in proof size weight assert!(gas_left < gas_limit.ref_time(), "gas_left must be less than initial"); diff --git a/primitives/weights/src/lib.rs b/primitives/weights/src/lib.rs index ca004757c83b3..e1ac7fcd4e892 100644 --- a/primitives/weights/src/lib.rs +++ b/primitives/weights/src/lib.rs @@ -70,7 +70,7 @@ pub mod constants { MaxEncodedLen, TypeInfo, )] -pub struct OldWeight(u64); +pub struct OldWeight(pub u64); /// The weight of database operations that the runtime can invoke. /// From d3b8a608b2cd937562f38e38eebf5a9f6563471a Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 28 Sep 2022 12:18:04 +0800 Subject: [PATCH 31/38] Fixes --- frame/contracts/src/wasm/mod.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 20965fdd49fa7..80e0d5e8f3b03 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -35,7 +35,7 @@ use crate::{ Schedule, }; use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::{dispatch::{DispatchError, DispatchResult}, weights::OldWeight}; +use frame_support::dispatch::{DispatchError, DispatchResult}; use sp_core::crypto::UncheckedFrom; use sp_sandbox::{SandboxEnvironmentBuilder, SandboxInstance, SandboxMemory}; use sp_std::prelude::*; @@ -274,7 +274,11 @@ mod tests { BalanceOf, CodeHash, Error, Pallet as Contracts, }; use assert_matches::assert_matches; - use frame_support::{assert_ok, dispatch::DispatchResultWithPostInfo, weights::Weight}; + use frame_support::{ + assert_ok, + dispatch::DispatchResultWithPostInfo, + weights::{OldWeight, Weight}, + }; use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pretty_assertions::assert_eq; use sp_core::{Bytes, H256}; From d3e95140bcc41b7d5f7037019eaff3fdedf059f4 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 28 Sep 2022 12:38:42 +0800 Subject: [PATCH 32/38] Only check for reference time weight in election provider --- frame/babe/src/tests.rs | 2 +- frame/contracts/src/wasm/mod.rs | 2 +- frame/election-provider-multi-phase/src/lib.rs | 8 +++++--- frame/election-provider-multi-phase/src/unsigned.rs | 9 ++++++--- 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/frame/babe/src/tests.rs b/frame/babe/src/tests.rs index 68c60f51cd3bc..d4132e6378540 100644 --- a/frame/babe/src/tests.rs +++ b/frame/babe/src/tests.rs @@ -852,7 +852,7 @@ fn valid_equivocation_reports_dont_pay_fees() { .get_dispatch_info(); // it should have non-zero weight and the fee has to be paid. - // TODO: maybe factor in proof size weight + // TODO: account for proof size weight assert!(info.weight.ref_time() > 0); assert_eq!(info.pays_fee, Pays::Yes); diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index 80e0d5e8f3b03..d8b4cd245356e 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -1551,7 +1551,7 @@ mod tests { let OldWeight(gas_left) = OldWeight::decode(&mut &*output.data).unwrap(); let actual_left = ext.gas_meter.gas_left(); - // TODO: maybe factor in proof size weight + // 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"); } diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 05353e5a3ac61..11bbf016b8868 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -1008,8 +1008,9 @@ pub mod pallet { // unlikely to ever return an error: if phase is signed, snapshot will exist. let size = Self::snapshot_metadata().ok_or(Error::::MissingSnapshotMetadata)?; + // TODO: account for proof size weight ensure!( - Self::solution_weight_of(&raw_solution, size).all_lt(T::SignedMaxWeight::get()), + Self::solution_weight_of(&raw_solution, size).ref_time() < T::SignedMaxWeight::get().ref_time(), Error::::SignedTooMuchWeight, ); @@ -2336,8 +2337,9 @@ mod tests { }; let mut active = 1; - while weight_with(active) - .all_lte(::BlockWeights::get().max_block) || + // TODO: account for proof size weight + while weight_with(active).ref_time() <= + ::BlockWeights::get().max_block.ref_time() || active == all_voters { active += 1; diff --git a/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index 833f80c90d13e..281ac37421174 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/frame/election-provider-multi-phase/src/unsigned.rs @@ -638,7 +638,8 @@ impl Miner { }; let next_voters = |current_weight: Weight, voters: u32, step: u32| -> Result { - if current_weight.all_lt(max_weight) { + // TODO: account for proof size weight + if current_weight.ref_time() < max_weight.ref_time() { let next_voters = voters.checked_add(step); match next_voters { Some(voters) if voters < max_voters => Ok(voters), @@ -673,7 +674,8 @@ impl Miner { // Time to finish. We might have reduced less than expected due to rounding error. Increase // one last time if we have any room left, the reduce until we are sure we are below limit. - while voters < max_voters && weight_with(voters + 1).all_lt(max_weight) { + // TODO: account for proof size weight + while voters < max_voters && weight_with(voters + 1).ref_time() < max_weight.ref_time() { voters += 1; } while voters.checked_sub(1).is_some() && weight_with(voters).any_gt(max_weight) { @@ -681,8 +683,9 @@ impl Miner { } let final_decision = voters.min(size.voters); + // TODO: account for proof size weight debug_assert!( - weight_with(final_decision).all_lte(max_weight), + weight_with(final_decision).ref_time() <= max_weight.ref_time(), "weight_with({}) <= {}", final_decision, max_weight, From 4a9f6315dbadeb54af1873252c0962503b26b811 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 28 Sep 2022 12:57:53 +0800 Subject: [PATCH 33/38] Fix test expectations --- frame/system/src/limits.rs | 2 +- frame/transaction-payment/src/types.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/system/src/limits.rs b/frame/system/src/limits.rs index abcaf0e3eda7b..cfc1d261baa01 100644 --- a/frame/system/src/limits.rs +++ b/frame/system/src/limits.rs @@ -224,7 +224,7 @@ impl BlockWeights { } let mut error = ValidationErrors::default(); - // TODO: Account for proof size weight in the assertions below + // TODO: account for proof size weight in the assertions below for class in DispatchClass::all() { let weights = self.per_class.get(*class); let max_for_class = or_max(weights.max_total); diff --git a/frame/transaction-payment/src/types.rs b/frame/transaction-payment/src/types.rs index 1f41ba7b0b72e..8ba7d99519813 100644 --- a/frame/transaction-payment/src/types.rs +++ b/frame/transaction-payment/src/types.rs @@ -140,7 +140,7 @@ mod tests { partial_fee: 1_000_000_u64, }; - let json_str = r#"{"weight":{"ref_time":5},"class":"normal","partialFee":"1000000"}"#; + let json_str = r#"{"weight":{"ref_time":5,"proof_size":0},"class":"normal","partialFee":"1000000"}"#; assert_eq!(serde_json::to_string(&info).unwrap(), json_str); assert_eq!(serde_json::from_str::>(json_str).unwrap(), info); From 12b60f85ce2da6c8452a68d46c2db204f24af087 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 28 Sep 2022 13:11:40 +0800 Subject: [PATCH 34/38] Fix test expectations --- frame/election-provider-multi-phase/src/lib.rs | 3 ++- frame/transaction-payment/src/types.rs | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 11bbf016b8868..bba8139f38f44 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -1010,7 +1010,8 @@ pub mod pallet { // TODO: account for proof size weight ensure!( - Self::solution_weight_of(&raw_solution, size).ref_time() < T::SignedMaxWeight::get().ref_time(), + Self::solution_weight_of(&raw_solution, size).ref_time() < + T::SignedMaxWeight::get().ref_time(), Error::::SignedTooMuchWeight, ); diff --git a/frame/transaction-payment/src/types.rs b/frame/transaction-payment/src/types.rs index 8ba7d99519813..fff41ef6937f5 100644 --- a/frame/transaction-payment/src/types.rs +++ b/frame/transaction-payment/src/types.rs @@ -140,7 +140,8 @@ mod tests { partial_fee: 1_000_000_u64, }; - let json_str = r#"{"weight":{"ref_time":5,"proof_size":0},"class":"normal","partialFee":"1000000"}"#; + let json_str = + r#"{"weight":{"ref_time":5,"proof_size":0},"class":"normal","partialFee":"1000000"}"#; assert_eq!(serde_json::to_string(&info).unwrap(), json_str); assert_eq!(serde_json::from_str::>(json_str).unwrap(), info); @@ -157,7 +158,7 @@ mod tests { partial_fee: u128::max_value(), }; - let json_str = r#"{"weight":{"ref_time":5},"class":"normal","partialFee":"340282366920938463463374607431768211455"}"#; + let json_str = r#"{"weight":{"ref_time":5,"proof_size":0},"class":"normal","partialFee":"340282366920938463463374607431768211455"}"#; assert_eq!(serde_json::to_string(&info).unwrap(), json_str); assert_eq!(serde_json::from_str::>(json_str).unwrap(), info); From b1a9125181682b61416787fed236e620f9c1fb7d Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 28 Sep 2022 13:24:37 +0800 Subject: [PATCH 35/38] Use only reference time weight in grandpa test --- frame/grandpa/src/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frame/grandpa/src/tests.rs b/frame/grandpa/src/tests.rs index 775eda58c03e0..5d2ebdf29cb6b 100644 --- a/frame/grandpa/src/tests.rs +++ b/frame/grandpa/src/tests.rs @@ -856,7 +856,8 @@ fn valid_equivocation_reports_dont_pay_fees() { .get_dispatch_info(); // it should have non-zero weight and the fee has to be paid. - assert!(info.weight.all_gt(Weight::zero())); + // TODO: account for proof size weight + assert!(info.weight.ref_time() > 0); assert_eq!(info.pays_fee, Pays::Yes); // report the equivocation. From 3dec18b941715d79627ac2d24124c20aa901cbd1 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 28 Sep 2022 13:37:05 +0800 Subject: [PATCH 36/38] Use only reference time weight in examples test --- frame/examples/basic/src/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frame/examples/basic/src/tests.rs b/frame/examples/basic/src/tests.rs index db4787eaa0faa..cf9269617fac0 100644 --- a/frame/examples/basic/src/tests.rs +++ b/frame/examples/basic/src/tests.rs @@ -197,5 +197,6 @@ fn weights_work() { // should be less. let custom_call = pallet_example_basic::Call::::set_dummy { new_value: 20 }; let info2 = custom_call.get_dispatch_info(); - assert!(info1.weight.all_gt(info2.weight)); + // TODO: account for proof size weight + assert!(info1.weight.ref_time() > info2.weight.ref_time()); } From 85594283db66e5a41148f441fe5eb956db3a00d7 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 28 Sep 2022 13:38:09 +0800 Subject: [PATCH 37/38] Use only reference time weight in examples test --- frame/examples/basic/src/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frame/examples/basic/src/tests.rs b/frame/examples/basic/src/tests.rs index cf9269617fac0..97fbddfbc41e0 100644 --- a/frame/examples/basic/src/tests.rs +++ b/frame/examples/basic/src/tests.rs @@ -191,7 +191,8 @@ fn weights_work() { let default_call = pallet_example_basic::Call::::accumulate_dummy { increase_by: 10 }; let info1 = default_call.get_dispatch_info(); // aka. `let info = as GetDispatchInfo>::get_dispatch_info(&default_call);` - assert!(info1.weight.all_gt(Weight::zero())); + // TODO: account for proof size weight + assert!(info1.weight.ref_time() > 0); // `set_dummy` is simpler than `accumulate_dummy`, and the weight // should be less. From 4589902c5a9d41adfa5157fe6237c84facd175ab Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 28 Sep 2022 17:34:22 +0800 Subject: [PATCH 38/38] Fix test expectations --- .../storage_ensure_span_are_ok_on_wrong_gen.stderr | 6 +++--- .../storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr | 6 +++--- .../test/tests/pallet_ui/storage_info_unsatisfied.stderr | 2 +- .../tests/pallet_ui/storage_info_unsatisfied_nmap.stderr | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr b/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr index 5d159ec961c7f..b0716d569409c 100644 --- a/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr +++ b/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr @@ -28,7 +28,7 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied <&[(T,)] as EncodeLike>> <&[(T,)] as EncodeLike>> <&[T] as EncodeLike>> - and 278 others + and 279 others = note: required because of the requirements on the impl of `FullEncode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `PartialStorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` @@ -69,7 +69,7 @@ error[E0277]: the trait bound `Bar: TypeInfo` is not satisfied (A, B, C, D) (A, B, C, D, E) (A, B, C, D, E, F) - and 159 others + and 160 others = note: required because of the requirements on the impl of `StaticTypeInfo` for `Bar` = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` @@ -103,7 +103,7 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied <&[(T,)] as EncodeLike>> <&[(T,)] as EncodeLike>> <&[T] as EncodeLike>> - and 278 others + and 279 others = note: required because of the requirements on the impl of `FullEncode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` diff --git a/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr b/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr index 4671855431b27..926dc92530659 100644 --- a/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr +++ b/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr @@ -28,7 +28,7 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied <&[(T,)] as EncodeLike>> <&[(T,)] as EncodeLike>> <&[T] as EncodeLike>> - and 278 others + and 279 others = note: required because of the requirements on the impl of `FullEncode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `PartialStorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` @@ -69,7 +69,7 @@ error[E0277]: the trait bound `Bar: TypeInfo` is not satisfied (A, B, C, D) (A, B, C, D, E) (A, B, C, D, E, F) - and 159 others + and 160 others = note: required because of the requirements on the impl of `StaticTypeInfo` for `Bar` = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` @@ -103,7 +103,7 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied <&[(T,)] as EncodeLike>> <&[(T,)] as EncodeLike>> <&[T] as EncodeLike>> - and 278 others + and 279 others = note: required because of the requirements on the impl of `FullEncode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` diff --git a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr index d9cd20711403d..563190a06f76f 100644 --- a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr +++ b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr @@ -13,5 +13,5 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5) (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6) (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6, TupleElement7) - and 76 others + and 77 others = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` diff --git a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr index 9a4e8d740cb2c..c10005223b674 100644 --- a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr +++ b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr @@ -13,6 +13,6 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5) (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6) (TupleElement0, TupleElement1, TupleElement2, TupleElement3, TupleElement4, TupleElement5, TupleElement6, TupleElement7) - and 76 others + and 77 others = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `Key` = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, Key, u32>`