Search code examples
blockchainparitysubstratepolkadot

Converting between AccountId32 and AccountId in Substrate


I have a requirement where i get passed in some bytes and i need to create an accountId from it in Substrate 2.0.

Is there a way to convert between AccountId32 and <T as frame_system::Trait>::AccountId in the runtime (FRAME) ? Or to create an instance of <T as frame_system::Trait>::AccountId from bytes?

Thanks


Solution

  • Given raw bytes, you can attempt to construct an account id like so:

    T::AccountId::decode(&mut &bytes[..]).unwrap_or_default();
    

    You may want to handle your error condition differently than returning a default AccountId.

    If you can verify that your raw bytes has length 32 ([u8; 32]), this operation should never fail, so you could place an .expect("32 bytes can always construct an AccountId32").