Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate a Solana wallet address with web3js?

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...

like image 645
Carlos de la Lama-Noriega Avatar asked Feb 03 '26 20:02

Carlos de la Lama-Noriega


1 Answers

PublicKey.isOnCurve() return true only if the address is on ed25519 curve such addresses generated from Keypair and returns false for off-curve addresses such as derived addresses from PublicKey.findProgramAddress() though they can be valid public key.

const owner = new PublicKey("DS2tt4BX7YwCw7yrDNwbAdnYrxjeCPeGJbHmZEYC8RTb");
console.log(PublicKey.isOnCurve(owner.toBytes())); // true
console.log(PublicKey.isOnCurve(owner.toString())); // true

const ownerPda = PublicKey.findProgramAddressSync(
    [owner.toBuffer()],
    new PublicKey("worm2ZoG2kUd4vFXhvjh93UUH596ayRfgQ2MgjNMTth"),
)[0];
console.log(PublicKey.isOnCurve(ownerPda.toString())); // false

console.log(PublicKey.isOnCurve([owner, 18])); // false

const RAY_MINT = new PublicKey("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R");
console.log(PublicKey.isOnCurve(new PublicKey(RAY_MINT))); // true

console.log(PublicKey.isOnCurve("fasddfasevase")); // throws error
like image 125
Ashish Sapkota Avatar answered Feb 06 '26 13:02

Ashish Sapkota



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!