Home > OS >  How can I validate a Solana wallet address with web3js?
How can I validate a Solana wallet address with web3js?

Time:02-21

I'm trying to validate that the input text I get from a user is a valid Solana address.

According to the web3.js documentation, the method .isOnCurve() does that:

https://solana-labs.github.io/solana-web3.js/classes/PublicKey.html#isOnCurve

I've managed to make it work with this code:

import {PublicKey} from '@solana/web3.js'

function validateSolAddress(address:string){
    try {
        let pubkey = new PublicKey(address)
        let  isSolana =  PublicKey.isOnCurve(pubkey.toBuffer())
        return isSolana
    } catch (error) {
        return false
    }
} 

function modalSubmit(modal: any){

  const firstResponse = modal.getTextInputValue(walletQuestFields.modal.componentsList[0].id)
 
  let isSolAddress = validateSolAddress(firstResponse)

  if (isSolAddress) {
    console.log('The address is valid')
  }else{
    console.log('The address is NOT valid')
  }
}

But when I pass let pubkey = new PublicKey(address) a string that is not similar to a solana address, it throws the exception Error: Invalid public key input (PublikKey expects a PublicKeyInitData: number | string | Buffer | Uint8Array | number[] | PublicKeyData)

That is why I had to out it into a try-catch block.

Is there any other (better) way to achieve this? It looks ugly...

CodePudding user response:

To validate a Solana public key may be a wallet address, you should both use isOnCurve() and the PublicKey constructor like you are doing.

The error thrown makes sense. If the address is not a public key, it should not be able to be instantiated.

Perhaps there could be another function made native to @solana/web3.js that takes care of validating wallet addresses for you in the future.

  • Related