11

We have a pallet which has their own account e.g *b"replace_" and we are able to generate sub accounts addresses like so:

let sub_account: T::AccountId = T::PalletId::get().into_sub_account((0, 1))

In our react frontend, how can we fetch the address of a pallet's sub-account address using PolkadotJS API? (in this example the id is tuple of (0,1))

We set up the pallet account as detailed in Shawn's accepted answer: https://stackoverflow.com/questions/67082488/transferring-assets-between-accounts-and-pallet

and i found from this site https://www.shawntabrizi.com/substrate-js-utilities/ we can get the Pallet's account address using:

let address = stringToU8a(("modl" + moduleId).padEnd(32, '\0'));
encodeAddress(address);

Our issue is getting the sub account address for a given id.

1 Answer 1

11

You just need to look at the Rust source code:

fn into_sub_account<S: Encode>(&self, sub: S) -> T {
    (Id::TYPE_ID, self, sub)
        .using_encoded(|b| T::decode(&mut TrailingZeroInput(b)))
        .expect("`AccountId` type is never greater than 32 bytes; qed")
}

So basically:

  1. Take the bytes of the TYPE_ID.

    For a PalletId that is:

    impl TypeId for PalletId {
        const TYPE_ID: [u8; 4] = *b"modl";
    }
    

    As hex bytes, "modl" is: 0x6d6f646c

  2. Take the PalletId itself as bytes, for example:

    pub const SocietyPalletId: PalletId = PalletId(*b"py/socie");
    

    As hex bytes, "py/socie" is: 0x70792f736f636965

  3. Take your sub account seed as bytes:

    /// The account ID of the payouts pot. This is where payouts are made from.
    ///
    /// This actually does computation. If you need to keep using it, then make sure you cache the
    /// value and only call this once.
    pub fn payouts() -> T::AccountId {
        T::PalletId::get().into_sub_account(b"payouts")
    }
    

    As bytes, "payouts" is 0x7061796f757473

  4. Then fill the rest of the account address with 0 to fill the expected account encoded length.

So putting this all together, you can find the account:

0x6d6f646c70792f736f6369657061796f75747300000000000000000000000000
--1-------2---------------3-------------4-------------------------

Which leads to SS58 Address:

5EYCAe5ijiYfqiTEFBxuWTX5AH6oQUT7Fe1Pz5wNvsNWXux7

And there you go! Check out the Society Pallet Payouts sub-account here:

https://kusama.subscan.io/account/5EYCAe5ijiYfqiTEFBxuWTX5AH6oQUT7Fe1Pz5wNvsNWXux7

0

Your Answer

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

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