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

How to encode the hex string representation of an account id in Substrate using Rust?

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

A​​ccountId 是Substrate 用户的地址。例如,5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY 是来自 Substrate 开发链的 Alice 的帐户 ID。

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

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

let account: AccountId32 = hex_literal::hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"].into(),

Note that 0x is omitted from the hex literal.

现在您应该 [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())
    }
}

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

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