1. 程式人生 > 其它 >【Substrate Collectables教程】【第1章基礎】2. 建立Storage Value

【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