4

I'm following this article about substrate keys. And I was unable to convert the account ID to account bytes in hex as it guides:

from this:

Account ID

5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY

to this:

Account Bytes in Hex

0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d

Do you know how it should be done?

1 Answer 1

5

SS58 -> public key

So what you are looking for here is the public key of the SS58 Account ID. Here is an example on how you can retrieve the above public key in polkadot-js with a simple script in two different ways:

require('@polkadot/api-augment');
const { cryptoWaitReady } = require('@polkadot/util-crypto');
const { Keyring } = require('@polkadot/keyring');
const { u8aToHex } = require('@polkadot/util');

const main = async () => {
    await cryptoWaitReady();

    const keyring = new Keyring();
    keyring.addFromAddress('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');

    console.log(u8aToHex(keyring.publicKeys[0]))

    // OR

    const keyring2 = new Keyring();
    console.log(u8aToHex(keyring.decodeAddress('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY')))
};

main().finally(() => process.exit());

This will output 0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d

To expand on the Keyring object it has more to it than the above.

The Keyring class can also take in options such as:

  • type: which would declare the type of scheme we want to specify such as sr25519, ecdsa, or ed25519.
  • ss58Format: which would declare the ss58 prefix we want the Keyring to specify.

So for example:

const keyring = new Keyring({ type: 'sr5519, ss58Format: 42 });

Public key -> SS58

We can also derive an address from a cryptographic public key with polkadot-js, lets take a look:

require('@polkadot/api-augment');
const { cryptoWaitReady } = require('@polkadot/util-crypto');
const { Keyring } = require('@polkadot/keyring');
const { hexToU8a } = require('@polkadot/util');

const main = async () => {
    await cryptoWaitReady();

    const publicKey = '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d';
    const ss58Format = 42;
    const scheme = 'sr25519';

    const u8aKey = hexToU8a(publicKey);
    const keyring = new Keyring({ type: scheme, ss58Format: ss58Format });
    const address = keyring.encodeAddress(u8aKey, ss58Format);

    console.log(address);

    // Note: If the scheme type is `ecdsa` we need to make sure we blake2a hash the public key if its
    // above 32 bytes in length. That would looks like:
    // (p.length > 32 ? blake2AsU8a(p) : p)
};

main().finally(() => process.exit());

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.