如何在基板运行时硬编码地址?

问题描述

您可以在托盘中手动预设整数、字符串和很多东西,但是除了 ensure_root 功能之外,我如何在托盘中手动设置 AccountId?

我认为由于区块链已经运行了很长时间,我无法更改链规范的起源。

解决方法

根据您的评论,我只能假设您问题的正确标题是:“如何在基板运行时中硬编码地址”。

已经回答了一个类似的问题 here。在这里简要回顾一下,托盘内已知的 AccountId 类型仅限于以下特征:https://github.com/paritytech/substrate/blob/master/frame/system/src/lib.rs#L195

因此,尽管仍然有可能,但在托盘内对 进行硬编码有点困难。更明智的方法是将硬编码帐户作为配置从外部注入到您的托盘中。

首先,您的配置特征需要接受包含此帐户的类型:

trait Config: frame_system::Config {
   // A type that can deliver a single account id value to the pallet.
   type CharityDest: Get<<Self as frame_system::Config>::AccountId>
}

然后,要使用它,您只需:

// inside the `impl<T> Module<T>` or `impl<C> Pallet<T>` or `decl_module` where `T` is in scope.
some_transfer_function(T::CharityDest::get(),amount);

最后,在您的顶级运行时文件中,您可以对 AccountId 进行硬编码并将其传入,如下所示:

parameter_types! {
     pub CharityDest: AccountId = hex_literal::hex!["hex-bytes-of-account"].into()
}

impl my_pallet::Config for Runtime {
   type CharityDest = CharityDest;
}

或者,您也可以使用大多数运行时的 AccountId 类型是 AccountId32 这一事实,它实现了 Ss58Codec,这意味着它有一堆有用的函数可以从ss58 字符串到帐户,所以你可以做类似的事情

parameter_types! {
     pub CharityDest: AccountId = AccountId::from_ss58check("AccountSs58Format").unwrap()
}