From d7d519202ba30582617f2069b7560378849fd963 Mon Sep 17 00:00:00 2001
From: zjb0807 <zjb0807@qq.com>
Date: Fri, 18 Sep 2020 11:58:48 +0800
Subject: [PATCH] Add weightInfo (#289)

* add weightInfo

* fix clippy
---
 authority/README.md                    | 11 +++++++++
 authority/src/default_weight.rs        | 27 ++++++++++++++++++++++
 authority/src/lib.rs                   | 23 ++++++++++++++-----
 authority/src/mock.rs                  |  1 +
 gradually-update/src/default_weight.rs | 31 ++++++++++++++++++++++++++
 gradually-update/src/lib.rs            | 31 ++++++++++++++++++--------
 gradually-update/src/mock.rs           |  1 +
 oracle/rpc/src/lib.rs                  | 10 +++++----
 oracle/src/default_weight.rs           | 15 +++++++++++++
 oracle/src/lib.rs                      | 16 +++++++++----
 oracle/src/mock.rs                     |  1 +
 rewards/README.md                      |  5 +++++
 rewards/src/default_weight.rs          |  9 ++++++++
 rewards/src/lib.rs                     | 11 +++++++--
 rewards/src/mock.rs                    |  1 +
 15 files changed, 169 insertions(+), 24 deletions(-)
 create mode 100644 authority/README.md
 create mode 100644 authority/src/default_weight.rs
 create mode 100644 gradually-update/src/default_weight.rs
 create mode 100644 oracle/src/default_weight.rs
 create mode 100644 rewards/README.md
 create mode 100644 rewards/src/default_weight.rs

diff --git a/authority/README.md b/authority/README.md
new file mode 100644
index 0000000..bc97f26
--- /dev/null
+++ b/authority/README.md
@@ -0,0 +1,11 @@
+# Authority module
+
+### Overview
+
+Authority module to provide features for governance including dispatch method on behalf other accounts and schdule dispatchables.
+
+- `dispatch_as` can dispatch a dispatchable on behalf of other origin.
+- `schedule_dispatch` can schdule a dispatchable to be dispatched at later block.
+- `fast_track_scheduled_dispatch` can fast track a scheduled dispatchable.
+- `delay_scheduled_dispatch` can delay a scheduled dispatchable.
+- `cancel_scheduled_dispatch` can cancel a scheduled dispatchable.
diff --git a/authority/src/default_weight.rs b/authority/src/default_weight.rs
new file mode 100644
index 0000000..e205b30
--- /dev/null
+++ b/authority/src/default_weight.rs
@@ -0,0 +1,27 @@
+//! Weights for the authority Module
+
+use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight};
+
+impl crate::WeightInfo for () {
+	fn dispatch_as() -> Weight {
+		50750000 as Weight
+	}
+	fn schedule_dispatch() -> Weight {
+		(147800000 as Weight)
+			.saturating_add(DbWeight::get().reads(3 as Weight))
+			.saturating_add(DbWeight::get().writes(3 as Weight))
+	}
+	fn fast_track_scheduled_dispatch() -> Weight {
+		// TODO
+		0 as Weight
+	}
+	fn delay_scheduled_dispatch() -> Weight {
+		// TODO
+		0 as Weight
+	}
+	fn cancel_scheduled_dispatch() -> Weight {
+		(127400000 as Weight)
+			.saturating_add(DbWeight::get().reads(2 as Weight))
+			.saturating_add(DbWeight::get().writes(2 as Weight))
+	}
+}
diff --git a/authority/src/lib.rs b/authority/src/lib.rs
index 3403fea..481e015 100644
--- a/authority/src/lib.rs
+++ b/authority/src/lib.rs
@@ -19,6 +19,7 @@
 #![allow(clippy::borrowed_box)]
 
 use codec::{Decode, Encode};
