::Currency as CurrencyTrait>::Balance;
+}
diff --git a/docs/sdk/src/reference_docs/wasm_memory.rs b/docs/sdk/src/reference_docs/wasm_memory.rs
new file mode 100644
index 0000000000000..4f4cda31094e4
--- /dev/null
+++ b/docs/sdk/src/reference_docs/wasm_memory.rs
@@ -0,0 +1,7 @@
+//! # WASM Memory Limitations.
+//!
+//! Notes:
+//!
+//! - Stack: Need to use `Box<_>`
+//! - Heap: Substrate imposes a limit. PvF execution has its own limits
+//! - Heap: There is also a maximum amount that a single allocation can have.
diff --git a/docs/sdk/src/reference_docs/wasm_meta_protocol.rs b/docs/sdk/src/reference_docs/wasm_meta_protocol.rs
new file mode 100644
index 0000000000000..37d1460f0e1a3
--- /dev/null
+++ b/docs/sdk/src/reference_docs/wasm_meta_protocol.rs
@@ -0,0 +1,113 @@
+//! # WASM Meta Protocol
+//!
+//! All Substrate based chains adhere to a unique architectural design novel to the Polkadot
+//! ecosystem. We refer to this design as the "WASM Meta Protocol".
+//!
+//! Consider the fact that a traditional blockchain software is usually a monolithic artifact.
+//! Upgrading any part of the system implies upgrading the entire system. This has historically led
+//! to cumbersome forkful upgrades to be the status quo in the blockchain ecosystem.
+//!
+//! Moreover, the idea of "storing code in the state" is explored in the context of smart contracts
+//! platforms, but has not been expanded further.
+//!
+//! Substrate mixes these two ideas together, and takes the novel approach of storing the
+//! blockchain's main "state transition function" in the main blockchain state, in the same fashion
+//! that a smart contract platform stores the code of individual contracts in its state. As noted in
+//! [`crate::reference_docs::blockchain_state_machines`], this state transition function is called
+//! the **Runtime**, and WASM is chosen as the bytecode. The Runtime is stored under a special key
+//! in the state (see
+//! [`sp_core::storage::well_known_keys`](../../../sp_core/index.html)) and can be
+//! updated as a part of the state transition function's execution, just like a user's account
+//! balance can be updated.
+//!
+//! > Note that while we drew an analogy between smart contracts and runtimes in the above, there
+//! > are fundamental differences between the two, explained in
+//! > [`crate::reference_docs::runtime_vs_smart_contract`].
+//!
+//! The rest of the system that is NOT the state transition function is called the **node**, and
+//! is a normal binary that is compiled from Rust to different hardware targets.
+//!
+//! This design enables all Substrate-based chains to be fork-less-ly upgradeable, because the
+//! Runtime can be updates on the fly, within the execution of a block, and the node is (for the
+//! most part) oblivious to the change that is happening.
+//!
+//! Therefore, the high-level architecture of a any Substrate-based chain can be demonstrated as
+//! follows:
+#![doc = simple_mermaid::mermaid!("../../../mermaid/substrate_simple.mmd")]
+//!
+//! The node and the runtime need to communicate. This is done through two concepts:
+//!
+//! 1. **Host functions**: a way for the (WASM) runtime to talk to the node. All host functions are
+//! defined in [`sp_io`]. For example, [`sp_io::storage`] are the set of host functions that
+//! allow the runtime to read and write data to the on-chain state.
+//! 2. **Runtime APIs**: a way for the node to talk to the WASM runtime. Runtime APIs are defined
+//! using macros and utilities in [`sp_api`]. For example, [`sp_api::Core`] is the most
+//! fundamental runtime API that any blockchain must implement in order to be able to (re)
+//! execute blocks.
+#![doc = simple_mermaid::mermaid!("../../../mermaid/substrate_client_runtime.mmd")]
+//!
+//! A runtime must have a set of runtime APIs in order to have any meaningful blockchain
+//! functionality, but it can also expose more APIs. See TODO as an example of how to add custom
+//! runtime APIs to your FRAME-based runtime.
+//!
+//! Similarly, for a runtime to be "compatible" with a node, the node must implement the full set of
+//! host functions that the runtime at any point in time requires. Given the fact that a runtime can
+//! evolve in time, and a blockchain node (typically) wishes to be capable of re-executing all the
+//! previous blocks, this means that a node must always maintain support for the old host functions.
+//! This also implies that adding a new host function is a big commitment and should be done with
+//! care. This is why, for example, adding a new host function to Polkadot always requires an RFC.
+//!
+//! ## Node vs. Runtime
+//!
+//! A common question is: which components of the system end up being part of the node, and which
+//! ones of the runtime?
+//!
+//! Recall from [`crate::reference_docs::blockchain_state_machines`] that the runtime is the state
+//! transition function. Anything that needs to influence how your blockchain's state is updated,
+//! should be a part of the runtime. For example, the logic around currency, governance, identity or
+//! any other application-specific logic that has to do with the state is part of the runtime.
+//!
+//! Anything that does not have to do with the state-transition function and will only
+//! facilitate/enable it is part of the node. For example, the database, networking, and even
+//! consensus algorithm are all node-side components.
+//!
+//! > The consensus is to your runtime what HTTP is to a web-application. It is the underlying
+//! > engine that enables trustless execution of the runtime in a distributed manner whilst
+//! > maintaining a canonical outcome of that execution.
+#![doc = simple_mermaid::mermaid!("../../../mermaid/substrate_with_frame.mmd")]
+//!
+//! ## State
+//!
+//! From the previous sections, we know that the a database component is part of the node, not the
+//! runtime. We also hinted that a set of host functions ([`sp_io::storage`]) are how the runtime
+//! issues commands to the node to read/write to the state. Let's dive deeper into this.
+//!
+//! The state of the blockchain, what we seek to come to consensus about, is indeed *kept* in the
+//! node side. Nonetheless, the runtime is the only component that:
+//!
+//! 1. Can update the state.
+//! 2. Can fully interpret the state.
+//!
+//! In fact, [`sp_core::storage::well_known_keys`] are the only state keys that the node side is
+//! aware of. The rest of the state, including what logic the runtime has, what balance each user
+//! has and such are all only comprehensible to the runtime.
+#![doc = simple_mermaid::mermaid!("../../../mermaid/state.mmd")]
+//!
+//! In the above diagram, all of the state keys and values are opaque bytes to the node. The node
+//! does not know what they mean, and it does not now what is the type of the corresponding value
+//! (e.g. if it is a number of a vector). Contrary, the runtime knows both the meaning of their
+//! keys, and the type of the values.
+//!
+//! This opaque-ness is the fundamental reason why Substrate-based chains can fork-less-ly upgrade:
+//! because the node side code is kept oblivious to all of the details of the state transition
+//! function. Therefore, the state transition function can freely upgrade without the node needing
+//! to know.
+//!
+//! ## Native Runtime
+//!
+//! TODO
+//!
+//!
+//! ## Example: Block Execution.
+//!
+//! TODO
diff --git a/polkadot/README.md b/polkadot/README.md
index 3c234bb8e3f4d..dbb1bf6a352b6 100644
--- a/polkadot/README.md
+++ b/polkadot/README.md
@@ -213,7 +213,7 @@ that we currently maintain.
### Using Docker
-[Using Docker](../docs/docker.md)
+[Using Docker](../docs/contributor/docker.md)
### Shell Completion
@@ -223,11 +223,11 @@ that we currently maintain.
### Contributing Guidelines
-[Contribution Guidelines](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CONTRIBUTING.md)
+[Contribution Guidelines](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md)
### Contributor Code of Conduct
-[Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CODE_OF_CONDUCT.md)
+[Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CODE_OF_CONDUCT.md)
## License
diff --git a/polkadot/node/network/protocol/src/request_response/mod.rs b/polkadot/node/network/protocol/src/request_response/mod.rs
index 96f7adeb29ba0..2df3021343df0 100644
--- a/polkadot/node/network/protocol/src/request_response/mod.rs
+++ b/polkadot/node/network/protocol/src/request_response/mod.rs
@@ -248,8 +248,8 @@ impl Protocol {
name,
fallback_names,
max_request_size: 1_000,
- /// Responses are just confirmation, in essence not even a bit. So 100 seems
- /// plenty.
+ // Responses are just confirmation, in essence not even a bit. So 100 seems
+ // plenty.
max_response_size: 100,
request_timeout: DISPUTE_REQUEST_TIMEOUT,
inbound_queue: tx,
diff --git a/polkadot/node/primitives/src/lib.rs b/polkadot/node/primitives/src/lib.rs
index dab72bb2a5ed8..be62145b99917 100644
--- a/polkadot/node/primitives/src/lib.rs
+++ b/polkadot/node/primitives/src/lib.rs
@@ -442,7 +442,7 @@ pub struct CollationSecondedSignal {
pub relay_parent: Hash,
/// The statement about seconding the collation.
///
- /// Anything else than [`Statement::Seconded`](Statement::Seconded) is forbidden here.
+ /// Anything else than [`Statement::Seconded`] is forbidden here.
pub statement: SignedFullStatement,
}
diff --git a/substrate/Cargo.toml b/substrate/Cargo.toml
deleted file mode 100644
index 8fb1be5821bad..0000000000000
--- a/substrate/Cargo.toml
+++ /dev/null
@@ -1,30 +0,0 @@
-[package]
-name = "substrate"
-description = "Next-generation framework for blockchain innovation"
-license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
-homepage = "https://substrate.io"
-repository.workspace = true
-authors.workspace = true
-edition.workspace = true
-version = "1.0.0"
-publish = false
-
-# The dependencies are only needed for docs.
-[dependencies]
-simple-mermaid = { git = "https://github.com/kianenigma/simple-mermaid.git", rev = "e48b187bcfd5cc75111acd9d241f1bd36604344b" }
-
-subkey = { path = "bin/utils/subkey" }
-chain-spec-builder = { package = "staging-chain-spec-builder", path = "bin/utils/chain-spec-builder" }
-
-sc-service = { path = "client/service" }
-sc-chain-spec = { path = "client/chain-spec" }
-sc-cli = { path = "client/cli" }
-sc-consensus-aura = { path = "client/consensus/aura" }
-sc-consensus-babe = { path = "client/consensus/babe" }
-sc-consensus-grandpa = { path = "client/consensus/grandpa" }
-sc-consensus-beefy = { path = "client/consensus/beefy" }
-sc-consensus-manual-seal = { path = "client/consensus/manual-seal" }
-sc-consensus-pow = { path = "client/consensus/pow" }
-
-sp-runtime = { path = "primitives/runtime" }
-frame-support = { path = "frame/support" }
diff --git a/substrate/README.md b/substrate/README.md
index f7afa7a894d88..81c7625539df4 100644
--- a/substrate/README.md
+++ b/substrate/README.md
@@ -3,7 +3,7 @@
[](#LICENSE)
[](https://gitlab.parity.io/parity/mirrors/polkadot-sdk/-/pipelines)
-[](docs/CONTRIBUTING.md)
+[](docs/contributor/CONTRIBUTING.md)
[](https://substrate.stackexchange.com/)
@@ -27,14 +27,13 @@ here](https://github.com/paritytech/polkadot-sdk/issues) for anything you suspec
## Contributions & Code of Conduct
Please follow the contributions guidelines as outlined in
-[`docs/CONTRIBUTING.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CONTRIBUTING.md). In all
-communications and contributions, this project follows the [Contributor Covenant Code of
-Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CODE_OF_CONDUCT.md).
+[`docs/contributor/CONTRIBUTING.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md).
+In all communications and contributions, this project follows the [Contributor Covenant Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CODE_OF_CONDUCT.md).
## Security
The security policy and procedures can be found in
-[`docs/SECURITY.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/SECURITY.md).
+[`docs/contributor/SECURITY.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/SECURITY.md).
## License
diff --git a/substrate/client/allocator/src/lib.rs b/substrate/client/allocator/src/lib.rs
index e50d7d54c8e97..70ed764bef8c1 100644
--- a/substrate/client/allocator/src/lib.rs
+++ b/substrate/client/allocator/src/lib.rs
@@ -18,7 +18,7 @@
//! Collection of allocator implementations.
//!
//! This crate provides the following allocator implementations:
-//! - A freeing-bump allocator: [`FreeingBumpHeapAllocator`](freeing_bump::FreeingBumpHeapAllocator)
+//! - A freeing-bump allocator: [`FreeingBumpHeapAllocator`]
#![warn(missing_docs)]
diff --git a/substrate/client/executor/src/lib.rs b/substrate/client/executor/src/lib.rs
index 6ee0ab3512ac0..25bad81938f38 100644
--- a/substrate/client/executor/src/lib.rs
+++ b/substrate/client/executor/src/lib.rs
@@ -58,7 +58,7 @@ pub use sc_executor_wasmtime::InstantiationStrategy as WasmtimeInstantiationStra
/// Extracts the runtime version of a given runtime code.
pub trait RuntimeVersionOf {
- /// Extract [`RuntimeVersion`](sp_version::RuntimeVersion) of the given `runtime_code`.
+ /// Extract [`RuntimeVersion`] of the given `runtime_code`.
fn runtime_version(
&self,
ext: &mut dyn Externalities,
diff --git a/substrate/frame/balances/src/lib.rs b/substrate/frame/balances/src/lib.rs
index d518f933df8db..843bc351494e3 100644
--- a/substrate/frame/balances/src/lib.rs
+++ b/substrate/frame/balances/src/lib.rs
@@ -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;
+//! # type Currency: Currency;
//! # }
//!
//! pub type BalanceOf = <::Currency as Currency<::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>;
+//! type Currency: LockableCurrency>;
//! }
//! # struct StakingLedger {
-//! # stash: ::AccountId,
-//! # total: <::Currency as frame_support::traits::Currency<::AccountId>>::Balance,
-//! # phantom: std::marker::PhantomData,
+//! # stash: ::AccountId,
+//! # total: <::Currency as frame_support::traits::Currency<::AccountId>>::Balance,
+//! # phantom: std::marker::PhantomData,
//! # }
//! # const STAKING_ID: [u8; 8] = *b"staking ";
//!
//! fn update_ledger(
-//! controller: &T::AccountId,
-//! ledger: &StakingLedger
+//! controller: &T::AccountId,
+//! ledger: &StakingLedger
//! ) {
-//! T::Currency::set_lock(
-//! STAKING_ID,
-//! &ledger.stash,
-//! ledger.total,
-//! WithdrawReasons::all()
-//! );
-//! // >::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()
+//! );
+//! // >::insert(controller, ledger); // Commented out as we don't have access to Staking's storage here.
//! }
//! # fn main() {}
//! ```
diff --git a/substrate/frame/bounties/src/migrations/v4.rs b/substrate/frame/bounties/src/migrations/v4.rs
index 936bac1170089..4e6ba93448162 100644
--- a/substrate/frame/bounties/src/migrations/v4.rs
+++ b/substrate/frame/bounties/src/migrations/v4.rs
@@ -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>(
@@ -164,7 +164,7 @@ pub fn pre_migration>(
diff --git a/substrate/frame/collective/src/migrations/v4.rs b/substrate/frame/collective/src/migrations/v4.rs
index b3326b4251c9b..300dff23d8eb5 100644
--- a/substrate/frame/collective/src/migrations/v4.rs
+++ b/substrate/frame/collective/src/migrations/v4.rs
@@ -76,7 +76,7 @@ pub fn migrate>(old_pallet_name: N) {
@@ -104,7 +104,7 @@ pub fn pre_migrate>(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>(old_pallet_name: N) {
diff --git a/substrate/frame/election-provider-multi-phase/src/mock.rs b/substrate/frame/election-provider-multi-phase/src/mock.rs
index 15a50165ff379..7bdd329d9b041 100644
--- a/substrate/frame/election-provider-multi-phase/src/mock.rs
+++ b/substrate/frame/election-provider-multi-phase/src/mock.rs
@@ -80,11 +80,7 @@ frame_election_provider_support::generate_solution_type!(
/// All events of this pallet.
pub(crate) fn multi_phase_events() -> Vec> {
- System::events()
- .into_iter()
- .map(|r| r.event)
- .filter_map(|e| if let RuntimeEvent::MultiPhase(inner) = e { Some(inner) } else { None })
- .collect::>()
+ System::read_events_for_pallet::>()
}
/// To from `now` to block `n`.
diff --git a/substrate/frame/elections-phragmen/src/migrations/v4.rs b/substrate/frame/elections-phragmen/src/migrations/v4.rs
index 7e946371f5ca6..e78465cd618de 100644
--- a/substrate/frame/elections-phragmen/src/migrations/v4.rs
+++ b/substrate/frame/elections-phragmen/src/migrations/v4.rs
@@ -69,7 +69,7 @@ pub fn migrate>(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>(new: N) {
@@ -97,7 +97,7 @@ pub fn pre_migration>(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() {
diff --git a/substrate/frame/elections-phragmen/src/migrations/v5.rs b/substrate/frame/elections-phragmen/src/migrations/v5.rs
index 6fac923703fec..6e360aa8b8c15 100644
--- a/substrate/frame/elections-phragmen/src/migrations/v5.rs
+++ b/substrate/frame/elections-phragmen/src/migrations/v5.rs
@@ -71,7 +71,7 @@ pub fn pre_migrate_fn(to_migrate: Vec) -> Box() {
diff --git a/substrate/frame/examples/kitchensink/src/lib.rs b/substrate/frame/examples/kitchensink/src/lib.rs
index 89759dd0bf635..18429bc967d7c 100644
--- a/substrate/frame/examples/kitchensink/src/lib.rs
+++ b/substrate/frame/examples/kitchensink/src/lib.rs
@@ -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,
diff --git a/substrate/frame/fast-unstake/src/types.rs b/substrate/frame/fast-unstake/src/types.rs
index 15d0a327e917e..3fb5720861fa8 100644
--- a/substrate/frame/fast-unstake/src/types.rs
+++ b/substrate/frame/fast-unstake/src/types.rs
@@ -39,6 +39,7 @@ impl frame_support::traits::Get for MaxChecking {
}
}
+#[docify::export]
pub(crate) type BalanceOf =
<::Currency as Currency<::AccountId>>::Balance;
/// An unstake request.
diff --git a/substrate/frame/grandpa/src/migrations/v4.rs b/substrate/frame/grandpa/src/migrations/v4.rs
index 8604296b6e57b..9daa818071f70 100644
--- a/substrate/frame/grandpa/src/migrations/v4.rs
+++ b/substrate/frame/grandpa/src/migrations/v4.rs
@@ -63,7 +63,7 @@ pub fn migrate>(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>(new: N) {
@@ -99,7 +99,7 @@ pub fn pre_migration>(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() {
diff --git a/substrate/frame/membership/src/migrations/v4.rs b/substrate/frame/membership/src/migrations/v4.rs
index 38e97af51a09d..9b80aca868474 100644
--- a/substrate/frame/membership/src/migrations/v4.rs
+++ b/substrate/frame/membership/src/migrations/v4.rs
@@ -77,7 +77,7 @@ pub fn migrate>(old_pallet_name: N, new_pallet_name: N) {
@@ -105,7 +105,7 @@ pub fn pre_migrate>(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>(old_pallet_name: N, new_pallet_name: N) {
diff --git a/substrate/frame/session/src/historical/offchain.rs b/substrate/frame/session/src/historical/offchain.rs
index 1b4d53b74b45e..95f4d762949ee 100644
--- a/substrate/frame/session/src/historical/offchain.rs
+++ b/substrate/frame/session/src/historical/offchain.rs
@@ -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},
diff --git a/substrate/frame/src/lib.rs b/substrate/frame/src/lib.rs
index 1a8350405a890..59cd923788888 100644
--- a/substrate/frame/src/lib.rs
+++ b/substrate/frame/src/lib.rs
@@ -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::*;
diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs
index ec4118918856a..682b135fa1432 100644
--- a/substrate/frame/support/procedural/src/lib.rs
+++ b/substrate/frame/support/procedural/src/lib.rs
@@ -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 Pallet {}
-/// ```
-///
-/// **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()
diff --git a/substrate/frame/support/procedural/src/pallet/parse/call.rs b/substrate/frame/support/procedural/src/pallet/parse/call.rs
index 519e1e618954f..f78f2baa9d10e 100644
--- a/substrate/frame/support/procedural/src/pallet/parse/call.rs
+++ b/substrate/frame/support/procedural/src/pallet/parse/call.rs
@@ -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` or `&OriginFor`.
+/// Check the syntax is `OriginFor`, `&OriginFor` 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 {
let is_ref = input.parse::().is_ok();
input.parse::()?;
@@ -173,14 +174,27 @@ pub fn check_dispatchable_first_arg_type(ty: &syn::Type, is_ref: bool) -> syn::R
}
}
- let result = syn::parse2::(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 {
+ input.parse::()?;
+ input.parse::()?;
+ input.parse::()?;
+
+ Ok(Self)
+ }
+ }
+
+ let result_origin_for = syn::parse2::(ty.to_token_stream());
+ let result_runtime_origin = syn::parse2::(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`"
} else {
- "Invalid type: expected `OriginFor`"
+ "Invalid type: expected `OriginFor` 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() {
diff --git a/substrate/frame/support/src/dispatch.rs b/substrate/frame/support/src/dispatch.rs
index e57227f9b401e..c81dba127667b 100644
--- a/substrate/frame/support/src/dispatch.rs
+++ b/substrate/frame/support/src/dispatch.rs
@@ -36,7 +36,8 @@ use sp_weights::Weight;
/// returned from a dispatch.
pub type DispatchResultWithPostInfo = sp_runtime::DispatchResultWithInfo;
-/// 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.
diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs
index 2ec3b24db0ce3..fd348f62b4f72 100644
--- a/substrate/frame/support/src/lib.rs
+++ b/substrate/frame/support/src/lib.rs
@@ -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(_);
+ /// # use frame_support::traits::BuildGenesisConfig;
+ /// #[pallet::call]
+ /// impl Pallet {
+ /// pub fn some_dispatchable(_origin: OriginFor, _input: u32) -> DispatchResult {
+ /// Ok(())
+ /// }
+ /// pub fn other(_origin: OriginFor, _input: u64) -> DispatchResult {
+ /// Ok(())
+ /// }
+ /// }
+ ///
+ /// // generates something like:
+ /// // enum Call {
+ /// // 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;
+ /// # }
+ /// 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::::some_dispatchable(origin.clone(), 10);
+ ///
+ /// // calling into a dispatchable from the outer world involves constructing the bytes of
+ /// let call = custom_pallet::Call::::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::::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 Pallet {}
+ /// ```
+ 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(_);
+ /// # use frame_support::traits::BuildGenesisConfig;
+ /// #[pallet::call]
+ /// impl Pallet {
+ /// pub fn some_dispatchable(_origin: OriginFor, #[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
diff --git a/substrate/frame/support/src/migrations.rs b/substrate/frame/support/src/migrations.rs
index a9eb460421f18..bfd62c8611c60 100644
--- a/substrate/frame/support/src/migrations.rs
+++ b/substrate/frame/support/src/migrations.rs
@@ -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<
diff --git a/substrate/frame/support/src/storage/child.rs b/substrate/frame/support/src/storage/child.rs
index e54002d18db3d..76e6f4ee4023e 100644
--- a/substrate/frame/support/src/storage/child.rs
+++ b/substrate/frame/support/src/storage/child.rs
@@ -165,9 +165,9 @@ pub fn kill_storage(child_info: &ChildInfo, limit: Option) -> 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.
diff --git a/substrate/frame/support/src/storage/mod.rs b/substrate/frame/support/src/storage/mod.rs
index 7f39a3fdad85e..c77de1f976f60 100644
--- a/substrate/frame/support/src/storage/mod.rs
+++ b/substrate/frame/support/src/storage/mod.rs
@@ -1583,7 +1583,7 @@ pub trait StorageTryAppend