Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate the public key from Polkadot Address from Substrate Side

I'm generating a Public key from PolkadotJS as follows

    const keyring = new Keyring({ type: "sr25519" });
    const account = keyring.addFromUri("//Bob", { name: "Bob default" });
    
    // encoded public key 
    let public_key = keyring.encodeAddress(account.publicKey, 42);
    console.log(public_key);

I am adding the type of public_key as "public_key": "Vec<u8>",

I am reading the public key from Substrate Node as follows

// pk_raw is a Vec<u8> array 
let pk =  str::from_utf8(pk_raw.as_ref()).unwrap() 
// the above returns `5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty`

I need to generate the public key from this value. I tried with the followings

ed25519::Public::try_from(&*pk_raw).unwrap(); 
// above throws error since the data length is not equals to 32

fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        if data.len() == 32 {
            let mut inner = [0u8; 32];
            inner.copy_from_slice(data);
            Ok(Public(inner))
        } else {
            Err(())
        }
    }

Is there a way to generate the public key using 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty from Substrate Rust Side?

like image 562
Gayan Kalanamith Avatar asked Oct 25 '25 04:10

Gayan Kalanamith


1 Answers

You can use something like this:

use sp_core::crypto::Ss58Codec;

ed25519::Public::from_ss58check("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty").expect("Valid address")
like image 144
bkchr Avatar answered Oct 26 '25 19:10

bkchr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!