+use frame_support::weights::Weight;
 use frame_support::{
 	decl_error, decl_event, decl_module, decl_storage,
 	dispatch::PostDispatchInfo,
@@ -35,9 +36,18 @@ use sp_runtime::{
 };
 use sp_std::prelude::*;
 
+mod default_weight;
 mod mock;
 mod tests;
 
+pub trait WeightInfo {
+	fn dispatch_as() -> Weight;
+	fn schedule_dispatch() -> Weight;
+	fn fast_track_scheduled_dispatch() -> Weight;
+	fn delay_scheduled_dispatch() -> Weight;
+	fn cancel_scheduled_dispatch() -> Weight;
+}
+
 /// A delayed origin. Can only be dispatched via `dispatch_as` with a delay.
 #[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode)]
 pub struct DelayedOrigin<BlockNumber, PalletsOrigin> {
@@ -143,6 +153,9 @@ pub trait Trait: frame_system::Trait {
 
 	/// Additional permission config.
 	type AuthorityConfig: AuthorityConfig<<Self as frame_system::Trait>::Origin, Self::PalletsOrigin, Self::BlockNumber>;
+
+	/// Weight information for extrinsics in this module.
+	type WeightInfo: WeightInfo;
 }
 
 decl_error! {
@@ -188,7 +201,7 @@ decl_module! {
 		fn deposit_event() = default;
 
 		/// Dispatch a dispatchable on behalf of other origin
-		#[weight = (call.get_dispatch_info().weight + 10_000, call.get_dispatch_info().class)]
+		#[weight = (T::WeightInfo::dispatch_as().saturating_add(call.get_dispatch_info().weight), call.get_dispatch_info().class)]
 		pub fn dispatch_as(
 			origin,
 			as_origin: T::AsOriginId,
@@ -203,7 +216,7 @@ decl_module! {
 
 		/// Schdule a dispatchable to be dispatched at later block.
 		/// This is the only way to dispatch a call with `DelayedOrigin`.
-		#[weight = 10_000]
+		#[weight = T::WeightInfo::schedule_dispatch()]
 		pub fn schedule_dispatch(
 			origin,
 			when: DispatchTime<T::BlockNumber>,
@@ -252,7 +265,7 @@ decl_module! {
 		}
 
 		/// Fast track a scheduled dispatchable.
-		#[weight = 10_000]
+		#[weight = T::WeightInfo::fast_track_scheduled_dispatch()]
 		pub fn fast_track_scheduled_dispatch(
 			origin,
 			initial_origin: T::PalletsOrigin,
@@ -281,7 +294,7 @@ decl_module! {
 		}
 
 		/// Delay a scheduled dispatchable.
-		#[weight = 10_000]
+		#[weight = T::WeightInfo::delay_scheduled_dispatch()]
 		pub fn delay_scheduled_dispatch(
 			origin,
 			initial_origin: T::PalletsOrigin,
@@ -296,7 +309,7 @@ decl_module! {
 		}
 
 		/// Cancel a scheduled dispatchable.
-		#[weight = 10_000]
+		#[weight = T::WeightInfo::cancel_scheduled_dispatch()]
 		pub fn cancel_scheduled_dispatch(
 			origin,
 			initial_origin: T::PalletsOrigin,
diff --git a/authority/src/mock.rs b/authority/src/mock.rs
index 1c699f3..d058bc0 100644
--- a/authority/src/mock.rs
+++ b/authority/src/mock.rs
@@ -151,6 +151,7 @@ impl Trait for Runtime {
 	type Call = Call;
 	type AsOriginId = MockAsOriginId;
 	type AuthorityConfig = AuthorityConfigImpl;
+	type WeightInfo = ();
 }
 
 pub type Block = sp_runtime::generic::Block<Header, UncheckedExtrinsic>;
diff --git a/gradually-update/src/default_weight.rs b/gradually-update/src/default_weight.rs
new file mode 100644
index 0000000..03a956c
--- /dev/null
+++ b/gradually-update/src/default_weight.rs
@@ -0,0 +1,31 @@
+//! Weights for the Gradually-update Module
+
+use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight};
+
+impl crate::WeightInfo for () {
+	fn gradually_update() -> Weight {
+		(82320000 as Weight)
+			.saturating_add(DbWeight::get().reads(2 as Weight))
+			.saturating_add(DbWeight::get().writes(1 as Weight))
+	}
+	fn cancel_gradually_update() -> Weight {
+		(72950000 as Weight)
+			.saturating_add(DbWeight::get().reads(1 as Weight))
+			.saturating_add(DbWeight::get().writes(1 as Weight))
+	}
+	fn on_initialize(need_update: bool, update_len: usize) -> Weight {
+		if !need_update {
+			return 0;
+		}
+
+		if update_len == 0 {
+			(30430000 as Weight)
+				.saturating_add(DbWeight::get().reads(2 as Weight))
+				.saturating_add(DbWeight::get().writes(1 as Weight))
+		} else {
+			(91390000 + (30000000 * update_len) as Weight)
+				.saturating_add(DbWeight::get().reads(3 as Weight))
+				.saturating_add(DbWeight::get().writes(3 as Weight))
+		}
+	}
+}
diff --git a/gradually-update/src/lib.rs b/gradually-update/src/lib.rs
index 47c58e7..7c9a088 100644
--- a/gradually-update/src/lib.rs
+++ b/gradually-update/src/lib.rs
@@ -31,9 +31,16 @@ use frame_system::ensure_root;
 use sp_runtime::{traits::SaturatedConversion, DispatchResult, RuntimeDebug};
 use sp_std::prelude::Vec;
 
+mod default_weight;
 mod mock;
 mod tests;
 
+pub trait WeightInfo {
+	fn gradually_update() -> Weight;
+	fn cancel_gradually_update() -> Weight;
+	fn on_initialize(need_update: bool, update_len: usize) -> Weight;
+}
+
 type StorageKey = Vec<u8>;
 type StorageValue = Vec<u8>;
 
@@ -42,11 +49,11 @@ type StorageValue = Vec<u8>;
 #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)]
 pub struct GraduallyUpdate {
 	/// The storage key of the value to update
-	key: StorageKey,
+	pub key: StorageKey,
 	/// The target value
-	target_value: StorageValue,
+	pub target_value: StorageValue,
 	/// The amount of the value to update per one block
-	per_block: StorageValue,
+	pub per_block: StorageValue,
 }
 
 pub trait Trait: frame_system::Trait {
@@ -55,6 +62,8 @@ pub trait Trait: frame_system::Trait {
 	type UpdateFrequency: Get<Self::BlockNumber>;
 	/// The origin that can schedule an update
 	type DispatchOrigin: EnsureOrigin<Self::Origin>;
+	/// Weight information for extrinsics in this module.
+	type WeightInfo: WeightInfo;
 }
 
 decl_storage! {
@@ -103,7 +112,7 @@ decl_module! {
 		const UpdateFrequency: T::BlockNumber = T::UpdateFrequency::get();
 
 		/// Add gradually_update to adjust numeric parameter.
-		#[weight = 10_000]
+		#[weight = T::WeightInfo::gradually_update()]
 		pub fn gradually_update(origin, update: GraduallyUpdate) {
 			T::DispatchOrigin::try_origin(origin).map(|_| ()).or_else(ensure_root)?;
 
@@ -127,7 +136,7 @@ decl_module! {
 		}
 
 		/// Cancel gradually_update to adjust numeric parameter.
-		#[weight = 10_000]
+		#[weight = T::WeightInfo::cancel_gradually_update()]
 		pub fn cancel_gradually_update(origin, key: StorageKey) {
 			T::DispatchOrigin::try_origin(origin).map(|_| ()).or_else(ensure_root)?;
 
@@ -143,10 +152,10 @@ decl_module! {
 			Self::deposit_event(RawEvent::GraduallyUpdateCancelled(key));
 		}
 
-		/// dummy `on_initialize` to return the weight used in `on_finalize`.
+		/// `on_initialize` to return the weight used in `on_finalize`.
 		fn on_initialize() -> Weight {
-			// weight of `on_finalize`
-			0
+			let now = <frame_system::Module<T>>::block_number();
+			T::WeightInfo::on_initialize(Self::_need_update(now), GraduallyUpdates::get().len())
 		}
 
 		/// Update gradually_update to adjust numeric parameter.
@@ -157,8 +166,12 @@ decl_module! {
 }
 
 impl<T: Trait> Module<T> {
+	fn _need_update(now: T::BlockNumber) -> bool {
+		now >= Self::last_updated_at() + T::UpdateFrequency::get()
+	}
+
 	fn _on_finalize(now: T::BlockNumber) {
-		if now < Self::last_updated_at() + T::UpdateFrequency::get() {
+		if !Self::_need_update(now) {
 			return;
 		}
 
diff --git a/gradually-update/src/mock.rs b/gradually-update/src/mock.rs
index 25a64a3..33a4651 100644
--- a/gradually-update/src/mock.rs
+++ b/gradually-update/src/mock.rs
@@ -74,6 +74,7 @@ impl Trait for Runtime {
 	type Event = TestEvent;
 	type UpdateFrequency = UpdateFrequency;
 	type DispatchOrigin = system::EnsureRoot<AccountId>;
+	type WeightInfo = ();
 }
 pub type GraduallyUpdateModule = Module<Runtime>;
 
diff --git a/oracle/rpc/src/lib.rs b/oracle/rpc/src/lib.rs
index 9844fc1..6d86b8b 100644
--- a/oracle/rpc/src/lib.rs
+++ b/oracle/rpc/src/lib.rs
@@ -62,9 +62,10 @@ where
 		at: Option<<Block as BlockT>::Hash>,
 	) -> Result<Option<Value>> {
 		let api = self.client.runtime_api();
-		let at = BlockId::hash(at.unwrap_or_else(||
+		let at = BlockId::hash(at.unwrap_or(
 			// If the block hash is not supplied assume the best block.
-			self.client.info().best_hash));
+			self.client.info().best_hash,
+		));
 		api.get_value(&at, provider_id, key).map_err(|e| RpcError {
 			code: ErrorCode::ServerError(Error::RuntimeError.into()),
 			message: "Unable to get value.".into(),
@@ -78,9 +79,10 @@ where
 		at: Option<<Block as BlockT>::Hash>,
 	) -> Result<Vec<(Key, Option<Value>)>> {
 		let api = self.client.runtime_api();
-		let at = BlockId::hash(at.unwrap_or_else(||
+		let at = BlockId::hash(at.unwrap_or(
 			// If the block hash is not supplied assume the best block.
-			self.client.info().best_hash));
+			self.client.info().best_hash,
+		));
 		api.get_all_values(&at, provider_id).map_err(|e| RpcError {
 			code: ErrorCode::ServerError(Error::RuntimeError.into()),
 			message: "Unable to get all values.".into(),
diff --git a/oracle/src/default_weight.rs b/oracle/src/default_weight.rs
new file mode 100644
index 0000000..a020f46
--- /dev/null
+++ b/oracle/src/default_weight.rs
@@ -0,0 +1,15 @@
+//! Weights for the Auction Module
+
+use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight};
+
+impl crate::WeightInfo for () {
+	fn feed_values(values_len: usize) -> Weight {
+		(101600000 as Weight)
+			.saturating_add(DbWeight::get().reads(3 as Weight))
+			.saturating_add(DbWeight::get().writes((1 + values_len * 2) as Weight))
+	}
+
+	fn on_initialize() -> Weight {
+		(18400000 as Weight).saturating_add(DbWeight::get().writes(1) as Weight)
+	}
+}
diff --git a/oracle/src/lib.rs b/oracle/src/lib.rs
index 85e40ca..017c898 100644
--- a/oracle/src/lib.rs
+++ b/oracle/src/lib.rs
@@ -20,9 +20,15 @@
 #![allow(clippy::string_lit_as_bytes)]
 
 mod default_combine_data;
+mod default_weight;
 mod mock;
 mod tests;
 
+pub trait WeightInfo {
+	fn feed_values(n: usize) -> Weight;
+	fn on_initialize() -> Weight;
+}
+
 use codec::{Decode, Encode};
 pub use default_combine_data::DefaultCombineData;
 use frame_support::{
@@ -72,6 +78,9 @@ pub trait Trait<I: Instance = DefaultInstance>: frame_system::Trait {
 
 	/// The root operator account id, recorad all sudo feeds on this account.
 	type RootOperatorAccountId: Get<Self::AccountId>;
+
+	/// Weight information for extrinsics in this module.
+	type WeightInfo: WeightInfo;
 }
 
 decl_error! {
@@ -130,7 +139,7 @@ decl_module! {
 		/// Feed the external value.
 		///
 		/// Require unsigned. However a valid signature signed by session key is required along with payload.
-		#[weight = (10_000, DispatchClass::Operational)]
+		#[weight = (T::WeightInfo::feed_values(values.len()), DispatchClass::Operational)]
 		pub fn feed_values(
 			origin,
 			values: Vec<(T::OracleKey, T::OracleValue)>,
@@ -140,10 +149,9 @@ decl_module! {
 			Ok(Pays::No.into())
 		}
 
-		/// dummy `on_initialize` to return the weight used in `on_finalize`.
+		/// `on_initialize` to return the weight used in `on_finalize`.
 		fn on_initialize() -> Weight {
-			// weight of `on_finalize`
-			0
+			T::WeightInfo::on_initialize()
 		}
 
 		fn on_finalize(_n: T::BlockNumber) {
diff --git a/oracle/src/mock.rs b/oracle/src/mock.rs
index 09d5026..8ee9548 100644
--- a/oracle/src/mock.rs
+++ b/oracle/src/mock.rs
@@ -110,6 +110,7 @@ impl Trait for Test {
 	type OracleKey = Key;
 	type OracleValue = Value;
 	type RootOperatorAccountId = RootOperatorAccountId;
+	type WeightInfo = ();
 }
 
 pub type ModuleOracle = Module<Test>;
diff --git a/rewards/README.md b/rewards/README.md
new file mode 100644
index 0000000..d797892
--- /dev/null
+++ b/rewards/README.md
@@ -0,0 +1,5 @@
+# Rewards module
+
+### Overview
+
+This module exposes capabilities for staking rewards.
diff --git a/rewards/src/default_weight.rs b/rewards/src/default_weight.rs
new file mode 100644
index 0000000..625e234
--- /dev/null
+++ b/rewards/src/default_weight.rs
@@ -0,0 +1,9 @@
+//! Weights for the Rewards Module
+
+use frame_support::weights::{constants::RocksDbWeight as DbWeight, Weight};
+
+impl crate::WeightInfo for () {
+	fn on_initialize() -> Weight {
+		(20100000 as Weight).saturating_add(DbWeight::get().reads(1 as Weight))
+	}
+}
diff --git a/rewards/src/lib.rs b/rewards/src/lib.rs
index b2362c3..d4e09e2 100644
--- a/rewards/src/lib.rs
+++ b/rewards/src/lib.rs
@@ -12,9 +12,14 @@ use sp_std::{
 	fmt::Debug,
 };
 
+mod default_weight;
 mod mock;
 mod tests;
 
+pub trait WeightInfo {
+	fn on_initialize() -> Weight;
+}
+
 /// The Reward Pool Info.
 #[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug, Default)]
 pub struct PoolInfo<Share: HasCompact, Balance: HasCompact> {
@@ -61,6 +66,9 @@ pub trait Trait: frame_system::Trait {
 		Balance = Self::Balance,
 		PoolId = Self::PoolId,
 	>;
+
+	/// Weight information for extrinsics in this module.
+	type WeightInfo: WeightInfo;
 }
 
 decl_storage! {
@@ -82,8 +90,7 @@ decl_module! {
 					Pools::<T>::mutate(pool, | pool_info | pool_info.total_rewards = pool_info.total_rewards.saturating_add(reward_to_accumulate));
 				}
 			});
-
-			0
+			T::WeightInfo::on_initialize()
 		}
 	}
 }
diff --git a/rewards/src/mock.rs b/rewards/src/mock.rs
index 4954254..c71a22d 100644
--- a/rewards/src/mock.rs
+++ b/rewards/src/mock.rs
@@ -118,6 +118,7 @@ impl Trait for Runtime {
 	type Balance = Balance;
 	type PoolId = PoolId;
 	type Handler = Handler;
+	type WeightInfo = ();
 }
 pub type RewardsModule = Module<Runtime>;
 
-- 
GitLab