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

感情迁移 提交于 2021-02-10 18:35:50

问题


Given a hex representation: 0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d, we can get the AccountId it represents using keyring.encodeAddress() using JavaScript. However, what is the corresponding function in Rust?

AccountId is the address of the Substrate user's address. For eg, 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY is the account id of Alice, from the Substrate's dev chain.


回答1:


Within rust, you should not really start with the hex representation, you want to work with bytes.

But assuming you have hex, you can convert a hex string to AccountId bytes using the hex_literal::hex macro:

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

Note that 0x is omitted from the hex literal.

Now you should have [u8; 32] wrapped in the AccountId32 identity struct.

From there, you can simply do the same logic as done in the implementation for 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())
    }
}

Basically the Address is the ss58 encoded version of the Account Id bytes.

The ss58 codec library can be found here: https://substrate.dev/rustdocs/master/sp_core/crypto/trait.Ss58Codec.html



来源:https://stackoverflow.com/questions/60983883/how-to-encode-the-hex-string-representation-of-an-account-id-in-substrate-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!