I am trying to get the SOL balance from a phantom wallet. The wallet has > 0 SOL in it, so I know that something is wrong when I make the call. Here is my code:
(async () => {
const connection = new solanaWeb3.Connection(
solanaWeb3.clusterApiUrl('devnet'),
'confirmed',
);
if (phantom && phantom.publicKey !== null) {
const balance = await connection.getBalance(phantom.publicKey)
console.log(balance);
}
})();
What am I doing wrong?
Your issue looks like it might be with the assignment to phantom.publicKey itself and not your code. Replacing phantom.public key with a defined public key below works.
const solanaWeb3 = require('@solana/web3.js');
const public_key=new solanaWeb3.PublicKey("your Solana public address with non-0 balance");
(async () => {
const connection = new solanaWeb3.Connection(
solanaWeb3.clusterApiUrl('devnet'),
'confirmed',
);
if (public_key !== null) {
const balance = await connection.getBalance(public_key);
console.log(balance)
}
})();