如何使用 Rust 在 Substrate 中编码帐户 ID 的十六进制字符串表示形式?

Avi*_*ava 5 rust substrate polkadot-js polkadot

给定一个十六进制表示:0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d,我们可以使用 JavaScript 获取它表示的 AccountId keyring.encodeAddress()。然而,Rust 中对应的函数是什么呢?

AccountId 是Substrate用户的地址。例如,5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY是来自 Substrate 开发链的 Alice 的账户 ID。

Sha*_*izi 4

在 Rust 中,您不应该真正从十六进制表示开始,您想要使用字节。

但假设您有十六进制,您可以使用宏将十六进制字符串转换为 AccountId 字节hex_literal::hex

let account: AccountId32 = hex_literal::hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"].into(),
Run Code Online (Sandbox Code Playgroud)

请注意,0x十六进制文字中省略了 。

现在您应该已经[u8; 32]包含在AccountId32身份结构中。

Display从那里,您可以简单地执行与for实现中相同的逻辑AccountId32

#[cfg(feature = "std")]
impl std::fmt::Display for AccountId32 {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.to_ss58check())
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,地址是ss58帐户 ID 字节的编码版本。

ss58 编解码器库可以在这里找到:https ://substrate.dev/rustdocs/master/sp_core/crypto/trait.Ss58Codec.html