Update Documentation (#2172)

* timestamp

* balances

* balances-remove-short-example

* system

* sudo (+missing period in balances)

* contract

* staking

* fix unclear definition in balances

* update after review

* update genesis-config-sudo link

Co-Authored-By: joepetrowski <25483142+joepetrowski@users.noreply.github.com>

* genesis
This commit is contained in:
joe petrowski
2019-04-16 15:35:21 +02:00
committed by Bastian Köcher
parent 700e5acf90
commit fc0b348de4
7 changed files with 264 additions and 268 deletions
+49 -77
View File
@@ -16,29 +16,28 @@
//! # Balances Module
//!
//! The balances module provides functionality for handling accounts and balances. To use the balances module, you need
//! to implement the [balances Trait](https://crates.parity.io/srml_balances/trait.Trait.html). Supported dispatchables
//! are documented in the [`Call` enum](https://crates.parity.io/srml_balances/enum.Call.html).
//! The Balances module provides functionality for handling accounts and balances.
//! To use it in your runtime, you need to implement the [`balances::Trait`](./trait.Trait.html).
//! Dispatchable functions are documented as part of the [`Call`](./enum.Call.html) enum.
//!
//! ## Overview
//!
//! The balances module provides functions for:
//! The Balances module provides functions for:
//!
//! - Getting and setting free balances
//! - Retrieving total, reserved and unreserved balances
//! - Repatriating a reserved balance to a beneficiary account that exists
//! - Transferring a balance between accounts (when not reserved)
//! - Slashing an account balance
//! - Account creation and removal
//! - Lookup of an index to reclaim an account
//! - Managing total issuance
//! - Setting and managing locks
//! - Getting and setting free balances.
//! - Retrieving total, reserved and unreserved balances.
//! - Repatriating a reserved balance to a beneficiary account that exists.
//! - Transferring a balance between accounts (when not reserved).
//! - Slashing an account balance.
//! - Account creation and removal.
//! - Managing total issuance.
//! - Setting and managing locks.
//!
//! ### Terminology
//!
//! - **Existential Deposit:** The minimum balance required to create or keep an account open. This prevents
//! "dust accounts" from filling storage.
//! - **Total Issuance:** The total amount of units in existence in a system.
//! - **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 balance is set
//! to zero.
//! - **Free Balance:** The portion of a balance that is not reserved. The free balance is the only balance that matters
@@ -48,8 +47,9 @@
//! can still be slashed, but only after all of free balance has been slashed. If the reserved balance falls below the
//! existential deposit then it and any related functionality will be deleted. When both it and the free balance are
//! deleted, then the account is said to be dead.
//! - **Imbalance:** A condition when some funds were created or deducted without equal and opposite accounting.
//! Functions that result in an imbalance will return an object of the `Imbalance` trait that must be handled.
//! - **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 must be handled.
//! - **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".
//! - **Vesting:** Similar to a lock, this is another, but independent, liquidity restriction that reduces linearly
@@ -57,82 +57,64 @@
//!
//! ### Implementations
//!
//! The balances module provides implementations for the following traits. If these traits provide the functionality
//! that you need, then you can avoid coupling with the balances module.
//! The Balances module provides implementations for the following traits. If these traits provide the functionality
//! that you need, then you can avoid coupling with the Balances module.
//!
//! - [`Currency`](https://crates.parity.io/srml_support/traits/trait.Currency.html): Functions for dealing with a
//! - [`Currency`](../srml_support/traits/trait.Currency.html): Functions for dealing with a
//! fungible assets system.
//! - [`ReservableCurrency`](https://crates.parity.io/srml_support/traits/trait.ReservableCurrency.html):
//! - [`ReservableCurrency`](../srml_support/traits/trait.ReservableCurrency.html):
//! Functions for dealing with assets that can be reserved from an account.
//! - [`LockableCurrency`](https://crates.parity.io/srml_support/traits/trait.LockableCurrency.html): Functions for
//! - [`LockableCurrency`](../srml_support/traits/trait.LockableCurrency.html): Functions for
//! dealing with accounts that allow liquidity restrictions.
//! - [`Imbalance`](https://crates.parity.io/srml_support/traits/trait.Imbalance.html): Functions for handling
//! - [`Imbalance`](../srml_support/traits/trait.Imbalance.html): Functions for handling
//! imbalances between total issuance in the system and account balances. Must be used when a function
//! creates new funds (e.g. a reward) or destroys some funds (e.g. a system fee).
//! - [`MakePayment`](https://crates.parity.io/srml_support/traits/trait.MakePayment.html): Simple trait designed
//! - [`MakePayment`](../srml_support/traits/trait.MakePayment.html): Simple trait designed
//! for hooking into a transaction payment.
//! - [`IsDeadAccount`](https://crates.parity.io/srml_system/trait.IsDeadAccount.html): Determiner to say whether a
//! - [`IsDeadAccount`](../srml_system/trait.IsDeadAccount.html): Determiner to say whether a
//! given account is unused.
//!
//! Example of using the `Currency` trait from the treasury module:
//!
//! ```rust,ignore
//! pub trait Trait: system::Trait {
//! /// The staking balance.
//! type Currency: Currency<Self::AccountId>;
//! }
//! ```
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! The `Call` enum is documented [here](https://crates.parity.io/srml_balances/enum.Call.html).
//!
//! - `transfer` - Transfer some liquid free balance to another account.
//! - `set_balance` - Set the balances of a given account. The origin of this call must be root.
//!
//! See the [`Call`](./enum.Call.html) enum and its associated variants for details of each function.
//!
//! ### Public Functions
//!
//! See the [module](https://crates.parity.io/srml_balances/struct.Module.html) for details on publicly available
//! functions.
//! - `vesting_balance` - Get the amount that is currently being vested and cannot be transferred out of this account.
//!
//! See the [`Module`](./struct.Module.html) struct for details of publicly available functions.
//!
//! ## Usage
//!
//! The following examples show how to use the balances module in your custom module.
//! The following examples show how to use the Balances module in your custom module.
//!
//! ### Import and Balance Transfer
//! ### Example from the SRML
//!
//! Import the `balances` module and derive your module configuration trait with the balances trait. You can now call
//! functions from the module.
//! The Contract module uses the `Currency` trait to handle gas.
//!
//! [(lib.rs)](https://github.com/paritytech/substrate/blob/master/srml/contract/src/lib.rs):
//!
//! ```rust,ignore
//! use support::{decl_module, dispatch::Result};
//! use system::ensure_signed;
//! use srml_support::traits::Currency
//!
//! pub trait Trait: balances::Trait {}
//! pub type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
//! pub type NegativeImbalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
//!```
//!
//! decl_module! {
//! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! fn transfer_proxy(origin, to: T::AccountId, value: T::Balance) -> Result {
//! let sender = ensure_signed(origin)?;
//! <balances::Module<T>>::make_transfer(&sender, &to, value)?;
//!
//! Ok(())
//! }
//! }
//! }
//! ```
//!
//! ### Real Use Example
//!
//! Use in the `contract` module (gas.rs):
//! [(gas.rs)](https://github.com/paritytech/substrate/blob/master/srml/contract/src/gas.rs):
//!
//! ```rust,ignore
//! use srml_support::traits::Currency
//!
//! pub fn refund_unused_gas<T: Trait>(
//! transactor: &T::AccountId,
//! gas_meter: GasMeter<T>,
//! imbalance: balances::NegativeImbalance<T>,
//! imbalance: NegativeImbalanceOf<T>,
//! ) {
//! let gas_spent = gas_meter.spent();
//! let gas_left = gas_meter.gas_left();
@@ -140,10 +122,9 @@
//! // Increase total spent gas.
//! <GasSpent<T>>::mutate(|block_gas_spent| *block_gas_spent += gas_spent);
//!
//! let refund = <T::Gas as As<T::Balance>>::as_(gas_left) * gas_meter.gas_price;
//! // Refund gas using balances module
//! let refund_imbalance = <balances::Module<T>>::deposit_creating(transactor, refund);
//! // Handle imbalance
//! // Refund gas left by the price it was bought at.
//! let refund = <T::Gas as As<BalanceOf<T>>>::as_(gas_left) * gas_meter.gas_price;
//! let refund_imbalance = T::Currency::deposit_creating(transactor, refund);
//! if let Ok(imbalance) = imbalance.offset(refund_imbalance) {
//! T::GasPayment::on_unbalanced(imbalance);
//! }
@@ -152,22 +133,13 @@
//!
//! ## Genesis config
//!
//! The following storage items depend on the genesis config:
//!
//! - `TotalIssuance`
//! - `ExistentialDeposit`
//! - `TransferFee`
//! - `CreationFee`
//! - `Vesting`
//! - `FreeBalance`
//! - `TransactionBaseFee`
//! - `TransactionByteFee`
//! The Balances module depends on the genesis configuration. See the [`GenesisConfig`](./struct.GenesisConfig.html)
//! struct for a list of attributes that can be provided.
//!
//! ## Related Modules
//!
//! The balances module depends on the [`system`](https://crates.parity.io/srml_system/index.html) and
//! [`srml_support`](https://crates.parity.io/srml_support/index.html) modules as well as Substrate Core
//! libraries and the Rust standard library.
//! - [`system`](../srml_system/index.html)
//! - [`srml_support`](../srml_support/index.html)
#![cfg_attr(not(feature = "std"), no_std)]
+1 -1
View File
@@ -247,7 +247,7 @@ pub fn refund_unused_gas<T: Trait>(
// also has T::Gas type.
<GasSpent<T>>::mutate(|block_gas_spent| *block_gas_spent += gas_spent);
// Refund gas left by the price it was bought.
// Refund gas left by the price it was bought at.
let refund = <T::Gas as As<BalanceOf<T>>>::as_(gas_left) * gas_meter.gas_price;
let refund_imbalance = T::Currency::deposit_creating(transactor, refund);
if let Ok(imbalance) = imbalance.offset(refund_imbalance) {
+47 -49
View File
@@ -16,14 +16,14 @@
//! # Contract Module
//!
//! The contract module provides functionality for the runtime to deploy and execute WebAssembly smart-contracts.
//! The supported dispatchable functions are documented as part of the [`Call`](./enum.Call.html) enum.
//! The Contract module provides functionality for the runtime to deploy and execute WebAssembly smart-contracts.
//! To use it in your runtime, you need to implement the [`contracts::Trait`](./trait.Trait.html).
//!
//! ## Overview
//!
//! This module extends accounts (see `Balances` module) to have smart-contract functionality.
//! These "smart-contract accounts" have the ability to create smart-contracts and make calls to other contract
//! and non-contract accounts.
//! This module extends accounts based on the `Currency` trait to have smart-contract functionality. It can
//! be used with other modules that implement accounts based on `Currency`. These "smart-contract accounts"
//! have the ability to create smart-contracts and make calls to other contract and non-contract accounts.
//!
//! The smart-contract code is stored once in a `code_cache`, and later retrievable via its `code_hash`.
//! This means that multiple smart-contracts can be instantiated from the same `code_cache`, without replicating
@@ -33,9 +33,8 @@
//! This call can alter the storage entries of the smart-contract account, create new smart-contracts,
//! or call other smart-contracts.
//!
//! Finally, when the `Balances` module determines an account is dead (i.e. account balance fell below the
//! existential deposit), it reaps the account. This will delete the associated code and storage of the
//! smart-contract account.
//! Finally, when an account is reaped, its associated code and storage of the smart-contract account
//! will also be deleted.
//!
//! ### Gas
//!
@@ -57,28 +56,28 @@
//!
//! ### Dispatchable functions
//!
//! * `put_code` - Stores the given binary Wasm code into the chains storage and returns its `code_hash`.
//!
//! * `put_code` - Stores the given binary Wasm code into the chain's storage and returns its `code_hash`.
//! * `create` - Deploys a new contract from the given `code_hash`, optionally transferring some balance.
//! This creates a new smart contract account and calls its contract deploy handler to initialize the contract.
//!
//! * `call` - Makes a call to an account, optionally transferring some balance.
//!
//! See the [`Call`](./enum.Call.html) enum and its associated variants for details of each function.
//!
//! ### Public functions
//!
//! See the [module](./struct.Module.html) for details on publicly available functions.
//! See the [`Module`](./struct.Module.html) struct for details on publicly available functions.
//!
//! ## Usage
//!
//! The contract module is a work in progress. The following examples show how this contract module can be
//! The Contract module is a work in progress. The following examples show how this Contract module can be
//! used to create and call contracts.
//!
//! * [`pDSL`](https://github.com/Robbepop/pdsl) is a domain specific language which enables writing
//! * [`pDSL`](https://github.com/Robbepop/pdsl) is a domain specific language that enables writing
//! WebAssembly based smart contracts in the Rust programming language. This is a work in progress.
//!
//! ## Related Modules
//! * [`Balances`](https://crates.parity.io/srml_balances/index.html)
//!
//! * [`Balances`](../srml_balances/index.html)
#![cfg_attr(not(feature = "std"), no_std)]
@@ -122,38 +121,38 @@ pub trait ComputeDispatchFee<Call, Balance> {
}
#[derive(Encode,Decode,Clone,Debug)]
/// Information for managing an acocunt and its sub trie abstraction.
/// This is the required info to cache for an account
/// Information for managing an account and its sub trie abstraction.
/// This is the required info to cache for an account.
pub struct AccountInfo {
/// unique ID for the subtree encoded as a byte
/// Unique ID for the subtree encoded as a byte.
pub trie_id: TrieId,
/// the size of stored value in octet
/// The size of stored value in octet.
pub storage_size: u64,
}
/// Get a trie id (trie id must be unique and collision resistant depending upon its context)
/// Note that it is different than encode because trie id should have collision resistance
/// property (being a proper uniqueid).
/// Get a trie id (trie id must be unique and collision resistant depending upon its context).
/// Note that it is different than encode because trie id should be collision resistant
/// (being a proper unique identifier).
pub trait TrieIdGenerator<AccountId> {
/// get a trie id for an account, using reference to parent account trie id to ensure
/// uniqueness of trie id
/// The implementation must ensure every new trie id is unique: two consecutive call with the
/// Get a trie id for an account, using reference to parent account trie id to ensure
/// uniqueness of trie id.
/// The implementation must ensure every new trie id is unique: two consecutive calls with the
/// same parameter needs to return different trie id values.
fn trie_id(account_id: &AccountId) -> TrieId;
}
/// Get trie id from `account_id`
/// Get trie id from `account_id`.
pub struct TrieIdFromParentCounter<T: Trait>(PhantomData<T>);
/// This generator use inner counter for account id and apply hash over `AccountId +
/// accountid_counter`
/// This generator uses inner counter for account id and applies the hash over `AccountId +
/// accountid_counter`.
impl<T: Trait> TrieIdGenerator<T::AccountId> for TrieIdFromParentCounter<T>
where
T::AccountId: AsRef<[u8]>
{
fn trie_id(account_id: &T::AccountId) -> TrieId {
// note that skipping a value due to error is not an issue here.
// we only need uniqueness, not sequence.
// Note that skipping a value due to error is not an issue here.
// We only need uniqueness, not sequence.
let new_seed = <AccountCounter<T>>::mutate(|v| v.wrapping_add(1));
let mut buf = Vec::new();
@@ -175,7 +174,7 @@ pub trait Trait: timestamp::Trait {
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
// As<u32> is needed for wasm-utils
// `As<u32>` is needed for wasm-utils
type Gas: Parameter + Default + Codec + SimpleArithmetic + Bounded + Copy + As<BalanceOf<Self>> + As<u64> + As<u32>;
/// A function type to get the contract address given the creator.
@@ -184,7 +183,7 @@ pub trait Trait: timestamp::Trait {
/// A function type that computes the fee for dispatching the given `Call`.
///
/// It is recommended (though not required) for this function to return a fee that would be taken
/// by executive module for regular dispatch.
/// by the Executive module for regular dispatch.
type ComputeDispatchFee: ComputeDispatchFee<Self::Call, BalanceOf<Self>>;
/// trieid id generator
@@ -194,10 +193,10 @@ pub trait Trait: timestamp::Trait {
type GasPayment: OnUnbalanced<NegativeImbalanceOf<Self>>;
}
/// Simple contract address determintator.
/// Simple contract address determiner.
///
/// Address calculated from the code (of the constructor), input data to the constructor
/// and account id which requested the account creation.
/// Address calculated from the code (of the constructor), input data to the constructor,
/// and the account id that requested the account creation.
///
/// Formula: `blake2_256(blake2_256(code) + blake2_256(data) + origin)`
pub struct SimpleAddressDeterminator<T: Trait>(PhantomData<T>);
@@ -218,7 +217,7 @@ where
}
/// The default dispatch fee computor computes the fee in the same way that
/// implementation of `MakePayment` for balances module does.
/// the implementation of `MakePayment` for the Balances module does.
pub struct DefaultDispatchFeeComputor<T: Trait>(PhantomData<T>);
impl<T: Trait> ComputeDispatchFee<T::Call, BalanceOf<T>> for DefaultDispatchFeeComputor<T> {
fn compute_dispatch_fee(call: &T::Call) -> BalanceOf<T> {
@@ -248,7 +247,7 @@ decl_module! {
Ok(())
}
/// Stores the given binary Wasm code into the chains storage and returns its `codehash`.
/// Stores the given binary Wasm code into the chain's storage and returns its `codehash`.
/// You can instantiate contracts only with stored code.
fn put_code(
origin,
@@ -310,7 +309,7 @@ decl_module! {
// Refund cost of the unused gas.
//
// NOTE: this should go after the commit to the storage, since the storage changes
// NOTE: This should go after the commit to the storage, since the storage changes
// can alter the balance of the caller.
gas::refund_unused_gas::<T>(&origin, gas_meter, imbalance);
@@ -327,9 +326,9 @@ decl_module! {
///
/// Creation is executed as follows:
///
/// - the destination address is computed based on the sender and hash of the code.
/// - the smart-contract account is created at the computed address.
/// - the `ctor_code` is executed in the context of the newly created account. Buffer returned
/// - The destination address is computed based on the sender and hash of the code.
/// - The smart-contract account is created at the computed address.
/// - The `ctor_code` is executed in the context of the newly-created account. Buffer returned
/// after the execution is saved as the `code` of the account. That code will be invoked
/// upon any call received by this account.
/// - The contract is initialized.
@@ -344,7 +343,7 @@ decl_module! {
// Commit the gas upfront.
//
// NOTE: it is very important to avoid any state changes before
// NOTE: It is very important to avoid any state changes before
// paying for the gas.
let (mut gas_meter, imbalance) = gas::buy_gas::<T>(&origin, gas_limit)?;
@@ -364,7 +363,7 @@ decl_module! {
// Refund cost of the unused gas.
//
// NOTE: this should go after the commit to the storage, since the storage changes
// NOTE: This should go after the commit to the storage, since the storage changes
// can alter the balance of the caller.
gas::refund_unused_gas::<T>(&origin, gas_meter, imbalance);
@@ -441,9 +440,9 @@ decl_storage! {
pub CodeHashOf: map T::AccountId => Option<CodeHash<T>>;
/// A mapping from an original code hash to the original code, untouched by instrumentation.
pub PristineCode: map CodeHash<T> => Option<Vec<u8>>;
/// A mapping between an original code hash and instrumented wasm code, ready for the execution.
/// A mapping between an original code hash and instrumented wasm code, ready for execution.
pub CodeStorage: map CodeHash<T> => Option<wasm::PrefabWasmModule>;
/// The subtrie counter
/// The subtrie counter.
pub AccountCounter: u64 = 0;
/// The code associated with a given account.
pub AccountInfoOf: map T::AccountId => Option<AccountInfo>;
@@ -494,7 +493,7 @@ pub struct Schedule<Gas> {
/// Version of the schedule.
pub version: u32,
/// Cost of putting a byte of code into the storage.
/// Cost of putting a byte of code into storage.
pub put_code_per_byte_cost: Gas,
/// Gas cost of a growing memory by single page.
@@ -518,14 +517,13 @@ pub struct Schedule<Gas> {
/// Gas cost per one byte written to the sandbox memory.
pub sandbox_data_write_cost: Gas,
/// How tall the stack is allowed to grow?
/// Maximum allowed stack height.
///
/// See https://wiki.parity.io/WebAssembly-StackHeight to find out
/// how the stack frame cost is calculated.
pub max_stack_height: u32,
/// What is the maximal memory pages amount is allowed to have for
/// a contract.
/// Maximum number of memory pages allowed for a contract.
pub max_memory_pages: u32,
/// Whether the `ext_println` function is allowed to be used contracts.
+106 -86
View File
@@ -17,51 +17,57 @@
//! # Staking Module
//! <!-- Original author of paragraph: @gavofyork -->
//!
//! The staking module is the means by which a set of network maintainers (known as _authorities_ in some contexts and _validators_ in others)
//! are chosen based upon those who voluntarily place funds under deposit. Under deposit, those funds are rewarded under
//! normal operation but are held at pain of _slash_ (expropriation) should the staked maintainer be found not to be
//! discharging their duties properly.
//! The Staking module is the means by which a set of network maintainers (known as _authorities_ in some contexts
//! and _validators_ in others) are chosen based upon those who voluntarily place funds under deposit. Under deposit,
//! those funds are rewarded under normal operation but are held at pain of _slash_ (expropriation) should the
//! staked maintainer be found not to be discharging its duties properly.
//!
//! You can start using the Staking module by implementing the staking [`Trait`].
//! To use the Staking module in your runtime, you need to implement the [`staking::Trait`](./trait.Trait.html).
//!
//! ## Overview
//!
//! ### Terminology
//! <!-- Original author of paragraph: @gavofyork -->
//!
//! - Staking: The process of locking up funds for some time, placing them at risk of slashing (loss) in order to become a rewarded maintainer of the network.
//! - Validating: The process of running a node to actively maintain the network, either by producing blocks or guaranteeing finality of the chain.
//! - Nominating: The process of placing staked funds behind one or more validators in order to share in any reward, and punishment, they take.
//! - Staking: The process of locking up funds for some time, placing them at risk of slashing (loss)
//! in order to become a rewarded maintainer of the network.
//! - Validating: The process of running a node to actively maintain the network, either by producing
//! blocks or guaranteeing finality of the chain.
//! - Nominating: The process of placing staked funds behind one or more validators in order to share
//! in any reward, and punishment, they take.
//! - Stash account: The account holding an owner's funds used for staking.
//! - Controller account: The account which controls an owner's funds for staking.
//! - Era: A (whole) number of sessions, which is the period that the validator set (and each validator's active nominator set) is recalculated and where rewards are paid out.
//! - Slash: The punishment of a staker by reducing their funds.
//! - Controller account: The account that controls an owner's funds for staking.
//! - Era: A (whole) number of sessions, which is the period that the validator set (and each validator's
//! active nominator set) is recalculated and where rewards are paid out.
//! - Slash: The punishment of a staker by reducing its funds.
//!
//! ### Goals
//! <!-- Original author of paragraph: @gavofyork -->
//!
//! The staking system in Substrate NPoS is designed to achieve three goals:
//! The staking system in Substrate NPoS is designed to make the following possible:
//!
//! - It should be possible to stake funds that are controlled by a cold wallet.
//! - It should be possible to withdraw some, or deposit more, funds without interrupting the role of an entity.
//! - It should be possible to switch between roles (nominator, validator, idle) with minimal overhead.
//! - Stake funds that are controlled by a cold wallet.
//! - Withdraw some, or deposit more, funds without interrupting the role of an entity.
//! - Switch between roles (nominator, validator, idle) with minimal overhead.
//!
//! ### Scenarios
//!
//! #### Staking
//!
//! Almost any interaction with the staking module requires a process of _**bonding**_ (also known as
//! being a _staker_). To become *bonded* a fund-holding account known as the _stash account_, which holds some of all of the
//! funds that become frozen in place as part of the staking process, is paired with an active **controller** account which issues
//! instructions on how they shall be used.
//! Almost any interaction with the Staking module requires a process of _**bonding**_ (also known as
//! being a _staker_). To become *bonded*, a fund-holding account known as the _stash account_, which holds
//! some or all of the funds that become frozen in place as part of the staking process, is paired with an
//! active **controller** account, which issues instructions on how they shall be used.
//!
//! An account pair can become bonded using the [`bond`](./enum.Call.html#variant.bond) call.
//!
//! Stash accounts can change their associated controller using the [`set_controller`](./enum.Call.html#variant.set_controller) call.
//! Stash accounts can change their associated controller using the
//! [`set_controller`](./enum.Call.html#variant.set_controller) call.
//!
//! There are three possible roles that any staked account pair can be in: `Validator`, `Nominator` and `Idle` (defined in [`StakerStatus`]). There are
//! three corresponding instructions to change between roles, namely:
//! [`validate`](./enum.Call.html#variant.validate), [`nominate`](./enum.Call.html#variant.nominate) and [`chill`](./enum.Call.html#variant.chill).
//! There are three possible roles that any staked account pair can be in: `Validator`, `Nominator` and `Idle`
//! (defined in [`StakerStatus`](./enum.StakerStatus.html)). There are three corresponding instructions to change between roles, namely:
//! [`validate`](./enum.Call.html#variant.validate), [`nominate`](./enum.Call.html#variant.nominate),
//! and [`chill`](./enum.Call.html#variant.chill).
//!
//! #### Validating
//!
@@ -86,15 +92,16 @@
//!
//! #### Rewards and Slash
//!
//! The **reward and slashing** procedure is the core of the staking module, attempting to _embrace valid behavior_
//! The **reward and slashing** procedure is the core of the Staking module, attempting to _embrace valid behavior_
//! while _punishing any misbehavior or lack of availability_.
//!
//! Slashing can occur at any point in time, once misbehavior is reported. Once slashing is determined, a value is
//! deducted from the balance of the validator and all the nominators who voted for this validator (values are deducted from the _stash_ account of the slashed entity).
//! deducted from the balance of the validator and all the nominators who voted for this validator
//! (values are deducted from the _stash_ account of the slashed entity).
//!
//! Similar to slashing, rewards are also shared among a validator and its associated nominators.
//! Yet, the reward funds are not always transferred to the stash account and can be configured. See [Reward Calculation](#reward-calculation)
//! for more details.
//! Yet, the reward funds are not always transferred to the stash account and can be configured.
//! See [Reward Calculation](#reward-calculation) for more details.
//!
//! #### Chilling
//!
@@ -106,43 +113,44 @@
//!
//! ## Interface
//!
//! ### Dispatchable
//! ### Dispatchable Functions
//!
//! The Dispatchable functions of the staking module enable the steps needed for entities to accept and change their
//! The dispatchable functions of the Staking module enable the steps needed for entities to accept and change their
//! role, alongside some helper functions to get/set the metadata of the module.
//!
//! Please refer to the [`Call`] enum and its associated variants for a detailed list of dispatchable functions.
//! See the [`Call`](./enum.Call.html) enum and its associated variants for details of each function.
//!
//! ### Public
//! The staking module contains many public storage items and (im)mutable functions. Please refer to the [struct list](#structs)
//! below and the [`Module`] struct definition for more details.
//! ### Public Functions
//!
//! The Staking module contains many public storage items and (im)mutable functions. Please refer to the
//! [struct list](#structs) below and the [`Module`](./struct.Module.html) struct definition for more details.
//!
//! ## Usage
//!
//!
//! ### Snippet: Bonding and Accepting Roles
//!
//! An arbitrary account pair, given that the associated stash has the required funds, can become stakers via the following call:
//! An arbitrary account pair, given that the associated stash has the required funds,
//! can become stakers via the following call:
//!
//! ```rust,ignore
//! // bond account 3 as stash
//! // account 4 as controller
//! // with stash value 1500 units
//! // while the rewards get transferred to the controller account.
//! // Bond account 3 as stash.
//! // Account 4 as controller.
//! // Stash value of 1500 units.
//! // Rewards get transferred to the controller account.
//! Staking::bond(Origin::signed(3), 4, 1500, RewardDestination::Controller);
//! ```
//!
//! To state desire to become a validator:
//!
//! ```rust,ignore
//! // controller account 4 states desire for validation with the given preferences.
//! // Controller account 4 states desire for validation with the given preferences.
//! Staking::validate(Origin::signed(4), ValidatorPrefs::default());
//! ```
//!
//! Similarly, to state desire in nominating:
//!
//! ```rust,ignore
//! // controller account 4 nominates for account 10 and 20.
//! // Controller account 4 nominates for accounts 10 and 20.
//! Staking::nominate(Origin::signed(4), vec![20, 10]);
//! ```
//!
@@ -153,6 +161,7 @@
//! ```
//!
//! You can find the equivalent of the above calls in your [Substrate UI](https://substrate-ui.parity.io).
//!
//! ### Snippet: Reporting Misbehavior
//!
//! ```
@@ -179,26 +188,30 @@
//!
//! ### Slot Stake
//!
//! The term [`SlotStake`] will be used throughout this section. It refers to a value calculated at the end of each era,
//! containing the _minimum value at stake among all validators._ Note that a validator's value at stake might be a combination of
//! The validator's own stake and the votes it received. See [`Exposure`] for more details.
//! The term [`SlotStake`](./struct.Module.html#method.slot_stake) will be used throughout this section. It refers
//! to a value calculated at the end of each era, containing the _minimum value at stake among all validators._
//! Note that a validator's value at stake might be a combination of The validator's own stake
//! and the votes it received. See [`Exposure`](./struct.Exposure.html) for more details.
//!
//! ### Reward Calculation
//!
//! Rewards are recorded **per-session** and paid **per-era**. The value of the reward for each session is calculated at
//! the end of the session based on the timeliness of the session, then accumulated to be paid later. The value of
//! the new _per-session-reward_ is calculated at the end of each era by multiplying [`SlotStake`] and [`SessionReward`]
//! the new _per-session-reward_ is calculated at the end of each era by multiplying `SlotStake` and `SessionReward`
//! (`SessionReward` is the multiplication factor, represented by a number between 0 and 1).
//! Once a new era is triggered, rewards are paid to the validators and the associated nominators.
//! Once a new era is triggered, rewards are paid to the validators and their associated nominators.
//!
//! The validator can declare an amount, named [`validator_payment`](./struct.ValidatorPrefs.html#structfield.validator_payment), that does not get shared with the nominators at
//! each reward payout through their [`ValidatorPrefs`]. This value gets deducted from the total reward that can be paid.
//! The remaining portion is split among the validator and all of the nominators that nominated the validator,
//! proportional to the value staked behind this validator
//! (_i.e._ dividing the [`own`](./struct.Exposure.html#structfield.own) or [`others`](./struct.Exposure.html#structfield.others) by [`total`](./struct.Exposure.html#structfield.total) in [`Exposure`]).
//! The validator can declare an amount, named
//! [`validator_payment`](./struct.ValidatorPrefs.html#structfield.validator_payment), that does not get shared
//! with the nominators at each reward payout through its [`ValidatorPrefs`](./struct.ValidatorPrefs.html). This value
//! gets deducted from the total reward that can be paid. The remaining portion is split among the validator and all
//! of the nominators that nominated the validator, proportional to the value staked behind this validator (_i.e._
//! dividing the [`own`](./struct.Exposure.html#structfield.own) or [`others`](./struct.Exposure.html#structfield.others)
//! by [`total`](./struct.Exposure.html#structfield.total) in [`Exposure`](./struct.Exposure.html)).
//!
//! All entities who receive a reward have the option to choose their reward destination,
//! through the [`Payee`] storage item (see [`set_payee`](enum.Call.html#variant.set_payee)), to be one of the following:
//! All entities who receive a reward have the option to choose their reward destination
//! through the [`Payee`](./struct.Payee.html) storage item (see [`set_payee`](enum.Call.html#variant.set_payee)),
//! to be one of the following:
//!
//! - Controller account, (obviously) not increasing the staked value.
//! - Stash account, not increasing the staked value.
@@ -206,49 +219,56 @@
//!
//! ### Slashing details
//!
//! A validator can be _reported_ to be offline at any point via [`on_offline_validator`](enum.Call.html#variant.on_offline_validator) public function.
//! Each validator declares how many times it can be _reported_ before it actually gets slashed via their
//! `unstake_threshold` in [`ValidatorPrefs`].
//! A validator can be _reported_ to be offline at any point via the public function
//! [`on_offline_validator`](enum.Call.html#variant.on_offline_validator). Each validator declares how many times it
//! can be _reported_ before it actually gets slashed via its
//! [`unstake_threshold`](./struct.ValidatorPrefs.html#structfield.unstake_threshold).
//!
//! On top of this, staking module also introduces an [`OfflineSlashGrace`], which applies to all validators and prevents
//! them from getting immediately slashed.
//! On top of this, the Staking module also introduces an
//! [`OfflineSlashGrace`](./struct.Module.html#method.offline_slash_grace), which applies
//! to all validators and prevents them from getting immediately slashed.
//!
//! Essentially, a validator gets slashed once they have been reported more than [`OfflineSlashGrace`] + [`unstake_threshold`](./struct.ValidatorPrefs.html#structfield.unstake_threshold) times.
//! Getting slashed due to offline report always leads to being _unstaked_ (_i.e._ removed as a validator candidate) as the consequence.
//! Essentially, a validator gets slashed once they have been reported more than
//! [`OfflineSlashGrace`] + [`unstake_threshold`] times. Getting slashed due to offline report always leads
//! to being _unstaked_ (_i.e._ removed as a validator candidate) as the consequence.
//!
//! The base slash value is computed _per slash-event_ by multiplying [`OfflineSlash`] and the `total` [`Exposure`]. This value
//! is then multiplied by `2.pow(unstake_threshold)` to obtain the final slash value.
//! All individual accounts' punishments are capped at their total stake (NOTE: This cap should never come into force in a correctly implemented, non-corrupted, well-configured system).
//! The base slash value is computed _per slash-event_ by multiplying
//! [`OfflineSlash`](./struct.Module.html#method.offline_slash) and the `total` `Exposure`. This value is then
//! multiplied by `2.pow(unstake_threshold)` to obtain the final slash value. All individual accounts' punishments are
//! capped at their total stake (NOTE: This cap should never come into force in a correctly implemented,
//! non-corrupted, well-configured system).
//!
//! ### Additional Fund Management Operations
//!
//! Any funds already placed into stash can be the target of the following operations:
//!
//! The controller account can free a portion (or all) of the funds using the [`unbond`](enum.Call.html#variant.unbond) call.
//! Note that the funds are not immediately accessible. Instead, a duration denoted by [`BondingDuration`] (in number of eras)
//! must pass until the funds can actually be removed. Once the [`BondingDuration`] is over the [`withdraw_unbonded`]((enum.Call.html#variant.withdraw_unbonded)) call can be used
//! The controller account can free a portion (or all) of the funds using the [`unbond`](enum.Call.html#variant.unbond)
//! call. Note that the funds are not immediately accessible. Instead, a duration denoted by
//! [`BondingDuration`](./struct.BondingDuration.html) (in number of eras) must pass until the funds can actually be
//! removed. Once the `BondingDuration` is over, the [`withdraw_unbonded`](./enum.Call.html#variant.withdraw_unbonded) call can be used
//! to actually withdraw the funds.
//!
//!### Election Algorithm
//! ### Election Algorithm
//!
//! The current election algorithm is implemented based on Phragmén.
//! The reference implementation can be found [here](https://github.com/w3f/consensus/tree/master/NPoS).
//!
//! The election algorithm, aside from electing the validators with the most stake value and votes, tries to divide the nominator votes
//! among candidates in an equal manner. To further assure this, an optional post-processing can be applied that iteratively normalizes the nominator staked values
//! until the total difference among votes of a particular nominator are less than a threshold.
//!
//! The election algorithm, aside from electing the validators with the most stake value and votes, tries to divide
//! the nominator votes among candidates in an equal manner. To further assure this, an optional post-processing
//! can be applied that iteractively normalizes the nominator staked values until the total difference among
//! votes of a particular nominator are less than a threshold.
//!
//! ## GenesisConfig
//!
//! See the [`GenesisConfig`] for a list of attributes that can be provided.
//! The Staking module depends on the genesis configuration. See the [`GenesisConfig`](./struct.GenesisConfig.html)
//! struct for a list of attributes that can be provided.
//!
//! ## Related Modules
//!
//! - [**Balances**](https://crates.parity.io/srml_balances/index.html): Used to manage values at stake.
//! - [**Sessions**](https://crates.parity.io/srml_session/index.html): Used to manage sessions. Also, a list of new validators is also stored in the sessions module's `Validators` at the end of each era.
//! - [**System**](https://crates.parity.io/srml_system/index.html): Used to obtain block number and time, among other details.
//!
//! - [**Balances**](../srml_balances/index.html): Used to manage values at stake.
//! - [**Session**](../srml_session/index.html): Used to manage sessions. Also, a list of new validators is
//! stored in the Session module's `Validators` at the end of each era.
//! - [**System**](../srml_system/index.html): Used to obtain block number and time, among other details.
#![cfg_attr(not(feature = "std"), no_std)]
@@ -471,7 +491,7 @@ decl_storage! {
pub Nominators get(nominators): linked_map T::AccountId => Vec<T::AccountId>;
/// Nominators for a particular account that is in action right now. You can't iterate through validators here,
/// but you can find them in the `sessions` module.
/// but you can find them in the Session module.
///
/// This is keyed by the stash account.
pub Stakers get(stakers): map T::AccountId => Exposure<T::AccountId, BalanceOf<T>>;
@@ -515,7 +535,7 @@ decl_storage! {
/// We are forcing a new era.
pub ForcingNewEra get(forcing_new_era): Option<()>;
/// Most recent `RECENT_OFFLINE_COUNT` instances. (who it was, when it was reported, how many instances they were offline for).
/// Most recent `RECENT_OFFLINE_COUNT` instances. (Who it was, when it was reported, how many instances they were offline for).
pub RecentlyOffline get(recently_offline): Vec<(T::AccountId, T::BlockNumber, u32)>;
}
add_extra_genesis {
@@ -763,16 +783,16 @@ decl_event!(
pub enum Event<T> where Balance = BalanceOf<T>, <T as system::Trait>::AccountId {
/// All validators have been rewarded by the given balance.
Reward(Balance),
/// One validator (and their nominators) has been given a offline-warning (they're still
/// within their grace). The accrued number of slashes is recorded, too.
/// One validator (and its nominators) has been given an offline-warning (it is still
/// within its grace). The accrued number of slashes is recorded, too.
OfflineWarning(AccountId, u32),
/// One validator (and their nominators) has been slashed by the given amount.
/// One validator (and its nominators) has been slashed by the given amount.
OfflineSlash(AccountId, Balance),
}
);
impl<T: Trait> Module<T> {
// Just force_new_era without origin check.
/// Just force_new_era without origin check.
fn apply_force_new_era(apply_rewards: bool) -> Result {
<ForcingNewEra<T>>::put(());
<session::Module<T>>::apply_force_new_session(apply_rewards)
@@ -799,12 +819,12 @@ impl<T: Trait> Module<T> {
<Ledger<T>>::insert(controller, ledger);
}
/// Slash a given validator by a specific amount. Removes the slash from their balance by preference,
/// Slash a given validator by a specific amount. Removes the slash from the validator's balance by preference,
/// and reduces the nominators' balance if needed.
fn slash_validator(stash: &T::AccountId, slash: BalanceOf<T>) {
// The exposure (backing stake) information of the validator to be slashed.
let exposure = Self::stakers(stash);
// The amount we are actually going to slash (can't be bigger than their total exposure)
// The amount we are actually going to slash (can't be bigger than the validator's total exposure)
let slash = slash.min(exposure.total);
// The amount we'll slash from the validator's stash directly.
let own_slash = exposure.own.min(slash);
@@ -849,7 +869,7 @@ impl<T: Trait> Module<T> {
}
}
/// Reward a given validator by a specific amount. Add the reward to their, and their nominators'
/// Reward a given validator by a specific amount. Add the reward to the validator's, and its nominators'
/// balance, pro-rata based on their exposure, after having removed the validator's pre-payout cut.
fn reward_validator(stash: &T::AccountId, reward: BalanceOf<T>) {
let off_the_table = reward.min(Self::validators(stash).validator_payment);
@@ -940,7 +960,7 @@ impl<T: Trait> Module<T> {
/// Select a new validator set from the assembled stakers and their role preferences.
///
/// Returns the new SlotStake value.
/// Returns the new `SlotStake` value.
fn select_validators() -> BalanceOf<T> {
let maybe_elected_candidates = elect::<T, _, _, _>(
Self::validator_count() as usize,
+10 -11
View File
@@ -18,31 +18,29 @@
//!
//! ## Overview
//!
//! The sudo module allows for a single account (called the "sudo key")
//! The Sudo module allows for a single account (called the "sudo key")
//! to execute dispatchable functions that require a `Root` call
//! or designate a new account to replace them as the sudo key.
//! Only one account can be the sudo key at a time.
//!
//! You can start using the sudo module by implementing the sudo [`Trait`].
//!
//! Supported dispatchable functions are documented in the [`Call`] enum.
//! You can start using the Sudo module by implementing the [`sudo::Trait`](./trait.Trait.html).
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! Only the sudo key can call the dispatchable functions from the sudo module.
//! Only the sudo key can call the dispatchable functions from the Sudo module.
//!
//! * `sudo` - Make a `Root` call to a dispatchable function.
//! * `set_key` - Assign a new account to be the sudo key.
//!
//! Please refer to the [`Call`] enum and its associated variants for documentation on each function.
//! See the [`Call`](./enum.Call.html) enum and its associated variants for details of each function.
//!
//! ## Usage
//!
//! ### Prerequisites
//!
//! To use the sudo module in your runtime, you must implement the following trait in your runtime:
//! To use the Sudo module in your runtime, you must implement the following trait in your runtime:
//!
//! ```ignore
//! impl sudo::Trait for Runtime {
@@ -59,8 +57,8 @@
//!
//! ### Executing Privileged Functions
//!
//! The sudo module itself is not intended to be used within other modules.
//! Instead, you can build "privileged functions" in other modules that require `Root` origin.
//! The Sudo module itself is not intended to be used within other modules.
//! Instead, you can build "privileged functions" (i.e. functions that require `Root` origin) in other modules.
//! You can execute these privileged functions by calling `sudo` with the sudo key account.
//! Privileged functions cannot be directly executed via an extrinsic.
//!
@@ -91,7 +89,7 @@
//!
//! ### Example from SRML
//!
//! The consensus module exposes a `set_code` privileged function
//! The Consensus module exposes a `set_code` privileged function
//! that allows you to set the on-chain Wasm runtime code:
//!
//! ```ignore
@@ -103,7 +101,8 @@
//!
//! ## Genesis Config
//!
//! To use the sudo module, you need to set an initial superuser account as the sudo `key`.
//! The Sudo module depends on the [`GenesisConfig`](./struct.GenesisConfig.html).
//! You need to set an initial superuser account as the sudo `key`.
//!
//! ```ignore
//! GenesisConfig {
+26 -26
View File
@@ -14,38 +14,38 @@
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! # System module
//! # System Module
//!
//! The system module provides low-level access to core types and cross-cutting utilities.
//! The System module provides low-level access to core types and cross-cutting utilities.
//! It acts as the base layer for other SRML modules to interact with the Substrate framework components.
//! To use it in your module, you should ensure your module's trait implies the system [`Trait`].
//! To use it in your module, you need to implement the [`system::Trait`](./trait.Trait.html).
//!
//! ## Overview
//!
//! The system module defines the core data types used in a Substrate runtime.
//! It also provides several utility functions (see [`Module`]) for other runtime modules.
//! The System module defines the core data types used in a Substrate runtime.
//! It also provides several utility functions (see [`Module`](./struct.Module.html)) for other runtime modules.
//!
//! In addition, it manages the storage items for extrinsics data, indexes, event record and digest items,
//! In addition, it manages the storage items for extrinsics data, indexes, event records, and digest items,
//! among other things that support the execution of the current block.
//!
//! It also handles low level tasks like depositing logs, basic set up and take down of
//! temporary storage entries and access to previous block hashes.
//! It also handles low-level tasks like depositing logs, basic set up and take down of
//! temporary storage entries, and access to previous block hashes.
//!
//! ## Interface
//!
//! ### Dispatchable functions
//! ### Dispatchable Functions
//!
//! The system module does not implement any dispatchable functions.
//! The System module does not implement any dispatchable functions.
//!
//! ### Public functions
//! ### Public Functions
//!
//! All public functions are available as part of the [`Module`] type.
//! See the [`Module`](./struct.Module.html) struct for details of publicly available functions.
//!
//! ## Usage
//!
//! ### Prerequisites
//!
//! Import the system module and derive your module's configuration trait from the system trait.
//! Import the System module and derive your module's configuration trait from the system trait.
//!
//! ### Example - Get random seed and extrinsic count for the current block
//!
@@ -99,7 +99,7 @@ impl<AccountId> OnNewAccount<AccountId> for () {
fn on_new_account(_who: &AccountId) {}
}
/// Determinator to say whether a given account is unused.
/// Determiner to say whether a given account is unused.
pub trait IsDeadAccount<AccountId> {
/// Is the given account dead?
fn is_dead_account(who: &AccountId) -> bool;
@@ -168,7 +168,7 @@ pub trait Trait: 'static + Eq + Clone {
/// The aggregated event type of the runtime.
type Event: Parameter + Member + From<Event>;
/// A piece of information which can be part of the digest (as a digest item).
/// A piece of information that can be part of the digest (as a digest item).
type Log: From<Log<Self>> + Into<DigestItemOf<Self>>;
}
@@ -176,7 +176,7 @@ pub type DigestItemOf<T> = <<T as Trait>::Digest as traits::Digest>::Item;
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// Deposits an event onto this block's event record.
/// Deposits an event into this block's event record.
pub fn deposit_event(event: T::Event) {
let extrinsic_index = Self::extrinsic_index();
let phase = extrinsic_index.map_or(Phase::Finalization, |c| Phase::ApplyExtrinsic(c));
@@ -215,7 +215,7 @@ pub struct EventRecord<E: Parameter + Member> {
}
decl_event!(
/// Event for the system module.
/// Event for the System module.
pub enum Event {
/// An extrinsic completed successfully.
ExtrinsicSuccess,
@@ -224,13 +224,13 @@ decl_event!(
}
);
/// Origin for the system module.
/// Origin for the System module.
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum RawOrigin<AccountId> {
/// The system itself ordained this dispatch to happen: this is the highest privilege level.
Root,
/// It is signed by some public key and we provide the AccountId.
/// It is signed by some public key and we provide the `AccountId`.
Signed(AccountId),
/// It is signed by nobody but included and agreed upon by the validators anyway: it's "inherently" true.
Inherent,
@@ -252,7 +252,7 @@ pub type Log<T> = RawLog<
<T as Trait>::Hash,
>;
/// A logs in this module.
/// A log in this module.
#[cfg_attr(feature = "std", derive(Serialize, Debug))]
#[derive(Encode, Decode, PartialEq, Eq, Clone)]
pub enum RawLog<Hash> {
@@ -299,7 +299,7 @@ decl_storage! {
AllExtrinsicsLen: Option<u32>;
/// Map of block numbers to block hashes.
pub BlockHash get(block_hash) build(|_| vec![(T::BlockNumber::zero(), hash69())]): map T::BlockNumber => T::Hash;
/// Extrinsics data for the current block (maps extrinsic's index to its data).
/// Extrinsics data for the current block (maps an extrinsic's index to its data).
ExtrinsicData get(extrinsic_data): map u32 => Vec<u8>;
/// Random seed of the current block.
RandomSeed get(random_seed) build(|_| T::Hash::default()): T::Hash;
@@ -388,7 +388,7 @@ impl<T: Trait> Module<T> {
/// Start the execution of a particular block.
pub fn initialize(number: &T::BlockNumber, parent_hash: &T::Hash, txs_root: &T::Hash) {
// populate environment.
// populate environment
storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
<Number<T>>::put(number);
<ParentHash<T>>::put(parent_hash);
@@ -412,7 +412,7 @@ impl<T: Trait> Module<T> {
let storage_changes_root = T::Hashing::storage_changes_root(parent_hash, number.as_() - 1);
// we can't compute changes trie root earlier && put it to the Digest
// because it will include all currently existing temporaries
// because it will include all currently existing temporaries.
if let Some(storage_changes_root) = storage_changes_root {
let item = RawLog::ChangesTrieRoot(storage_changes_root);
let item = <T as Trait>::Log::from(item).into();
@@ -424,7 +424,7 @@ impl<T: Trait> Module<T> {
<T::Header as traits::Header>::new(number, extrinsics_root, storage_root, parent_hash, digest)
}
/// Deposits a log and ensures it matches the blocks log data.
/// Deposits a log and ensures it matches the block's log data.
pub fn deposit_log(item: <T::Digest as traits::Digest>::Item) {
let mut l = <Digest<T>>::get();
traits::Digest::push(&mut l, item);
@@ -489,7 +489,7 @@ impl<T: Trait> Module<T> {
/// Note what the extrinsic data of the current extrinsic index is. If this is called, then
/// ensure `derive_extrinsics` is also called before block-building is completed.
///
/// NOTE this function is called only when the block is being constructed locally.
/// NOTE: This function is called only when the block is being constructed locally.
/// `execute_block` doesn't note any extrinsics.
pub fn note_extrinsic(encoded_xt: Vec<u8>) {
<ExtrinsicData<T>>::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt);
@@ -516,7 +516,7 @@ impl<T: Trait> Module<T> {
<ExtrinsicCount<T>>::put(extrinsic_index);
}
/// Remove all extrinsics data and save the extrinsics trie root.
/// Remove all extrinsic data and save the extrinsics trie root.
pub fn derive_extrinsics() {
let extrinsics = (0..<ExtrinsicCount<T>>::get().unwrap_or_default()).map(<ExtrinsicData<T>>::take).collect();
let xts_root = extrinsics_data_root::<T::Hashing>(extrinsics);
+25 -18
View File
@@ -16,39 +16,46 @@
//! # Timestamp Module
//!
//! The timestamp module provides functionality to get and set the on-chain time.
//! To use it in your module, you need to implement the timestamp [`Trait`].
//! The supported dispatchable functions are documented as part of the [`Call`] enum.
//! The Timestamp module provides functionality to get and set the on-chain time.
//! To use it in your runtime, you need to implement the [`timestamp::Trait`](./trait.Trait.html).
//! Dispatchable functions are documented as part of the [`Call`](./enum.Call.html) enum.
//!
//! ## Overview
//!
//! The timestamp module allows the validators to set and validate a timestamp with each block.
//! The Timestamp module allows the validators to set and validate a timestamp with each block.
//!
//! It uses inherents for timestamp data, which is provided by the block author and validated/verified by other validators.
//! The timestamp can be set only once per block and must be set each block. There could be a constraint on how much time must pass before setting the new timestamp.
//! It uses inherents for timestamp data, which is provided by the block author and validated/verified
//! by other validators. The timestamp can be set only once per block and must be set each block.
//! There could be a constraint on how much time must pass before setting the new timestamp.
//!
//! **NOTE:** The timestamp module is the recommended way to query the on-chain time instead of using an approach based on block numbers.
//! The block numbers based time measurement can cause issues because of cummulative calculation errors and hence it should be avoided.
//! **NOTE:** The Timestamp module is the recommended way to query the on-chain time instead of using
//! an approach based on block numbers. The block number based time measurement can cause issues
//! because of cumulative calculation errors and hence should be avoided.
//!
//! ## Interface
//!
//! ### Dispatchable functions ([`Call`])
//! ### Dispatchable Functions
//!
//! * `set` - Sets the current time.
//!
//! ### Public functions ([`Module`])
//! See the [`Call`](./enum.Call.html) enum and its associated variants for details of each function.
//!
//! * `get` - Gets the current time for the current block. If this function is called prior the setting to timestamp, it will return the timestamp of the previous block.
//! ### Public functions
//!
//! * `get` - Gets the current time for the current block. If this function is called prior to
//! setting the timestamp, it will return the timestamp of the previous block.
//! * `minimum_period` - Gets the minimum (and advised) period between blocks for the chain.
//!
//! See the [`Module`](./struct.Module.html) struct for details of publicly available functions.
//!
//! ## Usage
//!
//! The following example shows how to use the timestamp module in your custom module to query the current timestamp.
//! The following example shows how to use the Timestamp module in your custom module to query the current timestamp.
//!
//! ### Prerequisites
//!
//! Import the `timestamp` module in your custom module and derive the module configuration trait from the `timestamp` trait.
//! Import the Timestamp module into your custom module and derive the module configuration
//! trait from the timestamp trait.
//!
//! ### Get current timestamp
//!
@@ -69,15 +76,15 @@
//! }
//! ```
//!
//! ### Example from SRML
//! ### Example from the SRML
//!
//! The [`Session` module](https://github.com/paritytech/substrate/blob/master/srml/session/src/lib.rs) uses the `timestamp` module for session management.
//! The [Session module](https://github.com/paritytech/substrate/blob/master/srml/session/src/lib.rs) uses
//! the Timestamp module for session management.
//!
//! ## Related Modules
//!
//! * [`System`](https://crates.parity.io/srml_system/index.html)
//! * [`Session`](https://crates.parity.io/srml_session/index.html)
//!
//! * [`System`](../srml_system/index.html)
//! * [`Session`](../srml_session/index.html)
#![cfg_attr(not(feature = "std"), no_std)]