1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// This file is part of Substrate.

// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
// 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.

//! # SudoOrigin Pallet
//!
//! - [`Config`]
//! - [`Call`]
//! - [`SudoOrigin`]
//!
//! ## Overview
//!
//! The SudoOrigin pallet allows for an origin
//! to execute dispatchable functions that require a `Root` call.
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! Only the sudo origin can call the dispatchable functions from the SudoOrigin pallet.
//!
//! * `sudo` - Make a `Root` call to a dispatchable function.
//!
//! ## Usage
//!
//! ### Executing Privileged Functions
//!
//! The SudoOrigin pallet is intended to be used with the Council. The council can use this pallet to make `Root` calls
//! 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 origin.
//! Privileged functions cannot be directly executed via an extrinsic.
//!
//! Learn more about privileged functions and `Root` origin in the [`Origin`] type documentation.
//!
//! ### Simple Code Snippet
//!
//! This is an example of a pallet that exposes a privileged function:
//!
//! ```
//!
//! #[frame_support::pallet]
//! pub mod logger {
//! 	use frame_support::pallet_prelude::*;
//! 	use frame_system::pallet_prelude::*;
//! 	use super::*;
//!
//! 	#[pallet::config]
//! 	pub trait Config: frame_system::Config {}
//!
//! 	#[pallet::pallet]
//! 	pub struct Pallet<T>(PhantomData<T>);
//!
//! 	#[pallet::call]
//! 	impl<T: Config> Pallet<T> {
//! 		#[pallet::weight(0)]
//!         pub fn privileged_function(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
//!             ensure_root(origin)?;
//!
//!             // do something...
//!
//!             Ok(().into())
//!         }
//! 	}
//! }
//! # fn main() {}
//! ```
//!
//! ## Genesis Config
//!
//! The SudoOrigin pallet depends on the runtiem config.
//!
//! ## Related Pallets
//!
//! * Collective
//!
//! [`Origin`]: https://docs.substrate.io/v3/runtime/origins

#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::{dispatch::GetDispatchInfo, traits::UnfilteredDispatchable};
use sp_runtime::{traits::StaticLookup, DispatchResult};
use sp_std::{convert::TryInto, prelude::*};

#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;

pub(crate) const LOG_TARGET: &'static str = "sudo-origin";
pub(crate) const ALERT_STRING: &'static str = "ALERT!ALERT!ALERT!";

// syntactic sugar for logging.
#[macro_export]
macro_rules! alert_log {
	($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
		log::$level!(
			target: crate::LOG_TARGET,
			concat!("[{:?}] {:?} ", $patter), <frame_system::Pallet<T>>::block_number(), crate::ALERT_STRING $(, $values)*
		)
	};
}

pub use pallet::*;

#[frame_support::pallet]
pub mod pallet {
	use super::{DispatchResult, *};
	use frame_support::pallet_prelude::*;
	use frame_system::pallet_prelude::*;

	#[pallet::config]
	pub trait Config: frame_system::Config {
		/// The overarching event type.
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

		/// A sudo-able call.
		type RuntimeCall: Parameter
			+ UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin>
			+ GetDispatchInfo;

		/// The Origin allowed to use sudo
		type SudoOrigin: EnsureOrigin<Self::RuntimeOrigin>;
	}

	#[pallet::pallet]
	pub struct Pallet<T>(PhantomData<T>);

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// Authenticates the SudoOrigin and dispatches a function call with `Root` origin.
		///
		/// # <weight>
		/// - O(1).
		/// - Limited storage reads.
		/// - One DB write (event).
		/// - Weight of derivative `call` execution + 10,000.
		/// # </weight>
		#[pallet::call_index(0)]
		#[pallet::weight({
			let dispatch_info = call.get_dispatch_info();
			(dispatch_info.weight.saturating_add(Weight::from_parts(10_000, 0)), dispatch_info.class)
		})]
		pub fn sudo(
			origin: OriginFor<T>,
			call: Box<<T as Config>::RuntimeCall>,
		) -> DispatchResultWithPostInfo {
			// This is a public call, so we ensure that the origin is SudoOrigin.
			T::SudoOrigin::ensure_origin(origin)?;

			let res = call.clone().dispatch_bypass_filter(frame_system::RawOrigin::Root.into());
			Self::deposit_event(Event::SuOriginDid(res.clone().map(|_| ()).map_err(|e| e.error)));
			alert_log!(info, "A sudo action was performed: Call - {:?}, Result - {:?}!", call, res);
			// Sudo user does not pay a fee.
			Ok(Pays::No.into())
		}

		/// Authenticates the SudoOrigin and dispatches a function call with `Root` origin.
		/// This function does not check the weight of the call, and instead allows the
		/// SudoOrigin to specify the weight of the call.
		///
		/// # <weight>
		/// - O(1).
		/// - The weight of this call is defined by the caller.
		/// # </weight>
		#[pallet::call_index(1)]
		#[pallet::weight((*_weight, call.get_dispatch_info().class))]
		pub fn sudo_unchecked_weight(
			origin: OriginFor<T>,
			call: Box<<T as Config>::RuntimeCall>,
			_weight: Weight,
		) -> DispatchResultWithPostInfo {
			// This is a public call, so we ensure that the origin is SudoOrigin.
			T::SudoOrigin::ensure_origin(origin)?;

			let res = call.clone().dispatch_bypass_filter(frame_system::RawOrigin::Root.into());
			Self::deposit_event(Event::SuOriginDid(res.clone().map(|_| ()).map_err(|e| e.error)));
			alert_log!(
				info,
				"A sudo action was performed with unchecked weight: Call - {:?}, Result - {:?}!",
				call,
				res
			);
			// Sudo user does not pay a fee.
			Ok(Pays::No.into())
		}

		/// Authenticates the SudoOrigin and dispatches a function call with `Signed` origin from
		/// a given account.
		///
		/// # <weight>
		/// - O(1).
		/// - Limited storage reads.
		/// - One DB write (event).
		/// - Weight of derivative `call` execution + 10,000.
		/// # </weight>
		#[pallet::call_index(2)]
		#[pallet::weight({
			let dispatch_info = call.get_dispatch_info();
			(
				dispatch_info.weight
					.saturating_add(Weight::from_parts(10_000, 0))
					// AccountData for inner call origin accountdata.
					.saturating_add(T::DbWeight::get().reads_writes(1, 1)),
				dispatch_info.class,
			)
		})]
		pub fn sudo_as(
			origin: OriginFor<T>,
			who: <T::Lookup as StaticLookup>::Source,
			call: Box<<T as Config>::RuntimeCall>,
		) -> DispatchResultWithPostInfo {
			// This is a public call, so we ensure that the origin is SudoOrigin.
			T::SudoOrigin::ensure_origin(origin)?;

			let who = T::Lookup::lookup(who)?;

			let res = call
				.clone()
				.dispatch_bypass_filter(frame_system::RawOrigin::Signed(who.clone()).into());

			Self::deposit_event(Event::SuOriginDoAsDone(
				res.clone().map(|_| ()).map_err(|e| e.error),
			));
			alert_log!(
				info,
				"A sudo_as action was performed: Who - {:?}, Call - {:?}, Result - {:?}!",
				who,
				call,
				res
			);
			// Sudo user does not pay a fee.
			Ok(Pays::No.into())
		}
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
	pub enum Event<T: Config> {
		/// A sudo just took place. \[result\]
		SuOriginDid(DispatchResult),
		/// A sudo just took place. \[result\]
		SuOriginDoAsDone(DispatchResult),
	}

	#[pallet::error]
	/// Error for the Sudo pallet
	pub enum Error<T> {}
}