Introduce Polkadot-Sdk developer_hub (#2102)

This PR introduces the new crate `developer_hub` into the polkadot-sdk
repo. The vision for the developer-hub crate is detailed in [this
document](https://docs.google.com/document/d/1XLLkFNE8v8HLvZpI2rzsa8N2IN1FcKntc8q-Sc4xBAk/edit?usp=sharing).

<img width="1128" alt="Screenshot 2023-11-02 at 10 45 48"
src="https://github.com/paritytech/polkadot-sdk/assets/5588131/1e12b60f-fef5-42c4-8503-a3ba234077c3">


Other than adding the new crate, it also does the following: 

* Remove the `substrate` crate, as there is now a unique umbrella crate
for multiple things in `developer_hub::polkadot_sdk`.
* (backport candidate) A minor change to `frame-support` macros that
allows `T::RuntimeOrigin` to also be acceptable as the origin type.
* (backport candidate) A minor change to `frame-system` that allows us
to deposit events at genesis because now the real genesis config is
generated via wasm, and we can safely assume `cfg!(feature = "std")`
means only testing. related to #62.
* (backport candidate) Introduces a small `read_events_for_pallet` to
`frame_system` for easier event reading in tests.
* From https://github.com/paritytech/polkadot-sdk-docs/issues/31, it
takes action on improving the `pallet::call` docs.
* From https://github.com/paritytech/polkadot-sdk-docs/issues/31, it
takes action on improving the `UncheckedExtrinsic` docs.

## Way Forward

First, a version of this is deployed temporarily
[here](https://blog.kianenigma.nl/polkadot-sdk/developer_hub/index.html).
I will keep it up to date on a daily basis.

### This Pull Request

I see two ways forward: 

1. We acknowledge that everything in `developer-hub` is going to be WIP,
and merge this asap. We should not yet use links to this crate anywhere.
2. We make this be the feature branch, make PRs against this, and either
gradually backport it, or only merge to master once it is done.

I am personally in favor of option 1. If we stick to option 2, we need a
better way to deploy a staging version of this to gh-pages.

### Issue Tracking

The main issues related to the future of `developer_hub` are: 

- https://github.com/paritytech/polkadot-sdk-docs/issues/31
- https://github.com/paritytech/polkadot-sdk-docs/issues/4
- https://github.com/paritytech/polkadot-sdk-docs/issues/26 
- https://github.com/paritytech/polkadot-sdk-docs/issues/32
- https://github.com/paritytech/polkadot-sdk-docs/issues/36


### After This Pull Request

- [ ] create a redirect for
https://paritytech.github.io/polkadot-sdk/master/substrate/
- [x] analytics 
- [ ] link checker
- [ ] the matter of publishing, and how all of these relative links for
when we do, that is still an open question. There is section on this in
the landing page.
- [ ] updated https://paritytech.github.io/

---------

Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
Co-authored-by: Juan Girini <juangirini@gmail.com>
Co-authored-by: bader y <ibnbassem@gmail.com>
Co-authored-by: Sebastian Kunert <skunert49@gmail.com>
Co-authored-by: James Wilson <james@jsdw.me>
Co-authored-by: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com>
This commit is contained in:
Kian Paimani
2023-11-30 14:15:46 +03:00
committed by GitHub
parent 180a6ad9b0
commit eaf1bc5633
96 changed files with 3409 additions and 470 deletions
+23 -25
View File
@@ -49,8 +49,7 @@
//! - **Total Issuance:** The total number of units in existence in a system.
//!
//! - **Reaping an account:** The act of removing an account by resetting its nonce. Happens after
//! its
//! total balance has become zero (or, strictly speaking, less than the Existential Deposit).
//! its total balance has become zero (or, strictly speaking, less than the Existential Deposit).
//!
//! - **Free Balance:** The portion of a balance that is not reserved. The free balance is the only
//! balance that matters for most operations.
@@ -59,24 +58,23 @@
//! Reserved balance can still be slashed, but only after all the free balance has been slashed.
//!
//! - **Imbalance:** A condition when some funds were credited or debited without equal and opposite
//! accounting
//! (i.e. a difference between total issuance and account balances). Functions that result in an
//! imbalance will return an object of the `Imbalance` trait that can be managed within your runtime
//! logic. (If an imbalance is simply dropped, it should automatically maintain any book-keeping
//! such as total issuance.)
//! accounting (i.e. a difference between total issuance and account balances). Functions that
//! result in an imbalance will return an object of the `Imbalance` trait that can be managed within
//! your runtime logic. (If an imbalance is simply dropped, it should automatically maintain any
//! book-keeping such as total issuance.)
//!
//! - **Lock:** A freeze on a specified amount of an account's free balance until a specified block
//! number. Multiple
//! locks always operate over the same funds, so they "overlay" rather than "stack".
//! number. Multiple locks always operate over the same funds, so they "overlay" rather than
//! "stack".
//!
//! ### Implementations
//!
//! The Balances pallet provides implementations for the following traits. If these traits provide
//! the functionality that you need, then you can avoid coupling with the Balances pallet.
//!
//! - [`Currency`](frame_support::traits::Currency): Functions for dealing with a
//! - [`Currency`]: Functions for dealing with a
//! fungible assets system.
//! - [`ReservableCurrency`](frame_support::traits::ReservableCurrency):
//! - [`ReservableCurrency`]
//! - [`NamedReservableCurrency`](frame_support::traits::NamedReservableCurrency):
//! Functions for dealing with assets that can be reserved from an account.
//! - [`LockableCurrency`](frame_support::traits::LockableCurrency): Functions for
@@ -105,7 +103,7 @@
//! ```
//! use frame_support::traits::Currency;
//! # pub trait Config: frame_system::Config {
//! # type Currency: Currency<Self::AccountId>;
//! # type Currency: Currency<Self::AccountId>;
//! # }
//!
//! pub type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
@@ -120,26 +118,26 @@
//! use frame_support::traits::{WithdrawReasons, LockableCurrency};
//! use sp_runtime::traits::Bounded;
//! pub trait Config: frame_system::Config {
//! type Currency: LockableCurrency<Self::AccountId, Moment=frame_system::pallet_prelude::BlockNumberFor<Self>>;
//! type Currency: LockableCurrency<Self::AccountId, Moment=frame_system::pallet_prelude::BlockNumberFor<Self>>;
//! }
//! # struct StakingLedger<T: Config> {
//! # stash: <T as frame_system::Config>::AccountId,
//! # total: <<T as Config>::Currency as frame_support::traits::Currency<<T as frame_system::Config>::AccountId>>::Balance,
//! # phantom: std::marker::PhantomData<T>,
//! # stash: <T as frame_system::Config>::AccountId,
//! # total: <<T as Config>::Currency as frame_support::traits::Currency<<T as frame_system::Config>::AccountId>>::Balance,
//! # phantom: std::marker::PhantomData<T>,
//! # }
//! # const STAKING_ID: [u8; 8] = *b"staking ";
//!
//! fn update_ledger<T: Config>(
//! controller: &T::AccountId,
//! ledger: &StakingLedger<T>
//! controller: &T::AccountId,
//! ledger: &StakingLedger<T>
//! ) {
//! T::Currency::set_lock(
//! STAKING_ID,
//! &ledger.stash,
//! ledger.total,
//! WithdrawReasons::all()
//! );
//! // <Ledger<T>>::insert(controller, ledger); // Commented out as we don't have access to Staking's storage here.
//! T::Currency::set_lock(
//! STAKING_ID,
//! &ledger.stash,
//! ledger.total,
//! WithdrawReasons::all()
//! );
//! // <Ledger<T>>::insert(controller, ledger); // Commented out as we don't have access to Staking's storage here.
//! }
//! # fn main() {}
//! ```
@@ -110,7 +110,7 @@ pub fn migrate<
}
/// Some checks prior to migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::pre_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn pre_migration<T: pallet_bounties::Config, P: GetStorageVersion + 'static, N: AsRef<str>>(
@@ -164,7 +164,7 @@ pub fn pre_migration<T: pallet_bounties::Config, P: GetStorageVersion + 'static,
}
/// Some checks for after migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn post_migration<T: pallet_bounties::Config, P: GetStorageVersion, N: AsRef<str>>(
@@ -76,7 +76,7 @@ pub fn migrate<T: frame_system::Config, P: GetStorageVersion + PalletInfoAccess,
}
/// Some checks prior to migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::pre_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn pre_migrate<P: GetStorageVersion + PalletInfoAccess, N: AsRef<str>>(old_pallet_name: N) {
@@ -104,7 +104,7 @@ pub fn pre_migrate<P: GetStorageVersion + PalletInfoAccess, N: AsRef<str>>(old_p
}
/// Some checks for after migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn post_migrate<P: GetStorageVersion + PalletInfoAccess, N: AsRef<str>>(old_pallet_name: N) {
@@ -80,11 +80,7 @@ frame_election_provider_support::generate_solution_type!(
/// All events of this pallet.
pub(crate) fn multi_phase_events() -> Vec<super::Event<Runtime>> {
System::events()
.into_iter()
.map(|r| r.event)
.filter_map(|e| if let RuntimeEvent::MultiPhase(inner) = e { Some(inner) } else { None })
.collect::<Vec<_>>()
System::read_events_for_pallet::<super::Event<Runtime>>()
}
/// To from `now` to block `n`.
@@ -69,7 +69,7 @@ pub fn migrate<T: crate::Config, N: AsRef<str>>(new_pallet_name: N) -> Weight {
}
/// Some checks prior to migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::pre_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn pre_migration<T: crate::Config, N: AsRef<str>>(new: N) {
@@ -97,7 +97,7 @@ pub fn pre_migration<T: crate::Config, N: AsRef<str>>(new: N) {
}
/// Some checks for after migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn post_migration<T: crate::Config>() {
@@ -71,7 +71,7 @@ pub fn pre_migrate_fn<T: Config>(to_migrate: Vec<T::AccountId>) -> Box<dyn Fn()
}
/// Some checks for after migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn post_migrate<T: crate::Config>() {
@@ -292,9 +292,8 @@ pub mod pallet {
}
}
/// Allows you to define an enum on the pallet which will then instruct
/// `construct_runtime` to amalgamate all similarly-named enums from other
/// pallets into an aggregate enum.
/// Allows you to define an enum on the pallet which will then instruct `construct_runtime` to
/// amalgamate all similarly-named enums from other pallets into an aggregate enum.
#[pallet::composite_enum]
pub enum HoldReason {
Staking,
@@ -39,6 +39,7 @@ impl<T: Config> frame_support::traits::Get<u32> for MaxChecking<T> {
}
}
#[docify::export]
pub(crate) type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
/// An unstake request.
+2 -2
View File
@@ -63,7 +63,7 @@ pub fn migrate<T: crate::Config, N: AsRef<str>>(new_pallet_name: N) -> Weight {
}
/// Some checks prior to migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::pre_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn pre_migration<T: crate::Config, N: AsRef<str>>(new: N) {
@@ -99,7 +99,7 @@ pub fn pre_migration<T: crate::Config, N: AsRef<str>>(new: N) {
}
/// Some checks for after migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn post_migration() {
@@ -77,7 +77,7 @@ pub fn migrate<T: frame_system::Config, P: GetStorageVersion + PalletInfoAccess,
}
/// Some checks prior to migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::pre_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn pre_migrate<P: GetStorageVersion, N: AsRef<str>>(old_pallet_name: N, new_pallet_name: N) {
@@ -105,7 +105,7 @@ pub fn pre_migrate<P: GetStorageVersion, N: AsRef<str>>(old_pallet_name: N, new_
}
/// Some checks for after migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn post_migrate<P: GetStorageVersion, N: AsRef<str>>(old_pallet_name: N, new_pallet_name: N) {
@@ -17,13 +17,11 @@
//! Off-chain logic for creating a proof based data provided by on-chain logic.
//!
//! Validator-set extracting an iterator from an off-chain worker stored list containing
//! historical validator-sets.
//! Based on the logic of historical slashing, but the validation is done off-chain.
//! Validator-set extracting an iterator from an off-chain worker stored list containing historical
//! validator-sets. Based on the logic of historical slashing, but the validation is done off-chain.
//! Use [`fn store_current_session_validator_set_to_offchain()`](super::onchain) to store the
//! required data to the offchain validator set.
//! This is used in conjunction with [`ProvingTrie`](super::ProvingTrie) and
//! the off-chain indexing API.
//! required data to the offchain validator set. This is used in conjunction with [`ProvingTrie`]
//! and the off-chain indexing API.
use sp_runtime::{
offchain::storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
+23 -13
View File
@@ -15,10 +15,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//! > Made for [![polkadot]](https://polkadot.network)
//!
//! [polkadot]: https://img.shields.io/badge/polkadot-E6007A?style=for-the-badge&logo=polkadot&logoColor=white
//!
//! # FRAME
//!
//! ```no_compile
@@ -34,14 +30,21 @@
//! > **F**ramework for **R**untime **A**ggregation of **M**odularized **E**ntities: Substrate's
//! > State Transition Function (Runtime) Framework.
//!
//! ## Documentation
//!
//! See [`polkadot_sdk::frame`](../developer_hub/polkadot_sdk/frame_runtime/index.html).
//!
//! ## Warning: Experimental
//!
//! This crate and all of its content is experimental, and should not yet be used in production.
//!
//! ## Getting Started
//! ## Underlying dependencies
//!
//! TODO: link to `developer_hub::polkadot_sdk::frame`. The `developer_hub` hasn't been published
//! yet, this can be updated once it is linkable.
//! This crate is an amalgamation of multiple other crates that are often used together to compose a
//! pallet. It is not necessary to use it, and it may fall short for certain purposes.
//!
//! In short, this crate only re-exports types and traits from multiple sources. All of these
//! sources are listed (and re-exported again) in [`deps`].
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg(feature = "experimental")]
@@ -54,9 +57,19 @@
/// `#[pallet::bar]` inside the mod.
pub use frame_support::pallet;
pub use frame_support::pallet_macros::{import_section, pallet_section};
/// The logging library of the runtime. Can normally be the classic `log` crate.
pub use log;
/// A list of all macros used within the main [`pallet`] macro.
///
/// Note: All of these macros are "stubs" and not really usable outside `#[pallet] mod pallet { ..
/// }`. They are mainly provided for documentation and IDE support.
pub mod pallet_macros {
pub use frame_support::{derive_impl, pallet, pallet_macros::*};
}
/// The main prelude of FRAME.
///
/// This prelude should almost always be the first line of code in any pallet or runtime.
@@ -78,9 +91,6 @@ pub mod prelude {
/// Pallet prelude of `frame-support`.
///
/// Note: this needs to revised once `frame-support` evolves.
// `frame-support` will be break down https://github.com/paritytech/polkadot-sdk/issues/127 and its reexports will
// most likely change. These wildcard reexportings can be optimized once `frame-support` has
// changed.
#[doc(no_inline)]
pub use frame_support::pallet_prelude::*;
@@ -156,6 +166,9 @@ pub mod runtime {
/// Types to define your runtime version.
pub use sp_version::{create_runtime_str, runtime_version, RuntimeVersion};
/// Macro to implement runtime APIs.
pub use sp_api::impl_runtime_apis;
#[cfg(feature = "std")]
pub use sp_version::NativeVersion;
}
@@ -180,9 +193,6 @@ pub mod runtime {
pub use sp_inherents::{CheckInherentsResult, InherentData};
pub use sp_runtime::ApplyExtrinsicResult;
/// Macro to implement runtime APIs.
pub use sp_api::impl_runtime_apis;
pub use frame_system_rpc_runtime_api::*;
pub use sp_api::{self, *};
pub use sp_block_builder::*;
+9 -37
View File
@@ -1097,8 +1097,11 @@ pub fn weight(_: TokenStream, _: TokenStream) -> TokenStream {
pallet_macro_stub()
}
/// Compact encoding for arguments can be achieved via `#[pallet::compact]`. The function must
/// return a `DispatchResultWithPostInfo` or `DispatchResult`.
///
/// ---
///
/// **Rust-Analyzer users**: See the documentation of the Rust item in
/// [`frame_support::pallet_macros::call`](../../frame_support/pallet_macros/attr.call.html).
#[proc_macro_attribute]
pub fn compact(_: TokenStream, _: TokenStream) -> TokenStream {
pallet_macro_stub()
@@ -1108,7 +1111,7 @@ pub fn compact(_: TokenStream, _: TokenStream) -> TokenStream {
/// ---
///
/// **Rust-Analyzer users**: See the documentation of the Rust item in
/// `frame_support::pallet_macros::call`.
/// [`frame_support::pallet_macros::call`](../../frame_support/pallet_macros/attr.call.html).
#[proc_macro_attribute]
pub fn call(_: TokenStream, _: TokenStream) -> TokenStream {
pallet_macro_stub()
@@ -1117,41 +1120,10 @@ pub fn call(_: TokenStream, _: TokenStream) -> TokenStream {
/// Each dispatchable may also be annotated with the `#[pallet::call_index($idx)]` attribute,
/// which explicitly defines the codec index for the dispatchable function in the `Call` enum.
///
/// All call indexes start from 0, until it encounters a dispatchable function with a defined
/// call index. The dispatchable function that lexically follows the function with a defined
/// call index will have that call index, but incremented by 1, e.g. if there are 3
/// dispatchable functions `fn foo`, `fn bar` and `fn qux` in that order, and only `fn bar`
/// has a call index of 10, then `fn qux` will have an index of 11, instead of 1.
/// ---
///
/// All arguments must implement [`Debug`], [`PartialEq`], [`Eq`], `Decode`, `Encode`, and
/// [`Clone`]. For ease of use, bound by the trait `frame_support::pallet_prelude::Member`.
///
/// If no `#[pallet::call]` exists, then a default implementation corresponding to the
/// following code is automatically generated:
///
/// ```ignore
/// #[pallet::call]
/// impl<T: Config> Pallet<T> {}
/// ```
///
/// **WARNING**: modifying dispatchables, changing their order, removing some, etc., must be
/// done with care. Indeed this will change the outer runtime call type (which is an enum with
/// one variant per pallet), this outer runtime call can be stored on-chain (e.g. in
/// `pallet-scheduler`). Thus migration might be needed. To mitigate against some of this, the
/// `#[pallet::call_index($idx)]` attribute can be used to fix the order of the dispatchable so
/// that the `Call` enum encoding does not change after modification. As a general rule of
/// thumb, it is therefore adventageous to always add new calls to the end so you can maintain
/// the existing order of calls.
///
/// ### Macro expansion
///
/// The macro creates an enum `Call` with one variant per dispatchable. This enum implements:
/// [`Clone`], [`Eq`], [`PartialEq`], [`Debug`] (with stripped implementation in `not("std")`),
/// `Encode`, `Decode`, `GetDispatchInfo`, `GetCallName`, `GetCallIndex` and
/// `UnfilteredDispatchable`.
///
/// The macro implements the `Callable` trait on `Pallet` and a function `call_functions`
/// which returns the dispatchable metadata.
/// **Rust-Analyzer users**: See the documentation of the Rust item in
/// [`frame_support::pallet_macros::call`](../../frame_support/pallet_macros/attr.call.html).
#[proc_macro_attribute]
pub fn call_index(_: TokenStream, _: TokenStream) -> TokenStream {
pallet_macro_stub()
@@ -26,6 +26,7 @@ use syn::{spanned::Spanned, ExprClosure};
mod keyword {
syn::custom_keyword!(Call);
syn::custom_keyword!(OriginFor);
syn::custom_keyword!(RuntimeOrigin);
syn::custom_keyword!(weight);
syn::custom_keyword!(call_index);
syn::custom_keyword!(compact);
@@ -158,10 +159,10 @@ impl syn::parse::Parse for ArgAttrIsCompact {
}
}
/// Check the syntax is `OriginFor<T>` or `&OriginFor<T>`.
/// Check the syntax is `OriginFor<T>`, `&OriginFor<T>` or `T::RuntimeOrigin`.
pub fn check_dispatchable_first_arg_type(ty: &syn::Type, is_ref: bool) -> syn::Result<()> {
pub struct CheckDispatchableFirstArg(bool);
impl syn::parse::Parse for CheckDispatchableFirstArg {
pub struct CheckOriginFor(bool);
impl syn::parse::Parse for CheckOriginFor {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let is_ref = input.parse::<syn::Token![&]>().is_ok();
input.parse::<keyword::OriginFor>()?;
@@ -173,14 +174,27 @@ pub fn check_dispatchable_first_arg_type(ty: &syn::Type, is_ref: bool) -> syn::R
}
}
let result = syn::parse2::<CheckDispatchableFirstArg>(ty.to_token_stream());
return match result {
Ok(CheckDispatchableFirstArg(has_ref)) if is_ref == has_ref => Ok(()),
_ => {
pub struct CheckRuntimeOrigin;
impl syn::parse::Parse for CheckRuntimeOrigin {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
input.parse::<keyword::T>()?;
input.parse::<syn::Token![::]>()?;
input.parse::<keyword::RuntimeOrigin>()?;
Ok(Self)
}
}
let result_origin_for = syn::parse2::<CheckOriginFor>(ty.to_token_stream());
let result_runtime_origin = syn::parse2::<CheckRuntimeOrigin>(ty.to_token_stream());
return match (result_origin_for, result_runtime_origin) {
(Ok(CheckOriginFor(has_ref)), _) if is_ref == has_ref => Ok(()),
(_, Ok(_)) => Ok(()),
(_, _) => {
let msg = if is_ref {
"Invalid type: expected `&OriginFor<T>`"
} else {
"Invalid type: expected `OriginFor<T>`"
"Invalid type: expected `OriginFor<T>` or `T::RuntimeOrigin`"
};
return Err(syn::Error::new(ty.span(), msg))
},
@@ -282,8 +296,8 @@ impl CallDef {
0 if dev_mode => CallWeightDef::DevModeDefault,
0 => return Err(syn::Error::new(
method.sig.span(),
"A pallet::call requires either a concrete `#[pallet::weight($expr)]` or an
inherited weight from the `#[pallet:call(weight($type))]` attribute, but
"A pallet::call requires either a concrete `#[pallet::weight($expr)]` or an
inherited weight from the `#[pallet:call(weight($type))]` attribute, but
none were given.",
)),
1 => match weight_attrs.pop().unwrap() {
+2 -1
View File
@@ -36,7 +36,8 @@ use sp_weights::Weight;
/// returned from a dispatch.
pub type DispatchResultWithPostInfo = sp_runtime::DispatchResultWithInfo<PostDispatchInfo>;
/// Unaugmented version of `DispatchResultWithPostInfo` that can be returned from
#[docify::export]
/// Un-augmented version of `DispatchResultWithPostInfo` that can be returned from
/// dispatchable functions and is automatically converted to the augmented type. Should be
/// used whenever the `PostDispatchInfo` does not need to be overwritten. As this should
/// be the common case it is the implicit return type when none is specified.
+150 -2
View File
@@ -47,6 +47,8 @@ pub mod __private {
pub use sp_core::{OpaqueMetadata, Void};
pub use sp_core_hashing_proc_macro;
pub use sp_inherents;
#[cfg(feature = "std")]
pub use sp_io::TestExternalities;
pub use sp_io::{self, hashing, storage::root as storage_root};
pub use sp_metadata_ir as metadata_ir;
#[cfg(feature = "std")]
@@ -2226,13 +2228,159 @@ pub use frame_support_procedural::pallet;
/// Contains macro stubs for all of the pallet:: macros
pub mod pallet_macros {
pub use frame_support_procedural::{
call_index, compact, composite_enum, config, disable_frame_system_supertrait_check, error,
event, extra_constants, feeless_if, generate_deposit, generate_store, getter, hooks,
composite_enum, config, disable_frame_system_supertrait_check, error, event,
extra_constants, feeless_if, generate_deposit, generate_store, getter, hooks,
import_section, inherent, no_default, no_default_bounds, origin, pallet_section,
storage_prefix, storage_version, type_value, unbounded, validate_unsigned, weight,
whitelist_storage,
};
/// Allows a pallet to declare a set of functions as a *dispatchable extrinsic*. In
/// slightly simplified terms, this macro declares the set of "transactions" of a pallet.
///
/// > The exact definition of **extrinsic** can be found in
/// > [`sp_runtime::generic::UncheckedExtrinsic`].
///
/// A **dispatchable** is a common term in FRAME, referring to process of constructing a
/// function, and dispatching it with the correct inputs. This is commonly used with
/// extrinsics, for example "an extrinsic has been dispatched". See
/// [`sp_runtime::traits::Dispatchable`] and [`crate::traits::UnfilteredDispatchable`].
///
/// ## Call Enum
///
/// The macro is called `call` (rather than `#[pallet::extrinsics]`) because of the
/// generation of a `enum Call`. This enum contains only the encoding of the function
/// arguments of the dispatchable, alongside the information needed to route it to the
/// correct function.
///
/// ```
/// #[frame_support::pallet(dev_mode)]
/// pub mod custom_pallet {
/// # use frame_support::pallet_prelude::*;
/// # use frame_system::pallet_prelude::*;
/// # #[pallet::config]
/// # pub trait Config: frame_system::Config {}
/// # #[pallet::pallet]
/// # pub struct Pallet<T>(_);
/// # use frame_support::traits::BuildGenesisConfig;
/// #[pallet::call]
/// impl<T: Config> Pallet<T> {
/// pub fn some_dispatchable(_origin: OriginFor<T>, _input: u32) -> DispatchResult {
/// Ok(())
/// }
/// pub fn other(_origin: OriginFor<T>, _input: u64) -> DispatchResult {
/// Ok(())
/// }
/// }
///
/// // generates something like:
/// // enum Call<T: Config> {
/// // some_dispatchable { input: u32 }
/// // other { input: u64 }
/// // }
/// }
///
/// fn main() {
/// # use frame_support::{derive_impl, construct_runtime};
/// # use frame_support::__private::codec::Encode;
/// # use frame_support::__private::TestExternalities;
/// # use frame_support::traits::UnfilteredDispatchable;
/// # impl custom_pallet::Config for Runtime {}
/// # #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
/// # impl frame_system::Config for Runtime {
/// # type Block = frame_system::mocking::MockBlock<Self>;
/// # }
/// construct_runtime! {
/// pub struct Runtime {
/// System: frame_system,
/// Custom: custom_pallet
/// }
/// }
///
/// # TestExternalities::new_empty().execute_with(|| {
/// let origin: RuntimeOrigin = frame_system::RawOrigin::Signed(10).into();
/// // calling into a dispatchable from within the runtime is simply a function call.
/// let _ = custom_pallet::Pallet::<Runtime>::some_dispatchable(origin.clone(), 10);
///
/// // calling into a dispatchable from the outer world involves constructing the bytes of
/// let call = custom_pallet::Call::<Runtime>::some_dispatchable { input: 10 };
/// let _ = call.clone().dispatch_bypass_filter(origin);
///
/// // the routing of a dispatchable is simply done through encoding of the `Call` enum,
/// // which is the index of the variant, followed by the arguments.
/// assert_eq!(call.encode(), vec![0u8, 10, 0, 0, 0]);
///
/// // notice how in the encoding of the second function, the first byte is different and
/// // referring to the second variant of `enum Call`.
/// let call = custom_pallet::Call::<Runtime>::other { input: 10 };
/// assert_eq!(call.encode(), vec![1u8, 10, 0, 0, 0, 0, 0, 0, 0]);
/// # });
/// }
/// ```
///
/// Further properties of dispatchable functions are as follows:
///
/// - Unless if annotated by `dev_mode`, it must contain [`weight`] to denote the
/// pre-dispatch weight consumed.
/// - The dispatchable must declare its index via [`call_index`], which can override the
/// position of a function in `enum Call`.
/// - The first argument is always an `OriginFor` (or `T::RuntimeOrigin`).
/// - The return type is always [`crate::dispatch::DispatchResult`] (or
/// [`crate::dispatch::DispatchResultWithPostInfo`]).
///
/// **WARNING**: modifying dispatchables, changing their order (i.e. using [`call_index`]),
/// removing some, etc., must be done with care. This will change the encoding of the , and
/// the call can be stored on-chain (e.g. in `pallet-scheduler`). Thus, migration might be
/// needed. This is why the use of `call_index` is mandatory by default in FRAME.
///
/// ## Default Behavior
///
/// If no `#[pallet::call]` exists, then a default implementation corresponding to the
/// following code is automatically generated:
///
/// ```ignore
/// #[pallet::call]
/// impl<T: Config> Pallet<T> {}
/// ```
pub use frame_support_procedural::call;
/// Enforce the index of a variant in the generated `enum Call`. See [`call`] for more
/// information.
///
/// All call indexes start from 0, until it encounters a dispatchable function with a
/// defined call index. The dispatchable function that lexically follows the function with
/// a defined call index will have that call index, but incremented by 1, e.g. if there are
/// 3 dispatchable functions `fn foo`, `fn bar` and `fn qux` in that order, and only `fn
/// bar` has a call index of 10, then `fn qux` will have an index of 11, instead of 1.
pub use frame_support_procedural::call_index;
/// Declares the arguments of a [`call`] function to be encoded using
/// [`codec::Compact`]. This will results in smaller extrinsic encoding.
///
/// A common example of `compact` is for numeric values that are often times far far away
/// from their theoretical maximum. For example, in the context of a crypto-currency, the
/// balance of an individual account is oftentimes way less than what the numeric type
/// allows. In all such cases, using `compact` is sensible.
///
/// ```
/// #[frame_support::pallet(dev_mode)]
/// pub mod custom_pallet {
/// # use frame_support::pallet_prelude::*;
/// # use frame_system::pallet_prelude::*;
/// # #[pallet::config]
/// # pub trait Config: frame_system::Config {}
/// # #[pallet::pallet]
/// # pub struct Pallet<T>(_);
/// # use frame_support::traits::BuildGenesisConfig;
/// #[pallet::call]
/// impl<T: Config> Pallet<T> {
/// pub fn some_dispatchable(_origin: OriginFor<T>, #[pallet::compact] _input: u32) -> DispatchResult {
/// Ok(())
/// }
/// }
/// }
pub use frame_support_procedural::compact;
/// Allows you to define the genesis configuration for the pallet.
///
/// Item is defined as either an enum or a struct. It needs to be public and implement the
+1 -2
View File
@@ -224,8 +224,7 @@ impl PalletVersionToStorageVersionHelper for T {
}
}
/// Migrate from the `PalletVersion` struct to the new
/// [`StorageVersion`](crate::traits::StorageVersion) struct.
/// Migrate from the `PalletVersion` struct to the new [`StorageVersion`] struct.
///
/// This will remove all `PalletVersion's` from the state and insert the current storage version.
pub fn migrate_from_pallet_version_to_storage_version<
+3 -3
View File
@@ -165,9 +165,9 @@ pub fn kill_storage(child_info: &ChildInfo, limit: Option<u32>) -> KillStorageRe
/// guarantee that the subsequent call is in a new block; in this case the previous call's result
/// cursor need not be passed in an a `None` may be passed instead. This exception may be useful
/// then making this call solely from a block-hook such as `on_initialize`.
///
/// Returns [`MultiRemovalResults`](sp_io::MultiRemovalResults) to inform about the result. Once the
/// resultant `maybe_cursor` field is `None`, then no further items remain to be deleted.
/// Returns [`MultiRemovalResults`] to inform about the result. Once the resultant `maybe_cursor`
/// field is `None`, then no further items remain to be deleted.
///
/// NOTE: After the initial call for any given child storage, it is important that no keys further
/// keys are inserted. If so, then they may or may not be deleted by subsequent calls.
+3 -3
View File
@@ -1583,7 +1583,7 @@ pub trait StorageTryAppend<Item>: StorageDecodeLength + private::Sealed {
fn bound() -> usize;
}
/// Storage value that is capable of [`StorageTryAppend`](crate::storage::StorageTryAppend).
/// Storage value that is capable of [`StorageTryAppend`].
pub trait TryAppendValue<T: StorageTryAppend<I>, I: Encode> {
/// Try and append the `item` into the storage item.
///
@@ -1612,7 +1612,7 @@ where
}
}
/// Storage map that is capable of [`StorageTryAppend`](crate::storage::StorageTryAppend).
/// Storage map that is capable of [`StorageTryAppend`].
pub trait TryAppendMap<K: Encode, T: StorageTryAppend<I>, I: Encode> {
/// Try and append the `item` into the storage map at the given `key`.
///
@@ -1646,7 +1646,7 @@ where
}
}
/// Storage double map that is capable of [`StorageTryAppend`](crate::storage::StorageTryAppend).
/// Storage double map that is capable of [`StorageTryAppend`].
pub trait TryAppendDoubleMap<K1: Encode, K2: Encode, T: StorageTryAppend<I>, I: Encode> {
/// Try and append the `item` into the storage double map at the given `key`.
///
@@ -97,7 +97,7 @@ note: required because it appears within the type `RuntimeEvent`
| ||_- in this macro invocation
... |
note: required by a bound in `EncodeLike`
--> $CARGO/parity-scale-codec-3.6.4/src/encode_like.rs
--> $CARGO/parity-scale-codec-3.6.5/src/encode_like.rs
|
| pub trait EncodeLike<T: Encode = Self>: Sized + Encode {}
| ^^^^^ required by this bound in `EncodeLike`
@@ -129,7 +129,7 @@ note: required because it appears within the type `RuntimeEvent`
| ||_- in this macro invocation
... |
note: required by a bound in `Decode`
--> $CARGO/parity-scale-codec-3.6.4/src/codec.rs
--> $CARGO/parity-scale-codec-3.6.5/src/codec.rs
|
| pub trait Decode: Sized {
| ^^^^^ required by this bound in `Decode`
@@ -301,7 +301,7 @@ note: required because it appears within the type `RuntimeCall`
| ||_- in this macro invocation
... |
note: required by a bound in `EncodeLike`
--> $CARGO/parity-scale-codec-3.6.4/src/encode_like.rs
--> $CARGO/parity-scale-codec-3.6.5/src/encode_like.rs
|
| pub trait EncodeLike<T: Encode = Self>: Sized + Encode {}
| ^^^^^ required by this bound in `EncodeLike`
@@ -334,7 +334,7 @@ note: required because it appears within the type `RuntimeCall`
| ||_- in this macro invocation
... |
note: required by a bound in `Decode`
--> $CARGO/parity-scale-codec-3.6.4/src/codec.rs
--> $CARGO/parity-scale-codec-3.6.5/src/codec.rs
|
| pub trait Decode: Sized {
| ^^^^^ required by this bound in `Decode`
@@ -1,4 +1,4 @@
error: Invalid type: expected `OriginFor<T>`
error: Invalid type: expected `OriginFor<T>` or `T::RuntimeOrigin`
--> tests/pallet_ui/call_invalid_origin_type.rs:34:22
|
34 | pub fn foo(origin: u8) {}
+1 -1
View File
@@ -25,7 +25,7 @@ sp-runtime = { path = "../../primitives/runtime", default-features = false, feat
sp-std = { path = "../../primitives/std", default-features = false}
sp-version = { path = "../../primitives/version", default-features = false, features = ["serde"] }
sp-weights = { path = "../../primitives/weights", default-features = false, features = ["serde"] }
docify = "0.2.0"
docify = "0.2.6"
[dev-dependencies]
criterion = "0.4.0"
+18 -6
View File
@@ -1018,6 +1018,7 @@ impl_ensure_origin_with_arg_ignoring_arg! {
{}
}
#[docify::export]
/// Ensure that the origin `o` represents a signed extrinsic (i.e. transaction).
/// Returns `Ok` with the account that signed the extrinsic or an `Err` otherwise.
pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
@@ -1372,6 +1373,7 @@ impl<T: Config> Pallet<T> {
/// NOTE: Events not registered at the genesis block and quietly omitted.
pub fn deposit_event_indexed(topics: &[T::Hash], event: T::RuntimeEvent) {
let block_number = Self::block_number();
// Don't populate events on genesis.
if block_number.is_zero() {
return
@@ -1555,12 +1557,7 @@ impl<T: Config> Pallet<T> {
/// NOTE: Events not registered at the genesis block and quietly omitted.
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn events() -> Vec<EventRecord<T::RuntimeEvent, T::Hash>> {
debug_assert!(
!Self::block_number().is_zero(),
"events not registered at the genesis block"
);
// Dereferencing the events here is fine since we are not in the
// memory-restricted runtime.
// Dereferencing the events here is fine since we are not in the memory-restricted runtime.
Self::read_events_no_consensus().map(|e| *e).collect()
}
@@ -1581,6 +1578,21 @@ impl<T: Config> Pallet<T> {
Events::<T>::stream_iter()
}
/// Read and return the events of a specific pallet, as denoted by `E`.
///
/// This is useful for a pallet that wishes to read only the events it has deposited into
/// `frame_system` using the standard `fn deposit_event`.
pub fn read_events_for_pallet<E>() -> Vec<E>
where
T::RuntimeEvent: TryInto<E>,
{
Events::<T>::get()
.into_iter()
.map(|er| er.event)
.filter_map(|e| e.try_into().ok())
.collect::<_>()
}
/// Set the block number to something in particular. Can be used as an alternative to
/// `initialize` for tests that don't need to bother with the other environment entries.
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
+2 -2
View File
@@ -90,7 +90,7 @@ pub fn migrate<T: pallet_tips::Config, P: GetStorageVersion + PalletInfoAccess,
}
/// Some checks prior to migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::pre_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn pre_migrate<
@@ -129,7 +129,7 @@ pub fn pre_migrate<
}
/// Some checks for after migration. This can be linked to
/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing.
/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing.
///
/// Panics if anything goes wrong.
pub fn post_migrate<