diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index 53797d8cfc1dc..d840d45a7f430 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -15,14 +15,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! # Sudo Module +//! # Sudo Pallet //! //! - [`Config`] //! - [`Call`] //! //! ## Overview //! -//! The Sudo module allows for a single account (called the "sudo key") +//! The Sudo pallet allows for a single account (called the "sudo key") //! to execute dispatchable functions that require a `Root` call //! or designate a new account to replace them as the sudo key. //! Only one account can be the sudo key at a time. @@ -31,7 +31,7 @@ //! //! ### Dispatchable Functions //! -//! Only the sudo key can call the dispatchable functions from the Sudo module. +//! Only the sudo key can call the dispatchable functions from the Sudo pallet. //! //! * `sudo` - Make a `Root` call to a dispatchable function. //! * `set_key` - Assign a new account to be the sudo key. @@ -40,8 +40,8 @@ //! //! ### Executing Privileged Functions //! -//! The Sudo module itself is not intended to be used within other modules. -//! Instead, you can build "privileged functions" (i.e. functions that require `Root` origin) in other modules. +//! The Sudo pallet itself is not intended to be used within other pallets. +//! Instead, you can build "privileged functions" (i.e. functions that require `Root` origin) in other pallets. //! You can execute these privileged functions by calling `sudo` with the sudo key account. //! Privileged functions cannot be directly executed via an extrinsic. //! @@ -49,35 +49,46 @@ //! //! ### Simple Code Snippet //! -//! This is an example of a module that exposes a privileged function: +//! This is an example of a pallet that exposes a privileged function: //! //! ``` -//! use frame_support::{decl_module, dispatch}; -//! use frame_system::ensure_root; //! -//! pub trait Config: frame_system::Config {} +//! #[frame_support::pallet] +//! pub mod logger { +//! use frame_support::pallet_prelude::*; +//! use frame_system::pallet_prelude::*; +//! use super::*; //! -//! decl_module! { -//! pub struct Module for enum Call where origin: T::Origin { -//! #[weight = 0] -//! pub fn privileged_function(origin) -> dispatch::DispatchResult { +//! #[pallet::config] +//! pub trait Config: frame_system::Config {} +//! +//! #[pallet::pallet] +//! pub struct Pallet(PhantomData); +//! +//! #[pallet::hooks] +//! impl Hooks> for Pallet {} +//! +//! #[pallet::call] +//! impl Pallet { +//! #[pallet::weight(0)] +//! pub fn privileged_function(origin: OriginFor) -> DispatchResultWithPostInfo { //! ensure_root(origin)?; //! //! // do something... //! -//! Ok(()) +//! Ok(().into()) //! } -//! } +//! } //! } //! # fn main() {} //! ``` //! //! ## Genesis Config //! -//! The Sudo module depends on the [`GenesisConfig`](./struct.GenesisConfig.html). +//! The Sudo pallet depends on the [`GenesisConfig`]. //! You need to set an initial superuser account as the sudo `key`. //! -//! ## Related Modules +//! ## Related Pallets //! //! * [Democracy](../pallet_democracy/index.html) //! @@ -89,35 +100,41 @@ use sp_std::prelude::*; use sp_runtime::{DispatchResult, traits::StaticLookup}; use frame_support::{ - Parameter, decl_module, decl_event, decl_storage, decl_error, ensure, + weights::GetDispatchInfo, + traits::UnfilteredDispatchable, }; -use frame_support::{ - weights::{Weight, GetDispatchInfo, Pays}, - traits::{UnfilteredDispatchable, Get}, - dispatch::DispatchResultWithPostInfo, -}; -use frame_system::ensure_signed; #[cfg(test)] mod mock; #[cfg(test)] mod tests; -pub trait Config: frame_system::Config { - /// The overarching event type. - type Event: From> + Into<::Event>; +pub use pallet::*; - /// A sudo-able call. - type Call: Parameter + UnfilteredDispatchable + GetDispatchInfo; -} +#[frame_support::pallet] +pub mod pallet { + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + use super::{*, DispatchResult}; -decl_module! { - /// Sudo module declaration. - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type Event: From> + IsType<::Event>; - fn deposit_event() = default; + /// A sudo-able call. + type Call: Parameter + UnfilteredDispatchable + GetDispatchInfo; + } + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData); + + #[pallet::hooks] + impl Hooks> for Pallet {} + + #[pallet::call] + impl Pallet { /// Authenticates the sudo key and dispatches a function call with `Root` origin. /// /// The dispatch origin for this call must be _Signed_. @@ -128,17 +145,20 @@ decl_module! { /// - One DB write (event). /// - Weight of derivative `call` execution + 10,000. /// # - #[weight = { + #[pallet::weight({ let dispatch_info = call.get_dispatch_info(); (dispatch_info.weight.saturating_add(10_000), dispatch_info.class) - }] - fn sudo(origin, call: Box<::Call>) -> DispatchResultWithPostInfo { + })] + pub(crate) fn sudo( + origin: OriginFor, + call: Box<::Call>, + ) -> DispatchResultWithPostInfo { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; ensure!(sender == Self::key(), Error::::RequireSudo); let res = call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()); - Self::deposit_event(RawEvent::Sudid(res.map(|_| ()).map_err(|e| e.error))); + Self::deposit_event(Event::Sudid(res.map(|_| ()).map_err(|e| e.error))); // Sudo user does not pay a fee. Ok(Pays::No.into()) } @@ -153,14 +173,18 @@ decl_module! { /// - O(1). /// - The weight of this call is defined by the caller. /// # - #[weight = (*_weight, call.get_dispatch_info().class)] - fn sudo_unchecked_weight(origin, call: Box<::Call>, _weight: Weight) -> DispatchResultWithPostInfo { + #[pallet::weight((*_weight, call.get_dispatch_info().class))] + pub(crate) fn sudo_unchecked_weight( + origin: OriginFor, + call: Box<::Call>, + _weight: Weight, + ) -> DispatchResultWithPostInfo { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; ensure!(sender == Self::key(), Error::::RequireSudo); let res = call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()); - Self::deposit_event(RawEvent::Sudid(res.map(|_| ()).map_err(|e| e.error))); + Self::deposit_event(Event::Sudid(res.map(|_| ()).map_err(|e| e.error))); // Sudo user does not pay a fee. Ok(Pays::No.into()) } @@ -174,14 +198,17 @@ decl_module! { /// - Limited storage reads. /// - One DB change. /// # - #[weight = 0] - fn set_key(origin, new: ::Source) -> DispatchResultWithPostInfo { + #[pallet::weight(0)] + pub(crate) fn set_key( + origin: OriginFor, + new: ::Source, + ) -> DispatchResultWithPostInfo { // This is a public call, so we ensure that the origin is some signed account. let sender = ensure_signed(origin)?; ensure!(sender == Self::key(), Error::::RequireSudo); let new = T::Lookup::lookup(new)?; - Self::deposit_event(RawEvent::KeyChanged(Self::key())); + Self::deposit_event(Event::KeyChanged(Self::key())); >::put(new); // Sudo user does not pay a fee. Ok(Pays::No.into()) @@ -198,7 +225,7 @@ decl_module! { /// - One DB write (event). /// - Weight of derivative `call` execution + 10,000. /// # - #[weight = { + #[pallet::weight({ let dispatch_info = call.get_dispatch_info(); ( dispatch_info.weight @@ -207,8 +234,9 @@ decl_module! { .saturating_add(T::DbWeight::get().reads_writes(1, 1)), dispatch_info.class, ) - }] - fn sudo_as(origin, + })] + pub(crate) fn sudo_as( + origin: OriginFor, who: ::Source, call: Box<::Call> ) -> DispatchResultWithPostInfo { @@ -220,35 +248,55 @@ decl_module! { let res = call.dispatch_bypass_filter(frame_system::RawOrigin::Signed(who).into()); - Self::deposit_event(RawEvent::SudoAsDone(res.map(|_| ()).map_err(|e| e.error))); + Self::deposit_event(Event::SudoAsDone(res.map(|_| ()).map_err(|e| e.error))); // Sudo user does not pay a fee. Ok(Pays::No.into()) } } -} -decl_event!( - pub enum Event where AccountId = ::AccountId { + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + #[pallet::metadata(T::AccountId = "AccountId")] + pub enum Event { /// A sudo just took place. \[result\] Sudid(DispatchResult), /// The \[sudoer\] just switched identity; the old key is supplied. - KeyChanged(AccountId), + KeyChanged(T::AccountId), /// A sudo just took place. \[result\] SudoAsDone(DispatchResult), } -); -decl_storage! { - trait Store for Module as Sudo { + #[pallet::error] + /// Error for the Sudo pallet + pub enum Error { + /// Sender must be the Sudo account + RequireSudo, + } + + /// The `AccountId` of the sudo key. + #[pallet::storage] + #[pallet::getter(fn key)] + pub(super) type Key = StorageValue<_, T::AccountId, ValueQuery>; + + #[pallet::genesis_config] + pub struct GenesisConfig { /// The `AccountId` of the sudo key. - Key get(fn key) config(): T::AccountId; + pub key: T::AccountId, } -} -decl_error! { - /// Error for the Sudo module - pub enum Error for Module { - /// Sender must be the Sudo account - RequireSudo, + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + key: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + >::put(&self.key); + } } } diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index cd242d491dae2..9aac0a129907f 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -18,7 +18,7 @@ //! Test utilities use super::*; -use frame_support::{parameter_types, weights::Weight}; +use frame_support::{parameter_types, traits::GenesisBuild}; use sp_core::H256; use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; use sp_io; @@ -27,52 +27,80 @@ use frame_support::traits::Filter; use frame_system::limits; // Logger module to track execution. +#[frame_support::pallet] pub mod logger { + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; use super::*; - use frame_system::ensure_root; + #[pallet::config] pub trait Config: frame_system::Config { - type Event: From> + Into<::Event>; + type Event: From> + IsType<::Event>; } - decl_storage! { - trait Store for Module as Logger { - AccountLog get(fn account_log): Vec; - I32Log get(fn i32_log): Vec; + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData); + + #[pallet::hooks] + impl Hooks> for Pallet {} + + #[pallet::call] + impl Pallet { + #[pallet::weight(*weight)] + pub(crate) fn privileged_i32_log( + origin: OriginFor, + i: i32, + weight: Weight + ) -> DispatchResultWithPostInfo { + // Ensure that the `origin` is `Root`. + ensure_root(origin)?; + >::append(i); + Self::deposit_event(Event::AppendI32(i, weight)); + Ok(().into()) } - } - decl_event! { - pub enum Event where AccountId = ::AccountId { - AppendI32(i32, Weight), - AppendI32AndAccount(AccountId, i32, Weight), + #[pallet::weight(*weight)] + pub(crate) fn non_privileged_log( + origin: OriginFor, + i: i32, + weight: Weight + ) -> DispatchResultWithPostInfo { + // Ensure that the `origin` is some signed account. + let sender = ensure_signed(origin)?; + >::append(i); + >::append(sender.clone()); + Self::deposit_event(Event::AppendI32AndAccount(sender, i, weight)); + Ok(().into()) } } - decl_module! { - pub struct Module for enum Call where origin: ::Origin { - fn deposit_event() = default; - - #[weight = *weight] - fn privileged_i32_log(origin, i: i32, weight: Weight){ - // Ensure that the `origin` is `Root`. - ensure_root(origin)?; - ::append(i); - Self::deposit_event(RawEvent::AppendI32(i, weight)); - } - - #[weight = *weight] - fn non_privileged_log(origin, i: i32, weight: Weight){ - // Ensure that the `origin` is some signed account. - let sender = ensure_signed(origin)?; - ::append(i); - >::append(sender.clone()); - Self::deposit_event(RawEvent::AppendI32AndAccount(sender, i, weight)); - } - } + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + #[pallet::metadata(T::AccountId = "AccountId")] + pub enum Event { + AppendI32(i32, Weight), + AppendI32AndAccount(T::AccountId, i32, Weight), } + + #[pallet::storage] + #[pallet::getter(fn account_log)] + pub(super) type AccountLog = StorageValue< + _, + Vec, + ValueQuery + >; + + #[pallet::storage] + #[pallet::getter(fn i32_log)] + pub(super) type I32Log = StorageValue< + _, + Vec, + ValueQuery + >; } + type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; diff --git a/frame/sudo/src/tests.rs b/frame/sudo/src/tests.rs index 4d2552b7b88b4..780e07676b29c 100644 --- a/frame/sudo/src/tests.rs +++ b/frame/sudo/src/tests.rs @@ -58,7 +58,7 @@ fn sudo_emits_events_correctly() { // Should emit event to indicate success when called with the root `key` and `call` is `Ok`. let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1))); assert_ok!(Sudo::sudo(Origin::signed(1), call)); - let expected_event = TestEvent::sudo(RawEvent::Sudid(Ok(()))); + let expected_event = TestEvent::sudo(Event::Sudid(Ok(()))); assert!(System::events().iter().any(|a| a.event == expected_event)); }) } @@ -97,7 +97,7 @@ fn sudo_unchecked_weight_emits_events_correctly() { // Should emit event to indicate success when called with the root `key` and `call` is `Ok`. let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1))); assert_ok!(Sudo::sudo_unchecked_weight(Origin::signed(1), call, 1_000)); - let expected_event = TestEvent::sudo(RawEvent::Sudid(Ok(()))); + let expected_event = TestEvent::sudo(Event::Sudid(Ok(()))); assert!(System::events().iter().any(|a| a.event == expected_event)); }) } @@ -124,11 +124,11 @@ fn set_key_emits_events_correctly() { // A root `key` can change the root `key`. assert_ok!(Sudo::set_key(Origin::signed(1), 2)); - let expected_event = TestEvent::sudo(RawEvent::KeyChanged(1)); + let expected_event = TestEvent::sudo(Event::KeyChanged(1)); assert!(System::events().iter().any(|a| a.event == expected_event)); // Double check. assert_ok!(Sudo::set_key(Origin::signed(2), 4)); - let expected_event = TestEvent::sudo(RawEvent::KeyChanged(2)); + let expected_event = TestEvent::sudo(Event::KeyChanged(2)); assert!(System::events().iter().any(|a| a.event == expected_event)); }); } @@ -164,7 +164,7 @@ fn sudo_as_emits_events_correctly() { // A non-privileged function will work when passed to `sudo_as` with the root `key`. let call = Box::new(Call::Logger(LoggerCall::non_privileged_log(42, 1))); assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call)); - let expected_event = TestEvent::sudo(RawEvent::SudoAsDone(Ok(()))); + let expected_event = TestEvent::sudo(Event::SudoAsDone(Ok(()))); assert!(System::events().iter().any(|a| a.event == expected_event)); }); } diff --git a/frame/support/procedural/src/pallet/expand/call.rs b/frame/support/procedural/src/pallet/expand/call.rs index 27288a003785e..301d3fc5d9fa8 100644 --- a/frame/support/procedural/src/pallet/expand/call.rs +++ b/frame/support/procedural/src/pallet/expand/call.rs @@ -186,6 +186,7 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { impl<#type_impl_gen> #pallet_ident<#type_use_gen> #where_clause { #[doc(hidden)] + #[allow(dead_code)] pub fn call_functions() -> &'static [#frame_support::dispatch::FunctionMetadata] { &[ #( #frame_support::dispatch::FunctionMetadata {