Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created January 14, 2022 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topherPedersen/a622c2db0e241eafb23b58ed073fd2dc to your computer and use it in GitHub Desktop.
Save topherPedersen/a622c2db0e241eafb23b58ed073fd2dc to your computer and use it in GitHub Desktop.
Solana 101: Getting Your Balance (From Figment.io's Solana 101 Course)
import type {NextApiRequest, NextApiResponse} from 'next';
import {Connection, PublicKey} from '@solana/web3.js';
import {getNodeURL} from '@figment-solana/lib';
export default async function balance(
req: NextApiRequest,
res: NextApiResponse<string | number>,
) {
try {
const {network, address} = req.body;
const url = getNodeURL(network);
const connection = new Connection(url, 'confirmed');
const publicKey = new PublicKey(address);
const balance = await connection.getBalance(publicKey);
if (balance === 0 || balance === undefined) {
throw new Error('Account not funded');
}
res.status(200).json(balance);
} catch (error) {
let errorMessage = error instanceof Error ? error.message : 'Unknown Error';
res.status(500).json(errorMessage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment