【Substrate Collectables教程】【第1章基础】2. 创建Storage Value

创建Storage Value(存储值)

创建存储值,先将最简单的逻辑添加到runtime 中:一个存储变量的函数。

为此,我们首先需要在 decl_storage! 宏中为 Storage Item 定义存储变量。这种用法使得 Substrate 存储数据库的使用是类型安全的,因此你可以在区块中保存这些数据。

2.1 创建一个Storage Value

Substrate 本身支持 Rust 中可用的所有原始类型(boolu8u32 等)以及一些 Substrate 中的一些自定义类型 (AccountIdBlockNumberHash其它...)

你可以声明一个简单的 storage item(存储项),如下所示:

 

 

 这里我们定义了3个变量:一个 u32 变量和一个带有 getter 函数 my_bool_getter 的 bool 变量,以及一个名为Value的存储值用于存储u64类型get 参数是可选的,但如果将其添加到 storage item,它将公开具有指定名称的 getter 函数(fn getter_name() -> Type)。

2.2 使用 Storage Value

用于访问 StorageValue 的函数被定义在 srml_support::storage 中:

/// Get the storage key.
fn key() -> &'static [u8];

/// true if the value is defined in storage.
fn exists<S: Storage>(storage: &S) -> bool {
    storage.exists(Self::key())
}

/// Load the value from the provided storage instance.
fn get<S: Storage>(storage: &S) -> Self::Query;

/// Take a value from storage, removing it afterwards.
fn take<S: Storage>(storage: &S) -> Self::Query;

/// Store a value under this key into the provided storage instance.
fn put<S: Storage>(val: &T, storage: &S) {
    storage.put(Self::key(), val)
}

/// Mutate this value
fn mutate<R, F: FnOnce(&mut Self::Query) -> R, S: Storage>(f: F, storage: &S) -> R;

/// Clear the storage value.
fn kill<S: Storage>(storage: &S) {
    storage.kill(Self::key())
}

所以如果你想 "put" MyU32 的值,你可以这样写:

<MyU32<T>>::put(1337);

如果你想 "get" MyBool 的值,你可以选择以下任一一种写法:

let my_bol = <MyBool<T>>::get();
let also_my_bol = Self::my_bol_getter();

在下一节中展示如何将这些函数调用集成到你自己的 module 中。

2.3 更新Runtime

./scripts/build.sh               // 构建 Wasm
cargo build --release    // 构建 binary

 

posted @ 2022-05-12 09:27  MintMin  阅读(41)  评论(0编辑  收藏  举报