From 9a3798d00819886544474c6764f4f3fa1ebe653a Mon Sep 17 00:00:00 2001 From: vgantchev Date: Tue, 3 Dec 2024 12:31:45 +0100 Subject: [PATCH 01/17] dispatcher pallet base with mock weights --- Cargo.lock | 15 +++ Cargo.toml | 1 + pallets/dispatcher/Cargo.toml | 45 +++++++ pallets/dispatcher/README.md | 6 + pallets/dispatcher/src/lib.rs | 111 ++++++++++++++++++ pallets/dispatcher/src/weights.rs | 77 ++++++++++++ runtime/hydradx/Cargo.toml | 3 + runtime/hydradx/src/governance/mod.rs | 8 ++ runtime/hydradx/src/lib.rs | 2 + runtime/hydradx/src/weights/mod.rs | 1 + .../hydradx/src/weights/pallet_dispatcher.rs | 70 +++++++++++ 11 files changed, 339 insertions(+) create mode 100644 pallets/dispatcher/Cargo.toml create mode 100644 pallets/dispatcher/README.md create mode 100644 pallets/dispatcher/src/lib.rs create mode 100644 pallets/dispatcher/src/weights.rs create mode 100644 runtime/hydradx/src/weights/pallet_dispatcher.rs diff --git a/Cargo.lock b/Cargo.lock index 2c2f04cf3..976bfcfdd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4989,6 +4989,7 @@ dependencies = [ "pallet-currencies-rpc-runtime-api", "pallet-dca", "pallet-democracy 4.3.2", + "pallet-dispatcher", "pallet-duster", "pallet-dynamic-evm-fee", "pallet-dynamic-fees", @@ -8081,6 +8082,20 @@ dependencies = [ "sp-std", ] +[[package]] +name = "pallet-dispatcher" +version = "1.0.0" +dependencies = [ + "frame-benchmarking", + "frame-support", + "frame-system", + "parity-scale-codec", + "scale-info", + "sp-core", + "sp-runtime", + "sp-std", +] + [[package]] name = "pallet-duster" version = "3.2.7" diff --git a/Cargo.toml b/Cargo.toml index bc66434fe..7d61af539 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -117,6 +117,7 @@ pallet-collator-rewards = { path = "pallets/collator-rewards", default-features pallet-currencies = { path = "pallets/currencies", default-features = false } pallet-currencies-rpc-runtime-api = { path = "pallets/currencies/rpc/runtime-api", default-features = false } pallet-dca = { path = "pallets/dca", default-features = false } +pallet-dispatcher = { path = "pallets/dispatcher", default-features = false } pallet-duster = { path = "pallets/duster", default-features = false } pallet-dynamic-fees = { path = "pallets/dynamic-fees", default-features = false } pallet-dynamic-evm-fee = { path = "pallets/dynamic-evm-fee", default-features = false } diff --git a/pallets/dispatcher/Cargo.toml b/pallets/dispatcher/Cargo.toml new file mode 100644 index 000000000..21bd96dfb --- /dev/null +++ b/pallets/dispatcher/Cargo.toml @@ -0,0 +1,45 @@ +[package] +name = "pallet-dispatcher" +version = "1.0.0" +authors = ['GalacticCouncil'] +edition = "2021" +license = "Apache-2.0" +homepage = 'https://github.com/galacticcouncil/hydration-node' +repository = 'https://github.com/galacticcouncil/hydration-node' +description = "Pallet for dispatching calls as specific origins" +readme = "README.md" + +[dependencies] +# parity +codec = { workspace = true, features = ["derive", "max-encoded-len"] } +scale-info = { workspace = true } + +# primitives +sp-runtime = { workspace = true } +sp-std = { workspace = true } +sp-core = { workspace = true } + +# FRAME +frame-support = { workspace = true } +frame-system = { workspace = true } + +# Optional imports for benchmarking +frame-benchmarking = { workspace = true, optional = true } + +[features] +default = ['std'] +std = [ + 'codec/std', + 'scale-info/std', + 'sp-runtime/std', + 'sp-core/std', + 'sp-std/std', + 'frame-benchmarking/std' +] + +runtime-benchmarks = [ + "frame-benchmarking", + "frame-system/runtime-benchmarks", + "frame-support/runtime-benchmarks", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/dispatcher/README.md b/pallets/dispatcher/README.md new file mode 100644 index 000000000..41ba5dee9 --- /dev/null +++ b/pallets/dispatcher/README.md @@ -0,0 +1,6 @@ +# Dispatcher Pallet +This pallet enables specific OpenGov tracks to dispatch Runtime calls as predefined origins. + +The pallet supports the following dispatchables: +* `dispatch_as_treasury_manager` - allows the `TreasuryManager` track to dispatch calls as the Treasury account on Hydration (`7L53bUTBopuwFt3mKUfmkzgGLayYa1Yvn1hAg9v5UMrQzTfh`) +* `dispatch_as_aave_manager` - allows the `AaveManager` track to dispatch calls as the Money Market authority on Hydration (`add addr`) diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs new file mode 100644 index 000000000..01a2513fe --- /dev/null +++ b/pallets/dispatcher/src/lib.rs @@ -0,0 +1,111 @@ +// This file is part of https://github.com/galacticcouncil/* +// +// $$$$$$$ Licensed under the Apache License, Version 2.0 (the "License") +// $$$$$$$$$$$$$ you may only use this file in compliance with the License +// $$$$$$$$$$$$$$$$$$$ +// $$$$$$$$$ Copyright (C) 2021-2024 Intergalactic, Limited (GIB) +// $$$$$$$$$$$ $$$$$$$$$$ SPDX-License-Identifier: Apache-2.0 +// $$$$$$$$$$$$$$$$$$$$$$$$$$ +// $$$$$$$$$$$$$$$$$$$$$$$ $ Built with <3 for decentralisation +// $$$$$$$$$$$$$$$$$$$ $$$$$$$ +// $$$$$$$ $$$$$$$$$$$$$$$$$$ Unless required by applicable law or agreed to in +// $ $$$$$$$$$$$$$$$$$$$$$$$ writing, software distributed under the License is +// $$$$$$$$$$$$$$$$$$$$$$$$$$ distributed on an "AS IS" BASIS, WITHOUT WARRANTIES +// $$$$$$$$$ $$$$$$$$$$$ OR CONDITIONS OF ANY KIND, either express or implied. +// $$$$$$$$ +// $$$$$$$$$$$$$$$$$$ See the License for the specific language governing +// $$$$$$$$$$$$$ permissions and limitations under the License. +// $$$$$$$ +// $$ +// $$$$$ $$$$$ $$ $ +// $$$ $$$ $$$ $$ $$$$$ $$ $$$ $$$$ $$$$$$$ $$$$ $$$ $$$$$$ $$ $$$$$$ +// $$$ $$$ $$$ $$ $$$ $$$ $$$ $ $$ $$ $$ $$ $$ $$ $$$ $$$ +// $$$$$$$$$$$ $$ $$ $$$ $$ $$ $$$$$$$ $$ $$ $$ $$$ $$ $$ +// $$$ $$$ $$$$ $$$ $$ $$ $$$ $$ $$ $$ $$ $$ $$ $$ +// $$$$$ $$$$$ $$ $$$$$$$$ $ $$$ $$$$$$$$ $$$ $$$$ $$$$$$$ $$$$ $$$$ +// $$$ + +// #[cfg(any(feature = "runtime-benchmarks", test))] +// mod benchmarks; + +pub mod weights; +pub use weights::WeightInfo; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use codec::FullCodec; + use frame_support::{dispatch::{GetDispatchInfo, PostDispatchInfo}, pallet_prelude::*}; + use frame_system::{pallet_prelude::OriginFor}; + use sp_runtime::traits::Dispatchable; + + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// The overarching call type. + type RuntimeCall: IsType<::RuntimeCall> + + Dispatchable + + GetDispatchInfo + + FullCodec + + TypeInfo + + From> + + Parameter; + + type TreasuryManagerOrigin: EnsureOrigin; + type AaveManagerOrigin: EnsureOrigin; + + /// The weight information for this pallet. + type WeightInfo: WeightInfo; + } + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + TreasuryManagerCallDispatched { call_hash: T::Hash, result: DispatchResultWithPostInfo }, + AaveManagerCallDispatched { call_hash: T::Hash, result: DispatchResultWithPostInfo }, + } + + #[pallet::error] + pub enum Error { + /// The preimage of the call hash could not be loaded. + UnavailablePreImage, + } + + #[pallet::call] + impl Pallet { + #[pallet::call_index(0)] + #[pallet::weight(::WeightInfo::dispatch_as_treasury_manager())] + pub fn dispatch_as_treasury_manager(origin: OriginFor, call: Box<::RuntimeCall>,) -> DispatchResult { + T::TreasuryManagerOrigin::ensure_origin(origin)?; + + Ok(()) + } + } +} + +// impl Pallet { +// /// Clean whitelisting/preimage and dispatch call. +// /// +// /// Return the call actual weight of the dispatched call if there is some. +// fn do_dispatch(origin: T::Hash, call: ::RuntimeCall) -> Option { +// WhitelistedCall::::remove(call_hash); +// +// T::Preimages::unrequest(&call_hash); +// +// let result = call.dispatch(frame_system::Origin::::Root.into()); +// +// let call_actual_weight = match result { +// Ok(call_post_info) => call_post_info.actual_weight, +// Err(call_err) => call_err.post_info.actual_weight, +// }; +// +// Self::deposit_event(Event::::WhitelistedCallDispatched { call_hash, result }); +// +// call_actual_weight +// } +// } diff --git a/pallets/dispatcher/src/weights.rs b/pallets/dispatcher/src/weights.rs new file mode 100644 index 000000000..b3e34338b --- /dev/null +++ b/pallets/dispatcher/src/weights.rs @@ -0,0 +1,77 @@ +// This file is part of HydraDX. + +// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +//! Autogenerated weights for `pallet_otc` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-09-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` + +// Executed Command: +// target/release/hydradx +// benchmark +// pallet +// --chain=dev +// --steps=50 +// --repeat=20 +// --wasm-execution=compiled +// --pallet=pallet-otc +// --extrinsic=* +// --template=scripts/pallet-weight-template.hbs +// --output=./weights/pallet_otc.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{ + traits::Get, + weights::{constants::RocksDbWeight, Weight}, +}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for pallet_otc. +pub trait WeightInfo { + fn dispatch_as_treasury_manager() -> Weight; +} + +/// Weights for pallet_otc using the hydraDX node and recommended hardware. +impl WeightInfo for () { + /// Storage: `AssetRegistry::Assets` (r:2 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `OTC::NextOrderId` (r:1 w:1) + /// Proof: `OTC::NextOrderId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Reserves` (r:1 w:1) + /// Proof: `Tokens::Reserves` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:1 w:1) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `OTC::Orders` (r:0 w:1) + /// Proof: `OTC::Orders` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) + fn dispatch_as_treasury_manager() -> Weight { + // Proof Size summary in bytes: + // Measured: `963` + // Estimated: `6190` + // Minimum execution time: 46_446_000 picoseconds. + Weight::from_parts(47_816_000, 6190) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(4_u64)) + } +} diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index d247f83ed..218d70b8f 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -46,6 +46,7 @@ pallet-xyk-liquidity-mining = { workspace = true } pallet-bags-list = { workspace = true } pallet-balances = { workspace = true } pallet-conviction-voting = { workspace = true } +pallet-dispatcher = { workspace = true } pallet-transaction-payment = { workspace = true } pallet-transaction-payment-rpc-runtime-api = { workspace = true } pallet-treasury = { workspace = true } @@ -340,6 +341,7 @@ std = [ "pallet-conviction-voting/std", "pallet-referenda/std", "pallet-whitelist/std", + "pallet-dispatcher/std", ] try-runtime = [ "frame-try-runtime", @@ -414,6 +416,7 @@ try-runtime = [ "pallet-conviction-voting/try-runtime", "pallet-referenda/try-runtime", "pallet-whitelist/try-runtime", + "pallet-dispatcher/try-runtime", ] metadata-hash = [ diff --git a/runtime/hydradx/src/governance/mod.rs b/runtime/hydradx/src/governance/mod.rs index 1b0f2cca0..81b9094a2 100644 --- a/runtime/hydradx/src/governance/mod.rs +++ b/runtime/hydradx/src/governance/mod.rs @@ -229,3 +229,11 @@ impl pallet_referenda::Config for Runtime { } impl origins::pallet_custom_origins::Config for Runtime {} + +impl pallet_dispatcher::Config for Runtime { + type WeightInfo = weights::pallet_dispatcher::HydraWeight; + type RuntimeCall = RuntimeCall; + type TreasuryManagerOrigin = EitherOf, Treasurer>; + type AaveManagerOrigin = EitherOf, Treasurer>; + /// TreasuryPalletId::get().into_account_truncating(), +} diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index f1474c31e..25a892af7 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -167,6 +167,7 @@ construct_runtime!( Referenda: pallet_referenda = 37, Origins: pallet_custom_origins = 38, Whitelist: pallet_whitelist = 39, + Dispatcher: pallet_dispatcher = 40, // HydraDX related modules AssetRegistry: pallet_asset_registry = 51, @@ -325,6 +326,7 @@ mod benches { [pallet_conviction_voting, ConvictionVoting] [pallet_referenda, Referenda] [pallet_whitelist, Whitelist] + [pallet_dispatcher, Dispatcher] ); } diff --git a/runtime/hydradx/src/weights/mod.rs b/runtime/hydradx/src/weights/mod.rs index c15fda1c3..fe744ec7f 100644 --- a/runtime/hydradx/src/weights/mod.rs +++ b/runtime/hydradx/src/weights/mod.rs @@ -16,6 +16,7 @@ pub mod pallet_currencies; pub mod pallet_dca; pub mod pallet_democracy; pub mod pallet_duster; +pub mod pallet_dispatcher; pub mod pallet_dynamic_evm_fee; pub mod pallet_elections_phragmen; pub mod pallet_ema_oracle; diff --git a/runtime/hydradx/src/weights/pallet_dispatcher.rs b/runtime/hydradx/src/weights/pallet_dispatcher.rs new file mode 100644 index 000000000..c367072fe --- /dev/null +++ b/runtime/hydradx/src/weights/pallet_dispatcher.rs @@ -0,0 +1,70 @@ +// This file is part of HydraDX. + +// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +//! Autogenerated weights for `pallet_whitelist` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-07-30, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` + +// Executed Command: +// target/release/hydradx +// benchmark +// pallet +// --chain=dev +// --steps=10 +// --repeat=30 +// --wasm-execution=compiled +// --heap-pages=4096 +// --template=scripts/pallet-weight-template.hbs +// --pallet=pallet-whitelist +// --output=pallet_whitelist.rs +// --extrinsic=* + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; + +/// Weights for `pallet_whitelist`. +pub struct WeightInfo(PhantomData); + +/// Weights for `pallet_whitelist` using the HydraDX node and recommended hardware. +pub struct HydraWeight(PhantomData); +impl pallet_dispatcher::WeightInfo for HydraWeight { + /// Storage: `Whitelist::WhitelistedCall` (r:1 w:1) + /// Proof: `Whitelist::WhitelistedCall` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) + /// Storage: `Preimage::StatusFor` (r:1 w:0) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// Storage: `Preimage::RequestStatusFor` (r:1 w:1) + /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + fn dispatch_as_treasury_manager() -> Weight { + // Proof Size summary in bytes: + // Measured: `218` + // Estimated: `3556` + // Minimum execution time: 23_242_000 picoseconds. + Weight::from_parts(23_861_000, 3556) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } +} From 971c454da9fbc737b7f2555b75ce9adddc2c840e Mon Sep 17 00:00:00 2001 From: vgantchev Date: Tue, 3 Dec 2024 14:04:08 +0100 Subject: [PATCH 02/17] heal std --- pallets/dispatcher/src/lib.rs | 8 +++++++- runtime/hydradx/src/governance/mod.rs | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs index 01a2513fe..05cd8d63e 100644 --- a/pallets/dispatcher/src/lib.rs +++ b/pallets/dispatcher/src/lib.rs @@ -25,19 +25,25 @@ // $$$$$ $$$$$ $$ $$$$$$$$ $ $$$ $$$$$$$$ $$$ $$$$ $$$$$$$ $$$$ $$$$ // $$$ +#![cfg_attr(not(feature = "std"), no_std)] + // #[cfg(any(feature = "runtime-benchmarks", test))] // mod benchmarks; pub mod weights; pub use weights::WeightInfo; +// Re-export pallet items so that they can be accessed from the crate namespace. +pub use pallet::*; + #[frame_support::pallet] pub mod pallet { use super::*; use codec::FullCodec; use frame_support::{dispatch::{GetDispatchInfo, PostDispatchInfo}, pallet_prelude::*}; - use frame_system::{pallet_prelude::OriginFor}; + use frame_system::{pallet_prelude::*}; use sp_runtime::traits::Dispatchable; + use sp_std::boxed::Box; #[pallet::config] pub trait Config: frame_system::Config { diff --git a/runtime/hydradx/src/governance/mod.rs b/runtime/hydradx/src/governance/mod.rs index 81b9094a2..54038489a 100644 --- a/runtime/hydradx/src/governance/mod.rs +++ b/runtime/hydradx/src/governance/mod.rs @@ -233,7 +233,7 @@ impl origins::pallet_custom_origins::Config for Runtime {} impl pallet_dispatcher::Config for Runtime { type WeightInfo = weights::pallet_dispatcher::HydraWeight; type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; type TreasuryManagerOrigin = EitherOf, Treasurer>; type AaveManagerOrigin = EitherOf, Treasurer>; - /// TreasuryPalletId::get().into_account_truncating(), } From d4175c7d2ead4eebdf2d1778d600dbabe72a83d4 Mon Sep 17 00:00:00 2001 From: vgantchev Date: Mon, 9 Dec 2024 14:48:17 +0100 Subject: [PATCH 03/17] add possibility to dispatch call (without preimage) --- Cargo.lock | 5 + pallets/dispatcher/Cargo.toml | 13 +- pallets/dispatcher/src/lib.rs | 66 ++++--- pallets/dispatcher/src/mock.rs | 321 ++++++++++++++++++++++++++++++++ pallets/dispatcher/src/tests.rs | 50 +++++ 5 files changed, 430 insertions(+), 25 deletions(-) create mode 100644 pallets/dispatcher/src/mock.rs create mode 100644 pallets/dispatcher/src/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 976bfcfdd..fc00e9899 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8089,11 +8089,16 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "hydradx-traits", + "orml-tokens", + "orml-traits", "parity-scale-codec", "scale-info", "sp-core", + "sp-io", "sp-runtime", "sp-std", + "test-utils", ] [[package]] diff --git a/pallets/dispatcher/Cargo.toml b/pallets/dispatcher/Cargo.toml index 21bd96dfb..8b429912c 100644 --- a/pallets/dispatcher/Cargo.toml +++ b/pallets/dispatcher/Cargo.toml @@ -26,6 +26,13 @@ frame-system = { workspace = true } # Optional imports for benchmarking frame-benchmarking = { workspace = true, optional = true } +[dev-dependencies] +sp-io = { workspace = true } +hydradx-traits = { workspace = true } +orml-tokens = { workspace = true } +orml-traits = { workspace = true } +test-utils = { workspace = true } + [features] default = ['std'] std = [ @@ -33,8 +40,12 @@ std = [ 'scale-info/std', 'sp-runtime/std', 'sp-core/std', + 'sp-io/std', 'sp-std/std', - 'frame-benchmarking/std' + 'frame-benchmarking/std', + 'hydradx-traits/std', + 'orml-tokens/std', + 'orml-traits/std', ] runtime-benchmarks = [ diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs index 05cd8d63e..686fb42c6 100644 --- a/pallets/dispatcher/src/lib.rs +++ b/pallets/dispatcher/src/lib.rs @@ -27,14 +27,22 @@ #![cfg_attr(not(feature = "std"), no_std)] +#[cfg(test)] +mod tests; +#[cfg(test)] +pub mod mock; + // #[cfg(any(feature = "runtime-benchmarks", test))] // mod benchmarks; pub mod weights; + +use sp_runtime::traits::Dispatchable; pub use weights::WeightInfo; // Re-export pallet items so that they can be accessed from the crate namespace. pub use pallet::*; +use frame_support::pallet_prelude::Weight; #[frame_support::pallet] pub mod pallet { @@ -42,9 +50,12 @@ pub mod pallet { use codec::FullCodec; use frame_support::{dispatch::{GetDispatchInfo, PostDispatchInfo}, pallet_prelude::*}; use frame_system::{pallet_prelude::*}; - use sp_runtime::traits::Dispatchable; + use sp_runtime::traits::{Dispatchable, Hash}; use sp_std::boxed::Box; + + pub type AccountId = u64; + #[pallet::config] pub trait Config: frame_system::Config { /// The overarching event type. @@ -62,6 +73,8 @@ pub mod pallet { type TreasuryManagerOrigin: EnsureOrigin; type AaveManagerOrigin: EnsureOrigin; + type TreasuryAccount: Get; + /// The weight information for this pallet. type WeightInfo: WeightInfo; } @@ -86,32 +99,37 @@ pub mod pallet { impl Pallet { #[pallet::call_index(0)] #[pallet::weight(::WeightInfo::dispatch_as_treasury_manager())] - pub fn dispatch_as_treasury_manager(origin: OriginFor, call: Box<::RuntimeCall>,) -> DispatchResult { + pub fn dispatch_as_treasury_manager(origin: OriginFor, call: Box<::RuntimeCall>,) -> DispatchResultWithPostInfo { T::TreasuryManagerOrigin::ensure_origin(origin)?; - Ok(()) + let call_hash = T::Hashing::hash_of(&call).into(); + let call_len = call.encoded_size() as u32; + + /// TODO: Add call len to weight + let actual_weight = Self::do_dispatch(T::TreasuryAccount::get(), call_hash, *call).map(|w| { + w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager()) + }); + + Ok(actual_weight.into()) + } } } } -// impl Pallet { -// /// Clean whitelisting/preimage and dispatch call. -// /// -// /// Return the call actual weight of the dispatched call if there is some. -// fn do_dispatch(origin: T::Hash, call: ::RuntimeCall) -> Option { -// WhitelistedCall::::remove(call_hash); -// -// T::Preimages::unrequest(&call_hash); -// -// let result = call.dispatch(frame_system::Origin::::Root.into()); -// -// let call_actual_weight = match result { -// Ok(call_post_info) => call_post_info.actual_weight, -// Err(call_err) => call_err.post_info.actual_weight, -// }; -// -// Self::deposit_event(Event::::WhitelistedCallDispatched { call_hash, result }); -// -// call_actual_weight -// } -// } +impl Pallet { + /// Clean whitelisting/preimage and dispatch call. + /// + /// Return the call actual weight of the dispatched call if there is some. + fn do_dispatch(account: T::AccountId, call_hash: T::Hash, call: ::RuntimeCall) -> Option { + let result = call.dispatch(frame_system::Origin::::Signed(account).into()); + + let call_actual_weight = match result { + Ok(call_post_info) => call_post_info.actual_weight.clone(), + Err(call_err) => call_err.post_info.actual_weight, + }; + + Self::deposit_event(Event::::TreasuryManagerCallDispatched { call_hash, result }); + + call_actual_weight + } +} diff --git a/pallets/dispatcher/src/mock.rs b/pallets/dispatcher/src/mock.rs new file mode 100644 index 000000000..9f8bc4458 --- /dev/null +++ b/pallets/dispatcher/src/mock.rs @@ -0,0 +1,321 @@ +// This file is part of galacticcouncil/warehouse. +// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate as dispatcher; +use crate::Config; +use frame_support::{ + parameter_types, + traits::{Everything, Nothing}, + PalletId, +}; +use frame_system as system; +use hydradx_traits::{registry::Inspect, AssetKind}; +use orml_tokens::AccountData; +use orml_traits::parameter_type_with_key; +use sp_core::H256; +use sp_runtime::{ + traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, + BuildStorage, Permill, +}; +use std::{cell::RefCell, collections::HashMap}; +use frame_support::traits::EitherOf; +use frame_system::EnsureRoot; + +type Block = frame_system::mocking::MockBlock; + +pub type AccountId = u64; +pub type Amount = i128; +pub type AssetId = u32; +pub type Balance = u128; +pub type NamedReserveIdentifier = [u8; 8]; + +pub const HDX: AssetId = 0; +pub const DAI: AssetId = 2; +pub const DOGE: AssetId = 333; +pub const REGISTERED_ASSET: AssetId = 1000; + +pub const ONE: Balance = 1_000_000_000_000; + +pub const ALICE: AccountId = 1; +pub const BOB: AccountId = 2; + +pub const TREASURY_INITIAL_BALANCE: Balance = 1_000_000 * ONE; + +frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Dispatcher: dispatcher, + Tokens: orml_tokens, + } +); + +thread_local! { + pub static REGISTERED_ASSETS: RefCell> = RefCell::new(HashMap::default()); + pub static EXISTENTIAL_DEPOSIT: RefCell>= RefCell::new(HashMap::default()); + pub static PRECISIONS: RefCell>= RefCell::new(HashMap::default()); +} + +parameter_types! { + pub NativeCurrencyId: AssetId = HDX; + pub ExistentialDepositMultiplier: u8 = 5; + pub OtcFee: Permill = Permill::from_percent(1u32); + pub const TreasuryPalletId: PalletId = PalletId(*b"aca/trsy"); + pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating(); +} + +parameter_type_with_key! { + pub ExistentialDeposits: |currency_id: AssetId| -> Balance { + EXISTENTIAL_DEPOSIT.with(|v| *v.borrow().get(currency_id).unwrap_or(&(ONE / 10))) + }; +} + +impl dispatcher::Config for Test { + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type TreasuryManagerOrigin = EnsureRoot; + type AaveManagerOrigin = EnsureRoot; + type TreasuryAccount = TreasuryAccount; + type WeightInfo = (); + +} + +parameter_types! { + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 63; + pub const MaxReserves: u32 = 50; +} + +impl system::Config for Test { + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeTask = RuntimeTask; + type Nonce = u64; + type Block = Block; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; + type SingleBlockMigrations = (); + type MultiBlockMigrator = (); + type PreInherents = (); + type PostInherents = (); + type PostTransactions = (); +} + +impl orml_tokens::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = AssetId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type MaxLocks = (); + type DustRemovalWhitelist = Nothing; + type ReserveIdentifier = NamedReserveIdentifier; + type MaxReserves = MaxReserves; + type CurrencyHooks = (); +} + +pub struct DummyRegistry(sp_std::marker::PhantomData); + +impl Inspect for DummyRegistry { + type AssetId = AssetId; + type Location = u8; + + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() + } + + fn decimals(_id: Self::AssetId) -> Option { + unimplemented!() + } + + fn is_sufficient(_id: Self::AssetId) -> bool { + unimplemented!() + } + + fn exists(asset_id: AssetId) -> bool { + let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id)).copied()); + asset.is_some() + } + + fn is_banned(_id: Self::AssetId) -> bool { + unimplemented!() + } + + fn asset_name(_id: Self::AssetId) -> Option> { + unimplemented!() + } + + fn asset_symbol(_id: Self::AssetId) -> Option> { + unimplemented!() + } + + fn existential_deposit(_id: Self::AssetId) -> Option { + unimplemented!() + } +} + +#[cfg(feature = "runtime-benchmarks")] +use hydradx_traits::Create as CreateRegistry; +#[cfg(feature = "runtime-benchmarks")] +use sp_runtime::DispatchError; +#[cfg(feature = "runtime-benchmarks")] +impl CreateRegistry for DummyRegistry +where + T::AssetId: Into + From, +{ + type Error = DispatchError; + type Name = sp_runtime::BoundedVec>; + type Symbol = sp_runtime::BoundedVec>; + + fn register_asset( + _asset_id: Option, + _name: Option, + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { + let assigned = REGISTERED_ASSETS.with(|v| { + //NOTE: This is to have same ids as real AssetRegistry which is used in the benchmarks. + //1_000_000 - offset of the reals AssetRegistry + // - 3 - remove assets reagistered by default for the vec.len() + // +1 - first reg asset start with 1 not 0 + // => 1-th asset id == 1_000_001 + let l = 1_000_000 - 3 + 1 + v.borrow().len(); + v.borrow_mut().insert(l as u32, l as u32); + l as u32 + }); + Ok(assigned) + } + + fn get_or_register_asset( + _name: Self::Name, + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { + unimplemented!() + } +} + +pub struct ExtBuilder { + endowed_accounts: Vec<(u64, AssetId, Balance)>, + registered_assets: Vec, +} + +impl Default for ExtBuilder { + fn default() -> Self { + // If eg. tests running on one thread only, this thread local is shared. + // let's make sure that it is empty for each test case + // or set to original default value + REGISTERED_ASSETS.with(|v| { + v.borrow_mut().clear(); + }); + EXISTENTIAL_DEPOSIT.with(|v| { + v.borrow_mut().clear(); + }); + + Self { + endowed_accounts: vec![ + (ALICE, HDX, 10_000), + (BOB, HDX, 10_000), + (ALICE, DAI, 100), + (BOB, DAI, 100), + (TreasuryAccount::get(), HDX, 1_000_000), + ], + registered_assets: vec![HDX, DAI], + } + } +} + +impl ExtBuilder { + pub fn with_existential_deposit(self, asset_id: AssetId, precision: u32) -> Self { + EXISTENTIAL_DEPOSIT.with(|v| { + v.borrow_mut().insert(asset_id, 10u128.pow(precision)); + }); + PRECISIONS.with(|v| { + v.borrow_mut().insert(asset_id, precision); + }); + + self + } + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + + // Add DAI and HDX as pre-registered assets + REGISTERED_ASSETS.with(|v| { + v.borrow_mut().insert(HDX, HDX); + v.borrow_mut().insert(REGISTERED_ASSET, REGISTERED_ASSET); + self.registered_assets.iter().for_each(|asset| { + v.borrow_mut().insert(*asset, *asset); + }); + }); + + orml_tokens::GenesisConfig:: { + balances: self + .endowed_accounts + .iter() + .flat_map(|(x, asset, amount)| vec![(*x, *asset, *amount * 10u128.pow(precision(*asset)))]) + .collect(), + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut r: sp_io::TestExternalities = t.into(); + + r.execute_with(|| { + System::set_block_number(1); + }); + + r + } +} + +// thread_local! { +// pub static DUMMYTHREADLOCAL: RefCell = const { RefCell::new(100) }; +// } + +pub fn expect_events(e: Vec) { + test_utils::expect_events::(e); +} + +pub fn precision(asset_id: AssetId) -> u32 { + PRECISIONS.with(|v| *v.borrow().get(&asset_id).unwrap_or(&12)) +} diff --git a/pallets/dispatcher/src/tests.rs b/pallets/dispatcher/src/tests.rs new file mode 100644 index 000000000..d92dc79bf --- /dev/null +++ b/pallets/dispatcher/src/tests.rs @@ -0,0 +1,50 @@ +use crate as dispatcher; +use crate::mock::*; +use crate::Weight; +use sp_runtime::{DispatchError, traits::{BlakeTwo256, Hash}}; +use frame_support::{assert_ok, assert_noop, dispatch::PostDispatchInfo}; +use frame_support::dispatch::Pays; +use orml_traits::MultiCurrency; +use crate::Event; + +#[test] +fn dispatch_as_treasury_manager_should_work() { + ExtBuilder::default().build().execute_with(|| { + // Arrange + let call = Box::new(RuntimeCall::Tokens(orml_tokens::Call::transfer { + dest: ALICE, + currency_id: HDX, + amount: 1_000, + })); + + let call_hash = BlakeTwo256::hash_of(&call).into(); + let treasury_balance_before = Tokens::free_balance(HDX, &TreasuryAccount::get()); + + assert_ok!(Dispatcher::dispatch_as_treasury_manager(RuntimeOrigin::root(), call)); + + let treasury_balance_after = Tokens::free_balance(HDX, &TreasuryAccount::get()); + + assert_eq!(treasury_balance_after, treasury_balance_before - 1_000); + + expect_events(vec![Event::TreasuryManagerCallDispatched { + call_hash: call_hash, + result: Ok(PostDispatchInfo { + actual_weight: None, + pays_fee: Pays::Yes, + }) + }.into()]); + }); +} + +#[test] +fn dispatch_as_treasury_manager_should_fail_when_bad_origin() { + ExtBuilder::default().build().execute_with(|| { + // Arrange + let call = Box::new(RuntimeCall::System(frame_system::Call::remark_with_event { + remark: vec![1], + })); + + assert_noop!(Dispatcher::dispatch_as_treasury_manager(RuntimeOrigin::signed(ALICE), call), DispatchError::BadOrigin); + expect_events(vec![]); + }); +} From 0d1b8f8b5923efd5366d609907c1214faaa687d4 Mon Sep 17 00:00:00 2001 From: vgantchev Date: Tue, 10 Dec 2024 13:06:04 +0100 Subject: [PATCH 04/17] add benchmarks --- pallets/dispatcher/src/benchmarking.rs | 50 ++++++++++++++++++++++++++ pallets/dispatcher/src/lib.rs | 24 ++++++------- pallets/dispatcher/src/mock.rs | 39 ++++++++++++-------- pallets/dispatcher/src/weights.rs | 4 +-- runtime/hydradx/src/governance/mod.rs | 1 + 5 files changed, 89 insertions(+), 29 deletions(-) create mode 100644 pallets/dispatcher/src/benchmarking.rs diff --git a/pallets/dispatcher/src/benchmarking.rs b/pallets/dispatcher/src/benchmarking.rs new file mode 100644 index 000000000..b40fbedf6 --- /dev/null +++ b/pallets/dispatcher/src/benchmarking.rs @@ -0,0 +1,50 @@ +// This file is part of https://github.com/galacticcouncil/* +// +// $$$$$$$ Licensed under the Apache License, Version 2.0 (the "License") +// $$$$$$$$$$$$$ you may only use this file in compliance with the License +// $$$$$$$$$$$$$$$$$$$ +// $$$$$$$$$ Copyright (C) 2021-2024 Intergalactic, Limited (GIB) +// $$$$$$$$$$$ $$$$$$$$$$ SPDX-License-Identifier: Apache-2.0 +// $$$$$$$$$$$$$$$$$$$$$$$$$$ +// $$$$$$$$$$$$$$$$$$$$$$$ $ Built with <3 for decentralisation +// $$$$$$$$$$$$$$$$$$$ $$$$$$$ +// $$$$$$$ $$$$$$$$$$$$$$$$$$ Unless required by applicable law or agreed to in +// $ $$$$$$$$$$$$$$$$$$$$$$$ writing, software distributed under the License is +// $$$$$$$$$$$$$$$$$$$$$$$$$$ distributed on an "AS IS" BASIS, WITHOUT WARRANTIES +// $$$$$$$$$ $$$$$$$$$$$ OR CONDITIONS OF ANY KIND, either express or implied. +// $$$$$$$$ +// $$$$$$$$$$$$$$$$$$ See the License for the specific language governing +// $$$$$$$$$$$$$ permissions and limitations under the License. +// $$$$$$$ +// $$ +// $$$$$ $$$$$ $$ $ +// $$$ $$$ $$$ $$ $$$$$ $$ $$$ $$$$ $$$$$$$ $$$$ $$$ $$$$$$ $$ $$$$$$ +// $$$ $$$ $$$ $$ $$$ $$$ $$$ $ $$ $$ $$ $$ $$ $$ $$$ $$$ +// $$$$$$$$$$$ $$ $$ $$$ $$ $$ $$$$$$$ $$ $$ $$ $$$ $$ $$ +// $$$ $$$ $$$$ $$$ $$ $$ $$$ $$ $$ $$ $$ $$ $$ $$ +// $$$$$ $$$$$ $$ $$$$$$$$ $ $$$ $$$$$$$$ $$$ $$$$ $$$$$$$ $$$$ $$$$ +// $$$ + +#![cfg(feature = "runtime-benchmarks")] +use super::*; + +use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite}; +use frame_system::RawOrigin; + +#[cfg(test)] +use crate::Pallet as Dispatcher; + +benchmarks! { + where_clause { where + T: crate::Config, + } + + dispatch_as_treasury_manager { + let n in 1 .. 10_000; + let remark = sp_std::vec![1u8; n as usize]; + + let call: T::RuntimeCall = frame_system::Call::remark { remark }.into(); + }: _(RawOrigin::Root, call) + + impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Test); +} diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs index 686fb42c6..ba9667417 100644 --- a/pallets/dispatcher/src/lib.rs +++ b/pallets/dispatcher/src/lib.rs @@ -32,8 +32,8 @@ mod tests; #[cfg(test)] pub mod mock; -// #[cfg(any(feature = "runtime-benchmarks", test))] -// mod benchmarks; +#[cfg(any(feature = "runtime-benchmarks", test))] +mod benchmarking; pub mod weights; @@ -89,35 +89,33 @@ pub mod pallet { AaveManagerCallDispatched { call_hash: T::Hash, result: DispatchResultWithPostInfo }, } - #[pallet::error] - pub enum Error { - /// The preimage of the call hash could not be loaded. - UnavailablePreImage, - } - #[pallet::call] impl Pallet { #[pallet::call_index(0)] - #[pallet::weight(::WeightInfo::dispatch_as_treasury_manager())] + #[pallet::weight({ + let call_weight = call.get_dispatch_info().weight; + let call_len = call.encoded_size() as u32; + + T::WeightInfo::dispatch_as_treasury_manager(call_len) + .saturating_add(call_weight) + })] pub fn dispatch_as_treasury_manager(origin: OriginFor, call: Box<::RuntimeCall>,) -> DispatchResultWithPostInfo { T::TreasuryManagerOrigin::ensure_origin(origin)?; let call_hash = T::Hashing::hash_of(&call).into(); let call_len = call.encoded_size() as u32; - /// TODO: Add call len to weight let actual_weight = Self::do_dispatch(T::TreasuryAccount::get(), call_hash, *call).map(|w| { - w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager()) + w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len)) }); Ok(actual_weight.into()) } - } } } impl Pallet { - /// Clean whitelisting/preimage and dispatch call. + /// Dispatch the call from the specified account as Signed Origin. /// /// Return the call actual weight of the dispatched call if there is some. fn do_dispatch(account: T::AccountId, call_hash: T::Hash, call: ::RuntimeCall) -> Option { diff --git a/pallets/dispatcher/src/mock.rs b/pallets/dispatcher/src/mock.rs index 9f8bc4458..0b5e5af14 100644 --- a/pallets/dispatcher/src/mock.rs +++ b/pallets/dispatcher/src/mock.rs @@ -1,17 +1,29 @@ -// This file is part of galacticcouncil/warehouse. -// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 +// This file is part of https://github.com/galacticcouncil/* // -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// $$$$$$$ Licensed under the Apache License, Version 2.0 (the "License") +// $$$$$$$$$$$$$ you may only use this file in compliance with the License +// $$$$$$$$$$$$$$$$$$$ +// $$$$$$$$$ Copyright (C) 2021-2024 Intergalactic, Limited (GIB) +// $$$$$$$$$$$ $$$$$$$$$$ SPDX-License-Identifier: Apache-2.0 +// $$$$$$$$$$$$$$$$$$$$$$$$$$ +// $$$$$$$$$$$$$$$$$$$$$$$ $ Built with <3 for decentralisation +// $$$$$$$$$$$$$$$$$$$ $$$$$$$ +// $$$$$$$ $$$$$$$$$$$$$$$$$$ Unless required by applicable law or agreed to in +// $ $$$$$$$$$$$$$$$$$$$$$$$ writing, software distributed under the License is +// $$$$$$$$$$$$$$$$$$$$$$$$$$ distributed on an "AS IS" BASIS, WITHOUT WARRANTIES +// $$$$$$$$$ $$$$$$$$$$$ OR CONDITIONS OF ANY KIND, either express or implied. +// $$$$$$$$ +// $$$$$$$$$$$$$$$$$$ See the License for the specific language governing +// $$$$$$$$$$$$$ permissions and limitations under the License. +// $$$$$$$ +// $$ +// $$$$$ $$$$$ $$ $ +// $$$ $$$ $$$ $$ $$$$$ $$ $$$ $$$$ $$$$$$$ $$$$ $$$ $$$$$$ $$ $$$$$$ +// $$$ $$$ $$$ $$ $$$ $$$ $$$ $ $$ $$ $$ $$ $$ $$ $$$ $$$ +// $$$$$$$$$$$ $$ $$ $$$ $$ $$ $$$$$$$ $$ $$ $$ $$$ $$ $$ +// $$$ $$$ $$$$ $$$ $$ $$ $$$ $$ $$ $$ $$ $$ $$ $$ +// $$$$$ $$$$$ $$ $$$$$$$$ $ $$$ $$$$$$$$ $$$ $$$$ $$$$$$$ $$$$ $$$$ +// $$$ use crate as dispatcher; use crate::Config; @@ -30,7 +42,6 @@ use sp_runtime::{ BuildStorage, Permill, }; use std::{cell::RefCell, collections::HashMap}; -use frame_support::traits::EitherOf; use frame_system::EnsureRoot; type Block = frame_system::mocking::MockBlock; diff --git a/pallets/dispatcher/src/weights.rs b/pallets/dispatcher/src/weights.rs index b3e34338b..1082c50f4 100644 --- a/pallets/dispatcher/src/weights.rs +++ b/pallets/dispatcher/src/weights.rs @@ -50,7 +50,7 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_otc. pub trait WeightInfo { - fn dispatch_as_treasury_manager() -> Weight; + fn dispatch_as_treasury_manager(n: u32,) -> Weight; } /// Weights for pallet_otc using the hydraDX node and recommended hardware. @@ -65,7 +65,7 @@ impl WeightInfo for () { /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `OTC::Orders` (r:0 w:1) /// Proof: `OTC::Orders` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) - fn dispatch_as_treasury_manager() -> Weight { + fn dispatch_as_treasury_manager(n: u32,) -> Weight { // Proof Size summary in bytes: // Measured: `963` // Estimated: `6190` diff --git a/runtime/hydradx/src/governance/mod.rs b/runtime/hydradx/src/governance/mod.rs index 54038489a..d26198744 100644 --- a/runtime/hydradx/src/governance/mod.rs +++ b/runtime/hydradx/src/governance/mod.rs @@ -236,4 +236,5 @@ impl pallet_dispatcher::Config for Runtime { type RuntimeEvent = RuntimeEvent; type TreasuryManagerOrigin = EitherOf, Treasurer>; type AaveManagerOrigin = EitherOf, Treasurer>; + type TreasuryAccount = TreasuryAccount; } From 5cc2215a1d38f7ada780b34084702bde2b8d5d60 Mon Sep 17 00:00:00 2001 From: vgantchev Date: Tue, 10 Dec 2024 13:06:56 +0100 Subject: [PATCH 05/17] fmt --- pallets/dispatcher/src/benchmarking.rs | 18 +- pallets/dispatcher/src/lib.rs | 154 +++++----- pallets/dispatcher/src/mock.rs | 373 ++++++++++++------------- pallets/dispatcher/src/tests.rs | 81 +++--- runtime/hydradx/src/weights/mod.rs | 2 +- 5 files changed, 322 insertions(+), 306 deletions(-) diff --git a/pallets/dispatcher/src/benchmarking.rs b/pallets/dispatcher/src/benchmarking.rs index b40fbedf6..bbbc148c9 100644 --- a/pallets/dispatcher/src/benchmarking.rs +++ b/pallets/dispatcher/src/benchmarking.rs @@ -35,16 +35,16 @@ use frame_system::RawOrigin; use crate::Pallet as Dispatcher; benchmarks! { - where_clause { where - T: crate::Config, - } + where_clause { where + T: crate::Config, + } - dispatch_as_treasury_manager { - let n in 1 .. 10_000; - let remark = sp_std::vec![1u8; n as usize]; + dispatch_as_treasury_manager { + let n in 1 .. 10_000; + let remark = sp_std::vec![1u8; n as usize]; - let call: T::RuntimeCall = frame_system::Call::remark { remark }.into(); - }: _(RawOrigin::Root, call) + let call: T::RuntimeCall = frame_system::Call::remark { remark }.into(); + }: _(RawOrigin::Root, call) - impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Test); + impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Test); } diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs index ba9667417..f83825660 100644 --- a/pallets/dispatcher/src/lib.rs +++ b/pallets/dispatcher/src/lib.rs @@ -27,10 +27,10 @@ #![cfg_attr(not(feature = "std"), no_std)] -#[cfg(test)] -mod tests; #[cfg(test)] pub mod mock; +#[cfg(test)] +mod tests; #[cfg(any(feature = "runtime-benchmarks", test))] mod benchmarking; @@ -41,93 +41,103 @@ use sp_runtime::traits::Dispatchable; pub use weights::WeightInfo; // Re-export pallet items so that they can be accessed from the crate namespace. -pub use pallet::*; use frame_support::pallet_prelude::Weight; +pub use pallet::*; #[frame_support::pallet] pub mod pallet { - use super::*; - use codec::FullCodec; - use frame_support::{dispatch::{GetDispatchInfo, PostDispatchInfo}, pallet_prelude::*}; - use frame_system::{pallet_prelude::*}; - use sp_runtime::traits::{Dispatchable, Hash}; - use sp_std::boxed::Box; - - - pub type AccountId = u64; - - #[pallet::config] - pub trait Config: frame_system::Config { - /// The overarching event type. - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - - /// The overarching call type. - type RuntimeCall: IsType<::RuntimeCall> - + Dispatchable - + GetDispatchInfo - + FullCodec - + TypeInfo - + From> - + Parameter; - - type TreasuryManagerOrigin: EnsureOrigin; - type AaveManagerOrigin: EnsureOrigin; - - type TreasuryAccount: Get; - - /// The weight information for this pallet. - type WeightInfo: WeightInfo; - } - - #[pallet::pallet] - pub struct Pallet(_); - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - TreasuryManagerCallDispatched { call_hash: T::Hash, result: DispatchResultWithPostInfo }, - AaveManagerCallDispatched { call_hash: T::Hash, result: DispatchResultWithPostInfo }, - } - - #[pallet::call] - impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight({ + use super::*; + use codec::FullCodec; + use frame_support::{ + dispatch::{GetDispatchInfo, PostDispatchInfo}, + pallet_prelude::*, + }; + use frame_system::pallet_prelude::*; + use sp_runtime::traits::{Dispatchable, Hash}; + use sp_std::boxed::Box; + + pub type AccountId = u64; + + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// The overarching call type. + type RuntimeCall: IsType<::RuntimeCall> + + Dispatchable + + GetDispatchInfo + + FullCodec + + TypeInfo + + From> + + Parameter; + + type TreasuryManagerOrigin: EnsureOrigin; + type AaveManagerOrigin: EnsureOrigin; + + type TreasuryAccount: Get; + + /// The weight information for this pallet. + type WeightInfo: WeightInfo; + } + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + TreasuryManagerCallDispatched { + call_hash: T::Hash, + result: DispatchResultWithPostInfo, + }, + AaveManagerCallDispatched { + call_hash: T::Hash, + result: DispatchResultWithPostInfo, + }, + } + + #[pallet::call] + impl Pallet { + #[pallet::call_index(0)] + #[pallet::weight({ let call_weight = call.get_dispatch_info().weight; let call_len = call.encoded_size() as u32; T::WeightInfo::dispatch_as_treasury_manager(call_len) .saturating_add(call_weight) })] - pub fn dispatch_as_treasury_manager(origin: OriginFor, call: Box<::RuntimeCall>,) -> DispatchResultWithPostInfo { - T::TreasuryManagerOrigin::ensure_origin(origin)?; + pub fn dispatch_as_treasury_manager( + origin: OriginFor, + call: Box<::RuntimeCall>, + ) -> DispatchResultWithPostInfo { + T::TreasuryManagerOrigin::ensure_origin(origin)?; - let call_hash = T::Hashing::hash_of(&call).into(); - let call_len = call.encoded_size() as u32; + let call_hash = T::Hashing::hash_of(&call).into(); + let call_len = call.encoded_size() as u32; - let actual_weight = Self::do_dispatch(T::TreasuryAccount::get(), call_hash, *call).map(|w| { - w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len)) - }); + let actual_weight = Self::do_dispatch(T::TreasuryAccount::get(), call_hash, *call) + .map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len))); - Ok(actual_weight.into()) - } - } + Ok(actual_weight.into()) + } + } } impl Pallet { - /// Dispatch the call from the specified account as Signed Origin. - /// - /// Return the call actual weight of the dispatched call if there is some. - fn do_dispatch(account: T::AccountId, call_hash: T::Hash, call: ::RuntimeCall) -> Option { - let result = call.dispatch(frame_system::Origin::::Signed(account).into()); + /// Dispatch the call from the specified account as Signed Origin. + /// + /// Return the call actual weight of the dispatched call if there is some. + fn do_dispatch(account: T::AccountId, call_hash: T::Hash, call: ::RuntimeCall) -> Option { + let result = call.dispatch(frame_system::Origin::::Signed(account).into()); - let call_actual_weight = match result { - Ok(call_post_info) => call_post_info.actual_weight.clone(), - Err(call_err) => call_err.post_info.actual_weight, - }; + let call_actual_weight = match result { + Ok(call_post_info) => call_post_info.actual_weight.clone(), + Err(call_err) => call_err.post_info.actual_weight, + }; - Self::deposit_event(Event::::TreasuryManagerCallDispatched { call_hash, result }); + Self::deposit_event(Event::::TreasuryManagerCallDispatched { call_hash, result }); - call_actual_weight - } + call_actual_weight + } } diff --git a/pallets/dispatcher/src/mock.rs b/pallets/dispatcher/src/mock.rs index 0b5e5af14..9cebfbc42 100644 --- a/pallets/dispatcher/src/mock.rs +++ b/pallets/dispatcher/src/mock.rs @@ -28,21 +28,21 @@ use crate as dispatcher; use crate::Config; use frame_support::{ - parameter_types, - traits::{Everything, Nothing}, - PalletId, + parameter_types, + traits::{Everything, Nothing}, + PalletId, }; use frame_system as system; +use frame_system::EnsureRoot; use hydradx_traits::{registry::Inspect, AssetKind}; use orml_tokens::AccountData; use orml_traits::parameter_type_with_key; use sp_core::H256; use sp_runtime::{ - traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, - BuildStorage, Permill, + traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, + BuildStorage, Permill, }; use std::{cell::RefCell, collections::HashMap}; -use frame_system::EnsureRoot; type Block = frame_system::mocking::MockBlock; @@ -94,13 +94,12 @@ parameter_type_with_key! { } impl dispatcher::Config for Test { - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type TreasuryManagerOrigin = EnsureRoot; - type AaveManagerOrigin = EnsureRoot; - type TreasuryAccount = TreasuryAccount; - type WeightInfo = (); - + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type TreasuryManagerOrigin = EnsureRoot; + type AaveManagerOrigin = EnsureRoot; + type TreasuryAccount = TreasuryAccount; + type WeightInfo = (); } parameter_types! { @@ -110,89 +109,89 @@ parameter_types! { } impl system::Config for Test { - type BaseCallFilter = Everything; - type BlockWeights = (); - type BlockLength = (); - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type RuntimeTask = RuntimeTask; - type Nonce = u64; - type Block = Block; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = BlockHashCount; - type DbWeight = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = SS58Prefix; - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; - type SingleBlockMigrations = (); - type MultiBlockMigrator = (); - type PreInherents = (); - type PostInherents = (); - type PostTransactions = (); + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeTask = RuntimeTask; + type Nonce = u64; + type Block = Block; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; + type SingleBlockMigrations = (); + type MultiBlockMigrator = (); + type PreInherents = (); + type PostInherents = (); + type PostTransactions = (); } impl orml_tokens::Config for Test { - type RuntimeEvent = RuntimeEvent; - type Balance = Balance; - type Amount = Amount; - type CurrencyId = AssetId; - type WeightInfo = (); - type ExistentialDeposits = ExistentialDeposits; - type MaxLocks = (); - type DustRemovalWhitelist = Nothing; - type ReserveIdentifier = NamedReserveIdentifier; - type MaxReserves = MaxReserves; - type CurrencyHooks = (); + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = Amount; + type CurrencyId = AssetId; + type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type MaxLocks = (); + type DustRemovalWhitelist = Nothing; + type ReserveIdentifier = NamedReserveIdentifier; + type MaxReserves = MaxReserves; + type CurrencyHooks = (); } pub struct DummyRegistry(sp_std::marker::PhantomData); impl Inspect for DummyRegistry { - type AssetId = AssetId; - type Location = u8; + type AssetId = AssetId; + type Location = u8; - fn asset_type(_id: Self::AssetId) -> Option { - unimplemented!() - } + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() + } - fn decimals(_id: Self::AssetId) -> Option { - unimplemented!() - } + fn decimals(_id: Self::AssetId) -> Option { + unimplemented!() + } - fn is_sufficient(_id: Self::AssetId) -> bool { - unimplemented!() - } + fn is_sufficient(_id: Self::AssetId) -> bool { + unimplemented!() + } - fn exists(asset_id: AssetId) -> bool { - let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id)).copied()); - asset.is_some() - } + fn exists(asset_id: AssetId) -> bool { + let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id)).copied()); + asset.is_some() + } - fn is_banned(_id: Self::AssetId) -> bool { - unimplemented!() - } + fn is_banned(_id: Self::AssetId) -> bool { + unimplemented!() + } - fn asset_name(_id: Self::AssetId) -> Option> { - unimplemented!() - } + fn asset_name(_id: Self::AssetId) -> Option> { + unimplemented!() + } - fn asset_symbol(_id: Self::AssetId) -> Option> { - unimplemented!() - } + fn asset_symbol(_id: Self::AssetId) -> Option> { + unimplemented!() + } - fn existential_deposit(_id: Self::AssetId) -> Option { - unimplemented!() - } + fn existential_deposit(_id: Self::AssetId) -> Option { + unimplemented!() + } } #[cfg(feature = "runtime-benchmarks")] @@ -202,121 +201,121 @@ use sp_runtime::DispatchError; #[cfg(feature = "runtime-benchmarks")] impl CreateRegistry for DummyRegistry where - T::AssetId: Into + From, + T::AssetId: Into + From, { - type Error = DispatchError; - type Name = sp_runtime::BoundedVec>; - type Symbol = sp_runtime::BoundedVec>; - - fn register_asset( - _asset_id: Option, - _name: Option, - _kind: AssetKind, - _existential_deposit: Option, - _symbol: Option, - _decimals: Option, - _location: Option, - _xcm_rate_limit: Option, - _is_sufficient: bool, - ) -> Result { - let assigned = REGISTERED_ASSETS.with(|v| { - //NOTE: This is to have same ids as real AssetRegistry which is used in the benchmarks. - //1_000_000 - offset of the reals AssetRegistry - // - 3 - remove assets reagistered by default for the vec.len() - // +1 - first reg asset start with 1 not 0 - // => 1-th asset id == 1_000_001 - let l = 1_000_000 - 3 + 1 + v.borrow().len(); - v.borrow_mut().insert(l as u32, l as u32); - l as u32 - }); - Ok(assigned) - } - - fn get_or_register_asset( - _name: Self::Name, - _kind: AssetKind, - _existential_deposit: Option, - _symbol: Option, - _decimals: Option, - _location: Option, - _xcm_rate_limit: Option, - _is_sufficient: bool, - ) -> Result { - unimplemented!() - } + type Error = DispatchError; + type Name = sp_runtime::BoundedVec>; + type Symbol = sp_runtime::BoundedVec>; + + fn register_asset( + _asset_id: Option, + _name: Option, + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { + let assigned = REGISTERED_ASSETS.with(|v| { + //NOTE: This is to have same ids as real AssetRegistry which is used in the benchmarks. + //1_000_000 - offset of the reals AssetRegistry + // - 3 - remove assets reagistered by default for the vec.len() + // +1 - first reg asset start with 1 not 0 + // => 1-th asset id == 1_000_001 + let l = 1_000_000 - 3 + 1 + v.borrow().len(); + v.borrow_mut().insert(l as u32, l as u32); + l as u32 + }); + Ok(assigned) + } + + fn get_or_register_asset( + _name: Self::Name, + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { + unimplemented!() + } } pub struct ExtBuilder { - endowed_accounts: Vec<(u64, AssetId, Balance)>, - registered_assets: Vec, + endowed_accounts: Vec<(u64, AssetId, Balance)>, + registered_assets: Vec, } impl Default for ExtBuilder { - fn default() -> Self { - // If eg. tests running on one thread only, this thread local is shared. - // let's make sure that it is empty for each test case - // or set to original default value - REGISTERED_ASSETS.with(|v| { - v.borrow_mut().clear(); - }); - EXISTENTIAL_DEPOSIT.with(|v| { - v.borrow_mut().clear(); - }); - - Self { - endowed_accounts: vec![ - (ALICE, HDX, 10_000), - (BOB, HDX, 10_000), - (ALICE, DAI, 100), - (BOB, DAI, 100), - (TreasuryAccount::get(), HDX, 1_000_000), - ], - registered_assets: vec![HDX, DAI], - } - } + fn default() -> Self { + // If eg. tests running on one thread only, this thread local is shared. + // let's make sure that it is empty for each test case + // or set to original default value + REGISTERED_ASSETS.with(|v| { + v.borrow_mut().clear(); + }); + EXISTENTIAL_DEPOSIT.with(|v| { + v.borrow_mut().clear(); + }); + + Self { + endowed_accounts: vec![ + (ALICE, HDX, 10_000), + (BOB, HDX, 10_000), + (ALICE, DAI, 100), + (BOB, DAI, 100), + (TreasuryAccount::get(), HDX, 1_000_000), + ], + registered_assets: vec![HDX, DAI], + } + } } impl ExtBuilder { - pub fn with_existential_deposit(self, asset_id: AssetId, precision: u32) -> Self { - EXISTENTIAL_DEPOSIT.with(|v| { - v.borrow_mut().insert(asset_id, 10u128.pow(precision)); - }); - PRECISIONS.with(|v| { - v.borrow_mut().insert(asset_id, precision); - }); - - self - } - pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - - // Add DAI and HDX as pre-registered assets - REGISTERED_ASSETS.with(|v| { - v.borrow_mut().insert(HDX, HDX); - v.borrow_mut().insert(REGISTERED_ASSET, REGISTERED_ASSET); - self.registered_assets.iter().for_each(|asset| { - v.borrow_mut().insert(*asset, *asset); - }); - }); - - orml_tokens::GenesisConfig:: { - balances: self - .endowed_accounts - .iter() - .flat_map(|(x, asset, amount)| vec![(*x, *asset, *amount * 10u128.pow(precision(*asset)))]) - .collect(), - } - .assimilate_storage(&mut t) - .unwrap(); - - let mut r: sp_io::TestExternalities = t.into(); - - r.execute_with(|| { - System::set_block_number(1); - }); - - r - } + pub fn with_existential_deposit(self, asset_id: AssetId, precision: u32) -> Self { + EXISTENTIAL_DEPOSIT.with(|v| { + v.borrow_mut().insert(asset_id, 10u128.pow(precision)); + }); + PRECISIONS.with(|v| { + v.borrow_mut().insert(asset_id, precision); + }); + + self + } + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + + // Add DAI and HDX as pre-registered assets + REGISTERED_ASSETS.with(|v| { + v.borrow_mut().insert(HDX, HDX); + v.borrow_mut().insert(REGISTERED_ASSET, REGISTERED_ASSET); + self.registered_assets.iter().for_each(|asset| { + v.borrow_mut().insert(*asset, *asset); + }); + }); + + orml_tokens::GenesisConfig:: { + balances: self + .endowed_accounts + .iter() + .flat_map(|(x, asset, amount)| vec![(*x, *asset, *amount * 10u128.pow(precision(*asset)))]) + .collect(), + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut r: sp_io::TestExternalities = t.into(); + + r.execute_with(|| { + System::set_block_number(1); + }); + + r + } } // thread_local! { @@ -324,9 +323,9 @@ impl ExtBuilder { // } pub fn expect_events(e: Vec) { - test_utils::expect_events::(e); + test_utils::expect_events::(e); } pub fn precision(asset_id: AssetId) -> u32 { - PRECISIONS.with(|v| *v.borrow().get(&asset_id).unwrap_or(&12)) + PRECISIONS.with(|v| *v.borrow().get(&asset_id).unwrap_or(&12)) } diff --git a/pallets/dispatcher/src/tests.rs b/pallets/dispatcher/src/tests.rs index d92dc79bf..877af3abd 100644 --- a/pallets/dispatcher/src/tests.rs +++ b/pallets/dispatcher/src/tests.rs @@ -1,50 +1,57 @@ use crate as dispatcher; use crate::mock::*; +use crate::Event; use crate::Weight; -use sp_runtime::{DispatchError, traits::{BlakeTwo256, Hash}}; -use frame_support::{assert_ok, assert_noop, dispatch::PostDispatchInfo}; use frame_support::dispatch::Pays; +use frame_support::{assert_noop, assert_ok, dispatch::PostDispatchInfo}; use orml_traits::MultiCurrency; -use crate::Event; +use sp_runtime::{ + traits::{BlakeTwo256, Hash}, + DispatchError, +}; #[test] fn dispatch_as_treasury_manager_should_work() { - ExtBuilder::default().build().execute_with(|| { - // Arrange - let call = Box::new(RuntimeCall::Tokens(orml_tokens::Call::transfer { - dest: ALICE, - currency_id: HDX, - amount: 1_000, - })); - - let call_hash = BlakeTwo256::hash_of(&call).into(); - let treasury_balance_before = Tokens::free_balance(HDX, &TreasuryAccount::get()); - - assert_ok!(Dispatcher::dispatch_as_treasury_manager(RuntimeOrigin::root(), call)); - - let treasury_balance_after = Tokens::free_balance(HDX, &TreasuryAccount::get()); - - assert_eq!(treasury_balance_after, treasury_balance_before - 1_000); - - expect_events(vec![Event::TreasuryManagerCallDispatched { - call_hash: call_hash, - result: Ok(PostDispatchInfo { - actual_weight: None, - pays_fee: Pays::Yes, - }) - }.into()]); - }); + ExtBuilder::default().build().execute_with(|| { + // Arrange + let call = Box::new(RuntimeCall::Tokens(orml_tokens::Call::transfer { + dest: ALICE, + currency_id: HDX, + amount: 1_000, + })); + + let call_hash = BlakeTwo256::hash_of(&call).into(); + let treasury_balance_before = Tokens::free_balance(HDX, &TreasuryAccount::get()); + + assert_ok!(Dispatcher::dispatch_as_treasury_manager(RuntimeOrigin::root(), call)); + + let treasury_balance_after = Tokens::free_balance(HDX, &TreasuryAccount::get()); + + assert_eq!(treasury_balance_after, treasury_balance_before - 1_000); + + expect_events(vec![Event::TreasuryManagerCallDispatched { + call_hash: call_hash, + result: Ok(PostDispatchInfo { + actual_weight: None, + pays_fee: Pays::Yes, + }), + } + .into()]); + }); } #[test] fn dispatch_as_treasury_manager_should_fail_when_bad_origin() { - ExtBuilder::default().build().execute_with(|| { - // Arrange - let call = Box::new(RuntimeCall::System(frame_system::Call::remark_with_event { - remark: vec![1], - })); - - assert_noop!(Dispatcher::dispatch_as_treasury_manager(RuntimeOrigin::signed(ALICE), call), DispatchError::BadOrigin); - expect_events(vec![]); - }); + ExtBuilder::default().build().execute_with(|| { + // Arrange + let call = Box::new(RuntimeCall::System(frame_system::Call::remark_with_event { + remark: vec![1], + })); + + assert_noop!( + Dispatcher::dispatch_as_treasury_manager(RuntimeOrigin::signed(ALICE), call), + DispatchError::BadOrigin + ); + expect_events(vec![]); + }); } diff --git a/runtime/hydradx/src/weights/mod.rs b/runtime/hydradx/src/weights/mod.rs index fe744ec7f..f5aeaba40 100644 --- a/runtime/hydradx/src/weights/mod.rs +++ b/runtime/hydradx/src/weights/mod.rs @@ -15,8 +15,8 @@ pub mod pallet_conviction_voting; pub mod pallet_currencies; pub mod pallet_dca; pub mod pallet_democracy; -pub mod pallet_duster; pub mod pallet_dispatcher; +pub mod pallet_duster; pub mod pallet_dynamic_evm_fee; pub mod pallet_elections_phragmen; pub mod pallet_ema_oracle; From f3bdbad8615d7441642a908e058d6da4403e47e0 Mon Sep 17 00:00:00 2001 From: vgantchev Date: Fri, 13 Dec 2024 12:55:57 +0100 Subject: [PATCH 06/17] start benchmarks --- pallets/dispatcher/src/benchmarking.rs | 20 ++++++++++++------- pallets/dispatcher/src/lib.rs | 2 +- .../hydradx/src/weights/pallet_dispatcher.rs | 2 +- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/pallets/dispatcher/src/benchmarking.rs b/pallets/dispatcher/src/benchmarking.rs index bbbc148c9..b135ad986 100644 --- a/pallets/dispatcher/src/benchmarking.rs +++ b/pallets/dispatcher/src/benchmarking.rs @@ -25,15 +25,12 @@ // $$$$$ $$$$$ $$ $$$$$$$$ $ $$$ $$$$$$$$ $$$ $$$$ $$$$$$$ $$$$ $$$$ // $$$ -#![cfg(feature = "runtime-benchmarks")] + use super::*; -use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite}; +use frame_benchmarking::benchmarks; use frame_system::RawOrigin; -#[cfg(test)] -use crate::Pallet as Dispatcher; - benchmarks! { where_clause { where T: crate::Config, @@ -43,8 +40,17 @@ benchmarks! { let n in 1 .. 10_000; let remark = sp_std::vec![1u8; n as usize]; - let call: T::RuntimeCall = frame_system::Call::remark { remark }.into(); - }: _(RawOrigin::Root, call) + let call: ::RuntimeCall = frame_system::Call::remark { remark }.into(); + }: _(RawOrigin::Root, Box::new(call)) + + impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Test); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mock::*; + use frame_benchmarking::impl_benchmark_test_suite; impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Test); } diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs index f83825660..088b381fe 100644 --- a/pallets/dispatcher/src/lib.rs +++ b/pallets/dispatcher/src/lib.rs @@ -32,7 +32,7 @@ pub mod mock; #[cfg(test)] mod tests; -#[cfg(any(feature = "runtime-benchmarks", test))] +#[cfg(feature = "runtime-benchmarks")] mod benchmarking; pub mod weights; diff --git a/runtime/hydradx/src/weights/pallet_dispatcher.rs b/runtime/hydradx/src/weights/pallet_dispatcher.rs index c367072fe..455517030 100644 --- a/runtime/hydradx/src/weights/pallet_dispatcher.rs +++ b/runtime/hydradx/src/weights/pallet_dispatcher.rs @@ -58,7 +58,7 @@ impl pallet_dispatcher::WeightInfo for HydraWeight { /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// Storage: `Preimage::RequestStatusFor` (r:1 w:1) /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) - fn dispatch_as_treasury_manager() -> Weight { + fn dispatch_as_treasury_manager(n: u32,) -> Weight { // Proof Size summary in bytes: // Measured: `218` // Estimated: `3556` From c1bb1b142d0546141ea269a387453c02496ce5f5 Mon Sep 17 00:00:00 2001 From: vgantchev Date: Fri, 13 Dec 2024 18:36:50 +0100 Subject: [PATCH 07/17] add aave --- pallets/dispatcher/src/lib.rs | 34 ++++++++++++++++--- pallets/dispatcher/src/mock.rs | 1 + pallets/dispatcher/src/weights.rs | 11 ++++++ runtime/hydradx/src/governance/mod.rs | 1 + .../hydradx/src/weights/pallet_dispatcher.rs | 10 ++++++ 5 files changed, 53 insertions(+), 4 deletions(-) diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs index 088b381fe..762ecd542 100644 --- a/pallets/dispatcher/src/lib.rs +++ b/pallets/dispatcher/src/lib.rs @@ -76,6 +76,7 @@ pub mod pallet { type AaveManagerOrigin: EnsureOrigin; type TreasuryAccount: Get; + type AaveManagerAccount: Get; /// The weight information for this pallet. type WeightInfo: WeightInfo; @@ -116,9 +117,36 @@ pub mod pallet { let call_hash = T::Hashing::hash_of(&call).into(); let call_len = call.encoded_size() as u32; - let actual_weight = Self::do_dispatch(T::TreasuryAccount::get(), call_hash, *call) + let actual_weight = Self::do_dispatch(T::TreasuryAccount::get(), *call) .map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len))); + Self::deposit_event(Event::::TreasuryManagerCallDispatched { call_hash, result }); + + Ok(actual_weight.into()) + } + + #[crate::pallet::call_index(1)] + #[crate::pallet::weight({ + let call_weight = call.get_dispatch_info().weight; + let call_len = call.encoded_size() as u32; + + T::WeightInfo::dispatch_as_aave_manager(call_len) + .saturating_add(call_weight) + })] + pub fn dispatch_as_aave_manager( + origin: OriginFor, + call: Box<::RuntimeCall>, + ) -> DispatchResultWithPostInfo { + T::AaveManagerOrigin::ensure_origin(origin)?; + + let call_hash = T::Hashing::hash_of(&call).into(); + let call_len = call.encoded_size() as u32; + + let actual_weight = Self::do_dispatch(T::AaveManagerAccount::get(), *call) + .map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len))); + + Self::deposit_event(Event::::AaveManagerCallDispatched { call_hash, result }); + Ok(actual_weight.into()) } } @@ -128,7 +156,7 @@ impl Pallet { /// Dispatch the call from the specified account as Signed Origin. /// /// Return the call actual weight of the dispatched call if there is some. - fn do_dispatch(account: T::AccountId, call_hash: T::Hash, call: ::RuntimeCall) -> Option { + fn do_dispatch(account: T::AccountId, call: ::RuntimeCall) -> Option { let result = call.dispatch(frame_system::Origin::::Signed(account).into()); let call_actual_weight = match result { @@ -136,8 +164,6 @@ impl Pallet { Err(call_err) => call_err.post_info.actual_weight, }; - Self::deposit_event(Event::::TreasuryManagerCallDispatched { call_hash, result }); - call_actual_weight } } diff --git a/pallets/dispatcher/src/mock.rs b/pallets/dispatcher/src/mock.rs index 9cebfbc42..412a9b6db 100644 --- a/pallets/dispatcher/src/mock.rs +++ b/pallets/dispatcher/src/mock.rs @@ -99,6 +99,7 @@ impl dispatcher::Config for Test { type TreasuryManagerOrigin = EnsureRoot; type AaveManagerOrigin = EnsureRoot; type TreasuryAccount = TreasuryAccount; + type AaveManagerAccount = TreasuryAccount; type WeightInfo = (); } diff --git a/pallets/dispatcher/src/weights.rs b/pallets/dispatcher/src/weights.rs index 1082c50f4..5b32c72a1 100644 --- a/pallets/dispatcher/src/weights.rs +++ b/pallets/dispatcher/src/weights.rs @@ -51,6 +51,7 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_otc. pub trait WeightInfo { fn dispatch_as_treasury_manager(n: u32,) -> Weight; + fn dispatch_as_aave_manager(n: u32,) -> Weight; } /// Weights for pallet_otc using the hydraDX node and recommended hardware. @@ -74,4 +75,14 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } + + fn dispatch_as_aave_manager(n: u32,) -> Weight { + // Proof Size summary in bytes: + // Measured: `963` + // Estimated: `6190` + // Minimum execution time: 46_446_000 picoseconds. + Weight::from_parts(47_816_000, 6190) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(4_u64)) + } } diff --git a/runtime/hydradx/src/governance/mod.rs b/runtime/hydradx/src/governance/mod.rs index d26198744..6adc698ab 100644 --- a/runtime/hydradx/src/governance/mod.rs +++ b/runtime/hydradx/src/governance/mod.rs @@ -237,4 +237,5 @@ impl pallet_dispatcher::Config for Runtime { type TreasuryManagerOrigin = EitherOf, Treasurer>; type AaveManagerOrigin = EitherOf, Treasurer>; type TreasuryAccount = TreasuryAccount; + type AaveManagerAccount = TreasuryAccount; } diff --git a/runtime/hydradx/src/weights/pallet_dispatcher.rs b/runtime/hydradx/src/weights/pallet_dispatcher.rs index 455517030..a337d5bcf 100644 --- a/runtime/hydradx/src/weights/pallet_dispatcher.rs +++ b/runtime/hydradx/src/weights/pallet_dispatcher.rs @@ -67,4 +67,14 @@ impl pallet_dispatcher::WeightInfo for HydraWeight { .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } + + fn dispatch_as_aave_manager(n: u32,) -> Weight { + // Proof Size summary in bytes: + // Measured: `218` + // Estimated: `3556` + // Minimum execution time: 23_242_000 picoseconds. + Weight::from_parts(23_861_000, 3556) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } } From 3a075ace7f011019c8feb9afd4060aabd8f7823d Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 16:50:59 +0100 Subject: [PATCH 08/17] buildable --- pallets/dispatcher/src/benchmarking.rs | 1 - pallets/dispatcher/src/lib.rs | 24 ++++++++++++++---------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/pallets/dispatcher/src/benchmarking.rs b/pallets/dispatcher/src/benchmarking.rs index b135ad986..c934143b2 100644 --- a/pallets/dispatcher/src/benchmarking.rs +++ b/pallets/dispatcher/src/benchmarking.rs @@ -25,7 +25,6 @@ // $$$$$ $$$$$ $$ $$$$$$$$ $ $$$ $$$$$$$$ $$$ $$$$ $$$$$$$ $$$$ $$$$ // $$$ - use super::*; use frame_benchmarking::benchmarks; diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs index 762ecd542..1c08ed5b9 100644 --- a/pallets/dispatcher/src/lib.rs +++ b/pallets/dispatcher/src/lib.rs @@ -37,7 +37,8 @@ mod benchmarking; pub mod weights; -use sp_runtime::traits::Dispatchable; +use frame_support::dispatch::PostDispatchInfo; +use sp_runtime::{traits::Dispatchable, DispatchResultWithInfo}; pub use weights::WeightInfo; // Re-export pallet items so that they can be accessed from the crate namespace. @@ -117,16 +118,16 @@ pub mod pallet { let call_hash = T::Hashing::hash_of(&call).into(); let call_len = call.encoded_size() as u32; - let actual_weight = Self::do_dispatch(T::TreasuryAccount::get(), *call) - .map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len))); + let (result, actual_weight) = Self::do_dispatch(T::TreasuryAccount::get(), *call); + actual_weight.map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len))); Self::deposit_event(Event::::TreasuryManagerCallDispatched { call_hash, result }); Ok(actual_weight.into()) } - - #[crate::pallet::call_index(1)] - #[crate::pallet::weight({ + + #[pallet::call_index(1)] + #[pallet::weight({ let call_weight = call.get_dispatch_info().weight; let call_len = call.encoded_size() as u32; @@ -142,8 +143,8 @@ pub mod pallet { let call_hash = T::Hashing::hash_of(&call).into(); let call_len = call.encoded_size() as u32; - let actual_weight = Self::do_dispatch(T::AaveManagerAccount::get(), *call) - .map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len))); + let (result, actual_weight) = Self::do_dispatch(T::AaveManagerAccount::get(), *call); + actual_weight.map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len))); Self::deposit_event(Event::::AaveManagerCallDispatched { call_hash, result }); @@ -156,7 +157,10 @@ impl Pallet { /// Dispatch the call from the specified account as Signed Origin. /// /// Return the call actual weight of the dispatched call if there is some. - fn do_dispatch(account: T::AccountId, call: ::RuntimeCall) -> Option { + fn do_dispatch( + account: T::AccountId, + call: ::RuntimeCall, + ) -> (DispatchResultWithInfo, Option) { let result = call.dispatch(frame_system::Origin::::Signed(account).into()); let call_actual_weight = match result { @@ -164,6 +168,6 @@ impl Pallet { Err(call_err) => call_err.post_info.actual_weight, }; - call_actual_weight + (result, call_actual_weight) } } From 45ee50976a0e2aadbf80570cfa750f990fa5f79f Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 21:36:24 +0100 Subject: [PATCH 09/17] benchmarks --- pallets/dispatcher/src/benchmarking.rs | 13 ++-- pallets/dispatcher/src/weights.rs | 74 ++++++++----------- runtime/hydradx/Cargo.toml | 1 + .../hydradx/src/weights/pallet_dispatcher.rs | 51 ++++++------- 4 files changed, 62 insertions(+), 77 deletions(-) diff --git a/pallets/dispatcher/src/benchmarking.rs b/pallets/dispatcher/src/benchmarking.rs index c934143b2..8a203b7f5 100644 --- a/pallets/dispatcher/src/benchmarking.rs +++ b/pallets/dispatcher/src/benchmarking.rs @@ -29,6 +29,7 @@ use super::*; use frame_benchmarking::benchmarks; use frame_system::RawOrigin; +use sp_std::boxed::Box; benchmarks! { where_clause { where @@ -42,14 +43,12 @@ benchmarks! { let call: ::RuntimeCall = frame_system::Call::remark { remark }.into(); }: _(RawOrigin::Root, Box::new(call)) - impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Test); -} + dispatch_as_aave_manager { + let n in 1 .. 10_000; + let remark = sp_std::vec![1u8; n as usize]; -#[cfg(test)] -mod tests { - use super::*; - use crate::mock::*; - use frame_benchmarking::impl_benchmark_test_suite; + let call: ::RuntimeCall = frame_system::Call::remark { remark }.into(); + }: _(RawOrigin::Root, Box::new(call)) impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Test); } diff --git a/pallets/dispatcher/src/weights.rs b/pallets/dispatcher/src/weights.rs index 5b32c72a1..b073d9aaa 100644 --- a/pallets/dispatcher/src/weights.rs +++ b/pallets/dispatcher/src/weights.rs @@ -16,12 +16,12 @@ // limitations under the License. -//! Autogenerated weights for `pallet_otc` +//! Autogenerated weights for `pallet_dispatcher` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-09-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-12-29, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! HOSTNAME: `MBP.local`, CPU: `` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -29,60 +29,50 @@ // benchmark // pallet // --chain=dev -// --steps=50 -// --repeat=20 +// --steps=10 +// --repeat=30 // --wasm-execution=compiled -// --pallet=pallet-otc -// --extrinsic=* +// --heap-pages=4096 // --template=scripts/pallet-weight-template.hbs -// --output=./weights/pallet_otc.rs +// --pallet=pallet-dispatcher +// --output=weights.rs +// --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] #![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use core::marker::PhantomData; -/// Weight functions needed for pallet_otc. +/// Weight functions needed for duster. pub trait WeightInfo { - fn dispatch_as_treasury_manager(n: u32,) -> Weight; - fn dispatch_as_aave_manager(n: u32,) -> Weight; + fn dispatch_as_treasury_manager(n: u32) -> Weight; + fn dispatch_as_aave_manager(n: u32) -> Weight; } -/// Weights for pallet_otc using the hydraDX node and recommended hardware. +/// Weights for `pallet_dispatcher` using the HydraDX node and recommended hardware. +pub struct HydraWeight(PhantomData); impl WeightInfo for () { - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) - /// Storage: `OTC::NextOrderId` (r:1 w:1) - /// Proof: `OTC::NextOrderId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Reserves` (r:1 w:1) - /// Proof: `Tokens::Reserves` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:1 w:1) - /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `OTC::Orders` (r:0 w:1) - /// Proof: `OTC::Orders` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) - fn dispatch_as_treasury_manager(n: u32,) -> Weight { + /// The range of component `n` is `[1, 10000]`. + fn dispatch_as_treasury_manager(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `963` - // Estimated: `6190` - // Minimum execution time: 46_446_000 picoseconds. - Weight::from_parts(47_816_000, 6190) - .saturating_add(RocksDbWeight::get().reads(5_u64)) - .saturating_add(RocksDbWeight::get().writes(4_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_000_000 picoseconds. + Weight::from_parts(7_765_739, 0) + // Standard Error: 13 + .saturating_add(Weight::from_parts(1_305, 0).saturating_mul(n.into())) } - - fn dispatch_as_aave_manager(n: u32,) -> Weight { + /// The range of component `n` is `[1, 10000]`. + fn dispatch_as_aave_manager(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `963` - // Estimated: `6190` - // Minimum execution time: 46_446_000 picoseconds. - Weight::from_parts(47_816_000, 6190) - .saturating_add(RocksDbWeight::get().reads(5_u64)) - .saturating_add(RocksDbWeight::get().writes(4_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_000_000 picoseconds. + Weight::from_parts(9_277_359, 0) + // Standard Error: 52 + .saturating_add(Weight::from_parts(1_049, 0).saturating_mul(n.into())) } } diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index bb6b96984..912a2372a 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -226,6 +226,7 @@ runtime-benchmarks = [ "pallet-conviction-voting/runtime-benchmarks", "pallet-referenda/runtime-benchmarks", "pallet-whitelist/runtime-benchmarks", + "pallet-dispatcher/runtime-benchmarks", ] std = [ "codec/std", diff --git a/runtime/hydradx/src/weights/pallet_dispatcher.rs b/runtime/hydradx/src/weights/pallet_dispatcher.rs index a337d5bcf..1884fdeab 100644 --- a/runtime/hydradx/src/weights/pallet_dispatcher.rs +++ b/runtime/hydradx/src/weights/pallet_dispatcher.rs @@ -16,12 +16,12 @@ // limitations under the License. -//! Autogenerated weights for `pallet_whitelist` +//! Autogenerated weights for `pallet_dispatcher` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-07-30, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-12-29, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! HOSTNAME: `MBP.local`, CPU: `` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -34,8 +34,8 @@ // --wasm-execution=compiled // --heap-pages=4096 // --template=scripts/pallet-weight-template.hbs -// --pallet=pallet-whitelist -// --output=pallet_whitelist.rs +// --pallet=pallet-dispatcher +// --output=weights.rs // --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] @@ -46,35 +46,30 @@ use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use core::marker::PhantomData; -/// Weights for `pallet_whitelist`. +/// Weights for `pallet_dispatcher`. pub struct WeightInfo(PhantomData); -/// Weights for `pallet_whitelist` using the HydraDX node and recommended hardware. +/// Weights for `pallet_dispatcher` using the HydraDX node and recommended hardware. pub struct HydraWeight(PhantomData); impl pallet_dispatcher::WeightInfo for HydraWeight { - /// Storage: `Whitelist::WhitelistedCall` (r:1 w:1) - /// Proof: `Whitelist::WhitelistedCall` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) - /// Storage: `Preimage::StatusFor` (r:1 w:0) - /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) - /// Storage: `Preimage::RequestStatusFor` (r:1 w:1) - /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) - fn dispatch_as_treasury_manager(n: u32,) -> Weight { + /// The range of component `n` is `[1, 10000]`. + fn dispatch_as_treasury_manager(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `218` - // Estimated: `3556` - // Minimum execution time: 23_242_000 picoseconds. - Weight::from_parts(23_861_000, 3556) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_000_000 picoseconds. + Weight::from_parts(7_765_739, 0) + // Standard Error: 13 + .saturating_add(Weight::from_parts(1_305, 0).saturating_mul(n.into())) } - - fn dispatch_as_aave_manager(n: u32,) -> Weight { + /// The range of component `n` is `[1, 10000]`. + fn dispatch_as_aave_manager(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `218` - // Estimated: `3556` - // Minimum execution time: 23_242_000 picoseconds. - Weight::from_parts(23_861_000, 3556) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_000_000 picoseconds. + Weight::from_parts(9_277_359, 0) + // Standard Error: 52 + .saturating_add(Weight::from_parts(1_049, 0).saturating_mul(n.into())) } } From cbca5ae5f35bd59554d180c1b46b5c209d032267 Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 21:39:46 +0100 Subject: [PATCH 10/17] add OpenGov track EconomicParameters as AaveManagerOrigin --- runtime/hydradx/src/governance/mod.rs | 4 ++-- runtime/hydradx/src/governance/origins.rs | 2 ++ runtime/hydradx/src/governance/tracks.rs | 17 ++++++++++++++++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/runtime/hydradx/src/governance/mod.rs b/runtime/hydradx/src/governance/mod.rs index 6adc698ab..20f51cffe 100644 --- a/runtime/hydradx/src/governance/mod.rs +++ b/runtime/hydradx/src/governance/mod.rs @@ -33,7 +33,7 @@ pub mod tracks; use super::*; use crate::governance::{ - origins::{GeneralAdmin, ReferendumCanceller, ReferendumKiller, Spender, Treasurer, WhitelistedCaller}, + origins::{EconomicParameters, GeneralAdmin, ReferendumCanceller, ReferendumKiller, Spender, Treasurer, WhitelistedCaller}, tracks::TracksInfo, }; use frame_support::{ @@ -235,7 +235,7 @@ impl pallet_dispatcher::Config for Runtime { type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type TreasuryManagerOrigin = EitherOf, Treasurer>; - type AaveManagerOrigin = EitherOf, Treasurer>; + type AaveManagerOrigin = EitherOf, EconomicParameters>; type TreasuryAccount = TreasuryAccount; type AaveManagerAccount = TreasuryAccount; } diff --git a/runtime/hydradx/src/governance/origins.rs b/runtime/hydradx/src/governance/origins.rs index dc65f901e..d8881eb2b 100644 --- a/runtime/hydradx/src/governance/origins.rs +++ b/runtime/hydradx/src/governance/origins.rs @@ -61,6 +61,7 @@ pub mod pallet_custom_origins { Spender, /// Origin able to spend up to roughly $500 from the treasury at once. Tipper, + EconomicParameters, } macro_rules! decl_unit_ensures { @@ -100,6 +101,7 @@ pub mod pallet_custom_origins { ReferendumCanceller, ReferendumKiller, Treasurer, + EconomicParameters, ); macro_rules! decl_ensure { diff --git a/runtime/hydradx/src/governance/tracks.rs b/runtime/hydradx/src/governance/tracks.rs index 560807637..54e157745 100644 --- a/runtime/hydradx/src/governance/tracks.rs +++ b/runtime/hydradx/src/governance/tracks.rs @@ -45,7 +45,7 @@ const SUP_RECIP: Curve = Curve::make_reciprocal(5, 7, percent(1), percent(0), pe const SUP_FAST_RECIP: Curve = Curve::make_reciprocal(3, 7, percent(1), percent(0), percent(50)); const SUP_WHITELISTED_CALLER: Curve = Curve::make_reciprocal(1, 28, percent(3), percent(2), percent(50)); -const TRACKS_DATA: [(u16, pallet_referenda::TrackInfo); 9] = [ +const TRACKS_DATA: [(u16, pallet_referenda::TrackInfo); 10] = [ ( 0, pallet_referenda::TrackInfo { @@ -172,6 +172,20 @@ const TRACKS_DATA: [(u16, pallet_referenda::TrackInfo); 9] min_support: SUP_RECIP, }, ), + ( + 9, + pallet_referenda::TrackInfo { + name: "economic_parameters", + max_deciding: 3, + decision_deposit: 500_000 * UNITS, + prepare_period: 60 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 3 * HOURS, + min_enactment_period: 10 * MINUTES, + min_approval: APP_RECIP, + min_support: SUP_RECIP, + }, + ), ]; pub struct TracksInfo; @@ -197,6 +211,7 @@ impl pallet_referenda::TracksInfo for TracksInfo { origins::Origin::Spender => Ok(6), origins::Origin::Tipper => Ok(7), origins::Origin::OmnipoolAdmin => Ok(8), + origins::Origin::EconomicParameters => Ok(9), } } else { Err(()) From af30e2f9f6dcf0f72d37c4b272cb8da8dc31b8ee Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 21:41:31 +0100 Subject: [PATCH 11/17] format --- runtime/hydradx/src/governance/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/runtime/hydradx/src/governance/mod.rs b/runtime/hydradx/src/governance/mod.rs index 20f51cffe..441fd24d5 100644 --- a/runtime/hydradx/src/governance/mod.rs +++ b/runtime/hydradx/src/governance/mod.rs @@ -33,7 +33,9 @@ pub mod tracks; use super::*; use crate::governance::{ - origins::{EconomicParameters, GeneralAdmin, ReferendumCanceller, ReferendumKiller, Spender, Treasurer, WhitelistedCaller}, + origins::{ + EconomicParameters, GeneralAdmin, ReferendumCanceller, ReferendumKiller, Spender, Treasurer, WhitelistedCaller, + }, tracks::TracksInfo, }; use frame_support::{ From 451b69750a685378f1063221ce71d575dc88784d Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 21:43:13 +0100 Subject: [PATCH 12/17] bump runtime version --- Cargo.lock | 2 +- runtime/hydradx/Cargo.toml | 2 +- runtime/hydradx/src/lib.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b6320c5ae..70ef93896 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4918,7 +4918,7 @@ dependencies = [ [[package]] name = "hydradx-runtime" -version = "276.0.0" +version = "277.0.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-parachain-system", diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index aa5d5dc67..cd6f93f0f 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-runtime" -version = "276.0.0" +version = "277.0.0" authors = ["GalacticCouncil"] edition = "2021" license = "Apache 2.0" diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index 0bc614ba8..32a1c20fe 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -113,7 +113,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("hydradx"), impl_name: create_runtime_str!("hydradx"), authoring_version: 1, - spec_version: 276, + spec_version: 277, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, From 057849afad3992989b08532954dc03afdee4f9b8 Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 21:51:25 +0100 Subject: [PATCH 13/17] rename to dispatch_as_treasury --- pallets/dispatcher/README.md | 2 +- pallets/dispatcher/src/benchmarking.rs | 2 +- pallets/dispatcher/src/lib.rs | 8 ++++---- pallets/dispatcher/src/tests.rs | 8 ++++---- pallets/dispatcher/src/weights.rs | 4 ++-- runtime/hydradx/src/weights/pallet_dispatcher.rs | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/pallets/dispatcher/README.md b/pallets/dispatcher/README.md index 41ba5dee9..e4d95a35a 100644 --- a/pallets/dispatcher/README.md +++ b/pallets/dispatcher/README.md @@ -2,5 +2,5 @@ This pallet enables specific OpenGov tracks to dispatch Runtime calls as predefined origins. The pallet supports the following dispatchables: -* `dispatch_as_treasury_manager` - allows the `TreasuryManager` track to dispatch calls as the Treasury account on Hydration (`7L53bUTBopuwFt3mKUfmkzgGLayYa1Yvn1hAg9v5UMrQzTfh`) +* `dispatch_as_treasury` - allows the `Treasury` track to dispatch calls as the Treasury account on Hydration (`7L53bUTBopuwFt3mKUfmkzgGLayYa1Yvn1hAg9v5UMrQzTfh`) * `dispatch_as_aave_manager` - allows the `AaveManager` track to dispatch calls as the Money Market authority on Hydration (`add addr`) diff --git a/pallets/dispatcher/src/benchmarking.rs b/pallets/dispatcher/src/benchmarking.rs index 8a203b7f5..89c1c5ef8 100644 --- a/pallets/dispatcher/src/benchmarking.rs +++ b/pallets/dispatcher/src/benchmarking.rs @@ -36,7 +36,7 @@ benchmarks! { T: crate::Config, } - dispatch_as_treasury_manager { + dispatch_as_treasury { let n in 1 .. 10_000; let remark = sp_std::vec![1u8; n as usize]; diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs index 1c08ed5b9..ce2b84398 100644 --- a/pallets/dispatcher/src/lib.rs +++ b/pallets/dispatcher/src/lib.rs @@ -106,10 +106,10 @@ pub mod pallet { let call_weight = call.get_dispatch_info().weight; let call_len = call.encoded_size() as u32; - T::WeightInfo::dispatch_as_treasury_manager(call_len) + T::WeightInfo::dispatch_as_treasury(call_len) .saturating_add(call_weight) })] - pub fn dispatch_as_treasury_manager( + pub fn dispatch_as_treasury( origin: OriginFor, call: Box<::RuntimeCall>, ) -> DispatchResultWithPostInfo { @@ -119,7 +119,7 @@ pub mod pallet { let call_len = call.encoded_size() as u32; let (result, actual_weight) = Self::do_dispatch(T::TreasuryAccount::get(), *call); - actual_weight.map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len))); + actual_weight.map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury(call_len))); Self::deposit_event(Event::::TreasuryManagerCallDispatched { call_hash, result }); @@ -144,7 +144,7 @@ pub mod pallet { let call_len = call.encoded_size() as u32; let (result, actual_weight) = Self::do_dispatch(T::AaveManagerAccount::get(), *call); - actual_weight.map(|w| w.saturating_add(T::WeightInfo::dispatch_as_treasury_manager(call_len))); + actual_weight.map(|w| w.saturating_add(T::WeightInfo::dispatch_as_aave_manager(call_len))); Self::deposit_event(Event::::AaveManagerCallDispatched { call_hash, result }); diff --git a/pallets/dispatcher/src/tests.rs b/pallets/dispatcher/src/tests.rs index 877af3abd..964c870d8 100644 --- a/pallets/dispatcher/src/tests.rs +++ b/pallets/dispatcher/src/tests.rs @@ -11,7 +11,7 @@ use sp_runtime::{ }; #[test] -fn dispatch_as_treasury_manager_should_work() { +fn dispatch_as_treasury_should_work() { ExtBuilder::default().build().execute_with(|| { // Arrange let call = Box::new(RuntimeCall::Tokens(orml_tokens::Call::transfer { @@ -23,7 +23,7 @@ fn dispatch_as_treasury_manager_should_work() { let call_hash = BlakeTwo256::hash_of(&call).into(); let treasury_balance_before = Tokens::free_balance(HDX, &TreasuryAccount::get()); - assert_ok!(Dispatcher::dispatch_as_treasury_manager(RuntimeOrigin::root(), call)); + assert_ok!(Dispatcher::dispatch_as_treasury(RuntimeOrigin::root(), call)); let treasury_balance_after = Tokens::free_balance(HDX, &TreasuryAccount::get()); @@ -41,7 +41,7 @@ fn dispatch_as_treasury_manager_should_work() { } #[test] -fn dispatch_as_treasury_manager_should_fail_when_bad_origin() { +fn dispatch_as_treasury_should_fail_when_bad_origin() { ExtBuilder::default().build().execute_with(|| { // Arrange let call = Box::new(RuntimeCall::System(frame_system::Call::remark_with_event { @@ -49,7 +49,7 @@ fn dispatch_as_treasury_manager_should_fail_when_bad_origin() { })); assert_noop!( - Dispatcher::dispatch_as_treasury_manager(RuntimeOrigin::signed(ALICE), call), + Dispatcher::dispatch_as_treasury(RuntimeOrigin::signed(ALICE), call), DispatchError::BadOrigin ); expect_events(vec![]); diff --git a/pallets/dispatcher/src/weights.rs b/pallets/dispatcher/src/weights.rs index b073d9aaa..035d02bbb 100644 --- a/pallets/dispatcher/src/weights.rs +++ b/pallets/dispatcher/src/weights.rs @@ -48,7 +48,7 @@ use core::marker::PhantomData; /// Weight functions needed for duster. pub trait WeightInfo { - fn dispatch_as_treasury_manager(n: u32) -> Weight; + fn dispatch_as_treasury(n: u32) -> Weight; fn dispatch_as_aave_manager(n: u32) -> Weight; } @@ -56,7 +56,7 @@ pub trait WeightInfo { pub struct HydraWeight(PhantomData); impl WeightInfo for () { /// The range of component `n` is `[1, 10000]`. - fn dispatch_as_treasury_manager(n: u32, ) -> Weight { + fn dispatch_as_treasury(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` diff --git a/runtime/hydradx/src/weights/pallet_dispatcher.rs b/runtime/hydradx/src/weights/pallet_dispatcher.rs index 1884fdeab..309af8633 100644 --- a/runtime/hydradx/src/weights/pallet_dispatcher.rs +++ b/runtime/hydradx/src/weights/pallet_dispatcher.rs @@ -53,7 +53,7 @@ pub struct WeightInfo(PhantomData); pub struct HydraWeight(PhantomData); impl pallet_dispatcher::WeightInfo for HydraWeight { /// The range of component `n` is `[1, 10000]`. - fn dispatch_as_treasury_manager(n: u32, ) -> Weight { + fn dispatch_as_treasury(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` From ee4cc47d927bfa39f9c7503ff9404308fa570bb9 Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 21:52:19 +0100 Subject: [PATCH 14/17] update README --- pallets/dispatcher/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/dispatcher/README.md b/pallets/dispatcher/README.md index e4d95a35a..4c95775fc 100644 --- a/pallets/dispatcher/README.md +++ b/pallets/dispatcher/README.md @@ -3,4 +3,4 @@ This pallet enables specific OpenGov tracks to dispatch Runtime calls as predefi The pallet supports the following dispatchables: * `dispatch_as_treasury` - allows the `Treasury` track to dispatch calls as the Treasury account on Hydration (`7L53bUTBopuwFt3mKUfmkzgGLayYa1Yvn1hAg9v5UMrQzTfh`) -* `dispatch_as_aave_manager` - allows the `AaveManager` track to dispatch calls as the Money Market authority on Hydration (`add addr`) +* `dispatch_as_aave_manager` - allows the `EconomicParameters` track to dispatch calls as the Money Market authority on Hydration (`add addr`) From 43fbb695951286444210896239987d4d2e3caadc Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 21:53:05 +0100 Subject: [PATCH 15/17] versions --- Cargo.lock | 2 +- pallets/omnipool/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 70ef93896..c6994db25 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8798,7 +8798,7 @@ dependencies = [ [[package]] name = "pallet-omnipool" -version = "4.3.7" +version = "4.3.8" dependencies = [ "bitflags 1.3.2", "frame-benchmarking", diff --git a/pallets/omnipool/Cargo.toml b/pallets/omnipool/Cargo.toml index e5cdb43c8..d2de0e299 100644 --- a/pallets/omnipool/Cargo.toml +++ b/pallets/omnipool/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-omnipool" -version = "4.3.7" +version = "4.3.8" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" From 763a7bf12fd045bf3fadfcd6e11d0df63f190c69 Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 22:00:22 +0100 Subject: [PATCH 16/17] weights from reference machine --- pallets/dispatcher/src/weights.rs | 26 +++++++++---------- .../hydradx/src/weights/pallet_dispatcher.rs | 26 +++++++++---------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/pallets/dispatcher/src/weights.rs b/pallets/dispatcher/src/weights.rs index 035d02bbb..3b650ec1e 100644 --- a/pallets/dispatcher/src/weights.rs +++ b/pallets/dispatcher/src/weights.rs @@ -19,9 +19,9 @@ //! Autogenerated weights for `pallet_dispatcher` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-12-29, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-12-29, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `MBP.local`, CPU: `` +//! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -29,13 +29,13 @@ // benchmark // pallet // --chain=dev -// --steps=10 -// --repeat=30 +// --steps=50 +// --repeat=20 // --wasm-execution=compiled // --heap-pages=4096 // --template=scripts/pallet-weight-template.hbs // --pallet=pallet-dispatcher -// --output=weights.rs +// --output=dispatcher.rs // --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] @@ -60,19 +60,19 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_000_000 picoseconds. - Weight::from_parts(7_765_739, 0) - // Standard Error: 13 - .saturating_add(Weight::from_parts(1_305, 0).saturating_mul(n.into())) + // Minimum execution time: 11_248_000 picoseconds. + Weight::from_parts(11_516_144, 0) + // Standard Error: 6 + .saturating_add(Weight::from_parts(1_244, 0).saturating_mul(n.into())) } /// The range of component `n` is `[1, 10000]`. fn dispatch_as_aave_manager(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_000_000 picoseconds. - Weight::from_parts(9_277_359, 0) - // Standard Error: 52 - .saturating_add(Weight::from_parts(1_049, 0).saturating_mul(n.into())) + // Minimum execution time: 10_893_000 picoseconds. + Weight::from_parts(11_148_990, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(1_246, 0).saturating_mul(n.into())) } } diff --git a/runtime/hydradx/src/weights/pallet_dispatcher.rs b/runtime/hydradx/src/weights/pallet_dispatcher.rs index 309af8633..cb9563e5f 100644 --- a/runtime/hydradx/src/weights/pallet_dispatcher.rs +++ b/runtime/hydradx/src/weights/pallet_dispatcher.rs @@ -19,9 +19,9 @@ //! Autogenerated weights for `pallet_dispatcher` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-12-29, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-12-29, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `MBP.local`, CPU: `` +//! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -29,13 +29,13 @@ // benchmark // pallet // --chain=dev -// --steps=10 -// --repeat=30 +// --steps=50 +// --repeat=20 // --wasm-execution=compiled // --heap-pages=4096 // --template=scripts/pallet-weight-template.hbs // --pallet=pallet-dispatcher -// --output=weights.rs +// --output=dispatcher.rs // --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] @@ -57,19 +57,19 @@ impl pallet_dispatcher::WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_000_000 picoseconds. - Weight::from_parts(7_765_739, 0) - // Standard Error: 13 - .saturating_add(Weight::from_parts(1_305, 0).saturating_mul(n.into())) + // Minimum execution time: 11_248_000 picoseconds. + Weight::from_parts(11_516_144, 0) + // Standard Error: 6 + .saturating_add(Weight::from_parts(1_244, 0).saturating_mul(n.into())) } /// The range of component `n` is `[1, 10000]`. fn dispatch_as_aave_manager(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_000_000 picoseconds. - Weight::from_parts(9_277_359, 0) - // Standard Error: 52 - .saturating_add(Weight::from_parts(1_049, 0).saturating_mul(n.into())) + // Minimum execution time: 10_893_000 picoseconds. + Weight::from_parts(11_148_990, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(1_246, 0).saturating_mul(n.into())) } } From bb4d491606de1db5238ec9cb2c57abf7999ab02a Mon Sep 17 00:00:00 2001 From: vgantchev Date: Sun, 29 Dec 2024 22:01:54 +0100 Subject: [PATCH 17/17] update code docs --- pallets/dispatcher/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/dispatcher/src/lib.rs b/pallets/dispatcher/src/lib.rs index ce2b84398..e2a6cbdff 100644 --- a/pallets/dispatcher/src/lib.rs +++ b/pallets/dispatcher/src/lib.rs @@ -156,7 +156,7 @@ pub mod pallet { impl Pallet { /// Dispatch the call from the specified account as Signed Origin. /// - /// Return the call actual weight of the dispatched call if there is some. + /// Return the result and the actual weight of the dispatched call if there is some. fn do_dispatch( account: T::AccountId, call: ::RuntimeCall,