Rust-substrate实现区块链结构增加Pallet实例

环境需要参考之前的substrate学习进行,保证substrate可以直接运行后,对于需要的模块可以进行配置添加。

  1. 使用VSCode打开项目,在runtime中有一个Cargo.toml配置,将crate添加进入dependents中,并且在features中增加std依赖。

toml …… pallet-nicks = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.17" } [features] default = ['std'] std = [ ... 'pallet-aura/std', 'pallet-balances/std', 'pallet-nicks/std', ... ]

  1. 可以通过cargo check -p node-template-runtime命令查看是否编写错误

  2. 每一个需要引入的pallet都可以在lib.rs中进行配置,这种配置是非入侵式的,需要配置在construct_runtime!()之前,如下代码所示。

```rust // Add my Nick pallet static final config 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_runtime! macro. See below. // https://docs.substrate.io/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://docs.substrate.io/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;

}

// Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = opaque::Block, UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system, …… //这里需要添加pallet_nicks宏 // add my nicks pallet Nicks: pallet_nicks, } ); ```

测试成功

  1. 使用cargo build --release进行打包

  2. 重新运行项目./target/release/node-template --dev

  3. 启动前端yarn start

链接