substrate學習筆記3:新增一個Pallet到Runtime

linghuyichong發表於2022-03-21

substrate node template提供了一個最小的可工作的執行時,但是為了保持精煉,它並不包括Frame中的大多數的Pallet。本節我們將學習如何將Pallet新增到runtime中。

本節的學習需要使用到Node Template,其安裝過程我們在之前Substrate中已經講過,此處不再累述。

開啟runtime/Catgo.toml,分別新增依賴和feature。

  • 新增依賴:
[dependencies]
allet-nicks = { default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', tag = 'monthly-2021-08' }
  • 新增feature:
[features]
default = ["std"]
std = [
    #--snip--
    'pallet-nicks/std',
    #--snip--
]

在此節,我們主要要為runtime實現對應的nick pallet的config介面,因此我們在runtime/src/lib.rs中新增如下程式碼:

parameter_types! {
    // Choose a fee that incentivizes desireable behavior.
    pub const NickReservationFee: u128 = 100;
    pub const MinNickLength: u32 = 8;
    // Maximum bounds on storage are important to secure your chain.
    pub const MaxNickLength: u32 = 32;
}

impl pallet_nicks::Config for Runtime {
    // The Balances pallet implements the ReservableCurrency trait.
    // `Balances` is defined in `construct_runtimes!` macro. See below.
    // https://substrate.dev/rustdocs/latest/pallet_balances/index.html#implementations-2
    type Currency = Balances;

    // Use the NickReservationFee from the parameter_types block.
    type ReservationFee = NickReservationFee;

    // No action is taken when deposits are forfeited.
    type Slashed = ();

    // Configure the FRAME System Root origin as the Nick pallet admin.
    // https://substrate.dev/rustdocs/latest/frame_system/enum.RawOrigin.html#variant.Root
    type ForceOrigin = frame_system::EnsureRoot<AccountId>;

    // Use the MinNickLength from the parameter_types block.
    type MinLength = MinNickLength;

    // Use the MaxNickLength from the parameter_types block.
    type MaxLength = MaxNickLength;

    // The ubiquitous event type.
    type Event = Event;
}

construct_runtime!宏的意思是用給定的模組來定義我們的執行時,因此我們需要將我們的nick pallet新增到其中。在runtime/src/lib.rs的construct_runtime!中新增程式碼:

construct_runtime!(
    pub enum Runtime where
        Block = Block,
        NodeBlock = opaque::Block,
        UncheckedExtrinsic = UncheckedExtrinsic
    {
        /* --snip-- */

        /*** Add This Line ***/
        Nicks: pallet_nicks::{Pallet, Call, Storage, Event<T>},
    }
);

執行如下命令編譯:

cargo build --release

用如下命令執行:

./target/release/node-template --dev --tmp

啟動前端:

yarn start
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章