Search code examples
rustsubstratepolkadotpolkadot-js

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


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.


Solution

  • 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