How to check that a Solana address is valid in JavaScript

In this tutorial, we are going to learn how to verify that a Solana address is valid in JavaScript, using the @solana/web3.js library.

In this tutorial, we are going to learn how to verify that a Solana address is valid in JavaScript, using the @solana/web3.js library.

First, let's install the library:

npm install @solana/web3.js

Then, let's import what we need from the library:

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

Now that we have that, we need to create a PublicKey object from the address that we want to verify the validity.

Here is the code to do that, assuming you have that address as a string:

const addressToVerify = 'GX6nkQgcXy4xDyuSH9MKjG9nq5KN5ntE3ZUUHSqUrcC8'
const publicKey = new PublicKey(addressToVerify);

If you're using React, you can get the PublicKey of the connected wallet using the useWallet hook which returns a publicKey property.

Next, we need to use the isOnCurve method of the PublicKey class:

const isValidAddress = await PublicKey.isOnCurve(publicKey);

This will return a boolean indicating wether or not the address you passed is valid or not.

This method checks that a PublicKey is on the ed25519 curve. The ed25519 curve is an elliptic curve that Solana uses for cryptography. It is a way to generate public keys (account addresses) and private keys, use them to sign messages like transactions and verify signatures.

If you're curious and you want to learn more about the cryptography behind it and the ed25519 curve, check out these 2 pages on Wikipedia:

  • This one about the ed25519 digital signature scheme:
EdDSA - Wikipedia
  • And this one about digital signatures in general:
Digital signature - Wikipedia

And that's it 🎉

Thank you for reading this article