【问题标题】:What is the purpose of `pub` in decl_storage?decl_storage 中 pub 的用途是什么?
【发布时间】:2019-06-14 13:33:16
【问题描述】:

在基板中实现运行时模块时,给定以下存储

decl_storage! {
  trait Store for Module<T: Trait> as CatAuction {
    Kitties get(kitties): map T::Hash => Kitty<T::Hash, T::Balance>;
    KittyOwner get(owner_of): map T::Hash => Option<T::AccountId>;
    OwnedKitties get(kitties_owned): map T::AccountId => T::Hash;

    pub AllKittiesCount get(all_kitties_cnt): u64;
    Nonce: u64;

    // if you want to initialize value in storage, use genesis block
  }
}

pubAllKittiesCount前面的目的是什么?因为不管有没有pub,polkadot UI 还是可以查询到的,就好像它是一个公共变量一样。

【问题讨论】:

  • 我们是否告诉您在教程中的某处使用pub?或者这只是一个附带问题?
  • @ShawnTabrizi 遍历decl_storage! doc,说基本存储可以这样扩展:#vis #name get(#getter) config(#field_name) build(#closure): #type = #default;#vis: Set the visibility of the structure. pub or nothing ...

标签: substrate parity-io


【解决方案1】:

在这里稍微扩展一下,就像任何 Rust 类型一样,您需要明确不同类型的可见性。 decl_storage 宏为您的每个存储项目生成一个struct。例如:

decl_storage! {
    trait Store for Module<T: Trait> as TemplateModule {
        Something get(something): u32;
    }
}

会导致(为清楚起见删除了一些内容):

struct Something<T: Trait>(...);

impl <T: Trait> ... for Something<T> {
    fn get<S: ... >(storage: &S) -> Self::Query {
        storage.get(...).unwrap_or_else(|| Default::default())
    }
    fn take<S: ...>(storage: &S) -> Self::Query {
        storage.take(...).unwrap_or_else(|| Default::default())
    }
    fn mutate<R, F: FnOnce(&mut Self::Query) -> R, S: ...>(f: F, storage: &S) -> R {
        let mut val = <Self as ...>::get(storage);
        let ret = f(&mut val);
        <Self as ...>::put(&val, storage);
        ret
    }
}

如果您将存储项设为pub,您只需将pub 标记引入struct Something。这意味着,您现在可以从其他模块调用结构公开的所有这些函数,例如gettakemutate。否则,您将需要创建自己的公共函数来公开 API 以修改存储。

【讨论】:

    【解决方案2】:

    decl_storage!为每个存储生成一个结构,此结构实现指定的存储特征。

    $vis 指定此结构的可见性。

    注意:getter get($getter) 是一个在模块上实现的公共函数,它不受这个$vis 的影响。

    注意:最后,所有模块都写入唯一的 trie 存储,因此仍然可以通过请求正确的键以某种方式访问​​值。

    编辑:我可以补充一点,拥有公共存储结构的好处是,其他模块可以使用 Storage{Value, Map, ..} 特征直接写入它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 2011-12-17
      • 2010-11-21
      相关资源
      最近更新 更多