#
pezkuwi_sdk_docs/reference_docs/
trait_based_programming.rs

    1//! # Trait-based Programming
    2//!
    3//! This document walks you over a peculiar way of using Rust's `trait` items. This pattern is
    4//! abundantly used within [`frame`] and is therefore paramount important for a smooth transition
    5//! into it.
    6//!
    7//! The rest of this document assumes familiarity with the
    8//! [Rust book's Advanced Traits](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html)
    9//! section.
    10//! Moreover, we use the [`frame::traits::Get`].
    11//!
    12//! First, imagine we are writing a FRAME pallet. We represent this pallet with a `struct Pallet`,
    13//! and this pallet wants to implement the functionalities of that pallet, for example a simple
    14//! `transfer` function. For the sake of education, we are interested in having a `MinTransfer`
    15//! amount, expressed as a [`frame::traits::Get`], which will dictate what is the minimum amount
    16//! that can be transferred.
    17//!
    18//! We can foremost write this as simple as the following snippet:
    19#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", basic)]
    20//!
    21//!
    22//! In this example, we use arbitrary choices for `AccountId`, `Balance` and the `MinTransfer` type.
    23//! This works great for **one team's purposes** but we have to remember that Substrate and FRAME
    24//! are written as generic frameworks, intended to be highly configurable.
    25//!
    26//! In a broad sense, there are two avenues in exposing configurability:
    27//!
    28//! 1. For *values* that need to be generic, for example `MinTransfer`, we attach them to the
    29//!    `Pallet` struct as fields:
    30//!
    31//! ```
    32//! struct Pallet {
    33//! 	min_transfer: u128,
    34//! }
    35//! ```
    36//!
    37//! 2. For *types* that need to be generic, we would have to use generic or associated types, such
    38//!    as:
    39//!
    40//! ```
    41//! struct Pallet<AccountId> {
    42//! 	min_transfer: u128,
    43//!     _marker: std::marker::PhantomData<AccountId>,
    44//! }
    45//! ```
    46//!
    47//! Substrate and FRAME, for various reasons (performance, correctness, type safety) has opted to
    48//! use *types* to declare both *values* and *types* as generic. This is the essence of why the
    49//! `Get` trait exists.
    50//!
    51//! This would bring us to the second iteration of the pallet, which would look like:
    52#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", generic)]
    53//!
    54//! In this example, we managed to make all 3 of our types generic. Taking the example of the
    55//! `AccountId`, one should read the above as following:
    56//!
    57//! > The `Pallet` does not know what type `AccountId` concretely is, but it knows that it is
    58//! > something that adheres to being `From<[u8; 32]>`.
    59//!
    60//! This method would work, but it suffers from two downsides:
    61//!
    62//! 1. It is verbose, each `impl` block would have to reiterate all of the trait bounds.
    63//! 2. It cannot easily share/inherit generic types. Imagine multiple pallets wanting to be generic
    64//!    over a single `AccountId`. There is no easy way to express that in this model.
    65//!
    66//! Finally, this brings us to using traits and associated types on traits to express the above.
    67//! Trait associated types have the benefit of:
    68//!
    69//! 1. Being less verbose, as in effect they can *group multiple `type`s together*.
    70//! 2. Can inherit from one another by declaring
    71//! [supertraits](https://doc.rust-lang.org/rust-by-example/trait/supertraits.html).
    72//!
    73//! > Interestingly, one downside of associated types is that declaring defaults on them is not
    74//! > stable yet. In the meantime, we have built our own custom mechanics around declaring defaults
    75//! for associated types, see [`pallet_default_config_example`].
    76//!
    77//! The last iteration of our code would look like this:
    78#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", trait_based)]
    79//!
    80//! Notice how instead of having multiple generics, everything is generic over a single `<T:
    81//! Config>`, and all types are fetched through `T`, for example `T::AccountId`, `T::MinTransfer`.
    82//!
    83//! Finally, imagine all pallets wanting to be generic over `AccountId`. This can be achieved by
    84//! having individual `trait Configs` declare a shared `trait SystemConfig` as their
    85//! [supertrait](https://doc.rust-lang.org/rust-by-example/trait/supertraits.html).
    86#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", with_system)]
    87//! In FRAME, this shared supertrait is [`frame::prelude::frame_system`].
    88//!
    89//! Notice how this made no difference in the syntax of the rest of the code. `T::AccountId` is
    90//! still a valid type, since `T` implements `Config` and `Config` implies `SystemConfig`, which
    91//! has a `type AccountId`.
    92//!
    93//! Note, in some instances one would need to use what is known as the fully-qualified-syntax to
    94//! access a type to help the Rust compiler disambiguate.
    95#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", fully_qualified)]
    96//!
    97//! This syntax can sometimes become more complicated when you are dealing with nested traits.
    98//! Consider the following example, in which we fetch the `type Balance` from another trait
    99//! `CurrencyTrait`.
    100#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", fully_qualified_complicated)]
    101//!
    102//! Notice the final `type BalanceOf` and how it is defined. Using such aliases to shorten the
    103//! length of fully qualified syntax is a common pattern in FRAME.
    104//!
    105//! The above example is almost identical to the well-known (and somewhat notorious) `type
    106//! BalanceOf` that is often used in the context of [`frame::traits::fungible`].
    107#![doc = docify::embed!("../../substrate/frame/fast-unstake/src/types.rs", BalanceOf)]
    108//!
    109//! ## Additional Resources
    110//!
    111//! - <https://github.com/paritytech/substrate/issues/13836>
    112//! - [Substrate Seminar - Traits and Generic Types](https://www.youtube.com/watch?v=6cp10jVWNl4)
    113//! - <https://exchange.pezkuwichain.app/questions/2228/type-casting-to-trait-t-as-config>
    114#![allow(unused)]
    115
    116use frame::traits::Get;
    117
    118#[docify::export]
    119mod basic {
    120	struct Pallet;
    121
    122	type AccountId = frame::deps::sp_runtime::AccountId32;
    123	type Balance = u128;
    124	type MinTransfer = frame::traits::ConstU128<10>;
    125
    126	impl Pallet {
    127		fn transfer(_from: AccountId, _to: AccountId, _amount: Balance) {
    128			todo!()
    129		}
    130	}
    131}
    132
    133#[docify::export]
    134mod generic {
    135	use super::*;
    136
    137	struct Pallet<AccountId, Balance, MinTransfer> {
    138		_marker: std::marker::PhantomData<(AccountId, Balance, MinTransfer)>,
    139	}
    140
    141	impl<AccountId, Balance, MinTransfer> Pallet<AccountId, Balance, MinTransfer>
    142	where
    143		Balance: frame::traits::AtLeast32BitUnsigned,
    144		MinTransfer: frame::traits::Get<Balance>,
    145		AccountId: From<[u8; 32]>,
    146	{
    147		fn transfer(_from: AccountId, _to: AccountId, amount: Balance) {
    148			assert!(amount >= MinTransfer::get());
    149			unimplemented!();
    150		}
    151	}
    152}
    153
    154#[docify::export]
    155mod trait_based {
    156	use super::*;
    157
    158	trait Config {
    159		type AccountId: From<[u8; 32]>;
    160		type Balance: frame::traits::AtLeast32BitUnsigned;
    161		type MinTransfer: frame::traits::Get<Self::Balance>;
    162	}
    163
    164	struct Pallet<T: Config>(std::marker::PhantomData<T>);
    165	impl<T: Config> Pallet<T> {
    166		fn transfer(_from: T::AccountId, _to: T::AccountId, amount: T::Balance) {
    167			assert!(amount >= T::MinTransfer::get());
    168			unimplemented!();
    169		}
    170	}
    171}
    172
    173#[docify::export]
    174mod with_system {
    175	use super::*;
    176
    177	pub trait SystemConfig {
    178		type AccountId: From<[u8; 32]>;
    179	}
    180
    181	pub trait Config: SystemConfig {
    182		type Balance: frame::traits::AtLeast32BitUnsigned;
    183		type MinTransfer: frame::traits::Get<Self::Balance>;
    184	}
    185
    186	pub struct Pallet<T: Config>(std::marker::PhantomData<T>);
    187	impl<T: Config> Pallet<T> {
    188		fn transfer(_from: T::AccountId, _to: T::AccountId, amount: T::Balance) {
    189			assert!(amount >= T::MinTransfer::get());
    190			unimplemented!();
    191		}
    192	}
    193}
    194
    195#[docify::export]
    196mod fully_qualified {
    197	use super::with_system::*;
    198
    199	// Example of using fully qualified syntax.
    200	type AccountIdOf<T> = <T as SystemConfig>::AccountId;
    201}
    202
    203#[docify::export]
    204mod fully_qualified_complicated {
    205	use super::with_system::*;
    206
    207	trait CurrencyTrait {
    208		type Balance: frame::traits::AtLeast32BitUnsigned;
    209		fn more_stuff() {}
    210	}
    211
    212	trait Config: SystemConfig {
    213		type Currency: CurrencyTrait;
    214	}
    215
    216	struct Pallet<T: Config>(std::marker::PhantomData<T>);
    217	impl<T: Config> Pallet<T> {
    218		fn transfer(
    219			_from: T::AccountId,
    220			_to: T::AccountId,
    221			_amount: <<T as Config>::Currency as CurrencyTrait>::Balance,
    222		) {
    223			unimplemented!();
    224		}
    225	}
    226
    227	/// A common pattern in FRAME.
    228	type BalanceOf<T> = <<T as Config>::Currency as CurrencyTrait>::Balance;
    229}