1

In the Utility pallet there is a function:

/// Derive a derivative account ID from the owner account and the sub-account index.
pub fn derivative_account_id(who: T::AccountId, index: u16) -> T::AccountId {
    let entropy = (b"modlpy/utilisuba", who, index).using_encoded(blake2_256);
    Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref()))
        .expect("infinite length input; no invalid inputs for type; qed")
}

using_encoded() converts (b"modlpy/utilisuba", who, index) to a slice, encodes it, then it invokes blake2_256 on the slice.

TrailingZeroInput adds zeros to the end of this byte array.

Decode::decode() deserializes the value.

But what actually converts the deserialized value into an AccountId?

I see that AccountId is defined in the node primitives:

/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;

1 Answer 1

1

frame_system::Config::AccountId requires Decode + Encode.

And in your pallet, trait Config: frame_system::Config.

So, T::AccountId has these functions.

Just treat it as a codec object.

You don't need to care about the primitives::AccountId. frame_system::Config::AccountId will guarantee it has the decode function.


And if you want to know how the decoding works: https://stackoverflow.com/questions/61232644/converting-between-accountid32-and-accountid-in-substrate


Let me give you a re-implementation as an example.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=04784c805dfd38620228144a48f6abc3

use std::marker::PhantomData;

type AccountId = u8;

trait Decode {
    fn decode(bytes: [u8; 1]) -> Self;
}
impl Decode for AccountId {
    fn decode(bytes: [u8; 1]) -> Self {
        u8::from_be_bytes(bytes)
    }
}

trait FrameSystemConfig {
    type AccountId: Decode;
}
trait PalletUtilityConfig: FrameSystemConfig {}

struct PalletUtility<T>(PhantomData<T>);
impl<T> PalletUtility<T> 
where
    T: PalletUtilityConfig
{
    fn bytes2account(bytes: [u8; 1]) -> T::AccountId {
        Decode::decode(bytes)
    }
}

struct Runtime;
impl FrameSystemConfig for Runtime {
    type AccountId = AccountId;
}
impl PalletUtilityConfig for Runtime {}

fn main() {
    println!("{}", <PalletUtility<Runtime>>::bytes2account([0]));
}
2
  • Still not clear how Rust goes from bytes to T::AccountId. Is there an implicit conversion?
    – Bruno
    Commented Feb 14, 2023 at 21:26
  • 1
    Updated my answer. This is just a Rust question.
    – AurevoirXavier
    Commented Feb 15, 2023 at 3:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.