Skip to Content
DocumentationSOLWatch Lamport Balance

Watch Lamport Balance

Watches for real-time changes to SOL balances using WebSocket subscriptions. The function fetches the current balance immediately and then subscribes to ongoing updates, calling the provided callback whenever the balance changes.

Returns: () => void - A cleanup function to stop watching

const stopWatching = connection.watchLamportBalance( address, (error, balance) => { if (error) { console.error("Error:", error); return; } console.log("Balance:", balance); } ); // Later, to stop watching: stopWatching();

Parameters

  • address: Address - The Solana address to watch for balance changes
  • callback: (error: any, balance: Lamports | null) => void - Called with (error, balance) on each balance change
    • error: any - Any error that occurred (null if successful)
    • balance: Lamports | null - The new lamport balance as a bigint (null if error occurred)

Returns

Returns a cleanup function that stops watching for balance changes. Call this function when you no longer need to watch the balance.

Examples

Watch a wallet balance and log changes:

const stopWatching = connection.watchLamportBalance( "GkFTrgp8FcCgkCZeKreKKVHLyzGV6eqBpDHxRzg1brRn", (error, balance) => { if (error) { console.error("Error watching balance:", error); return; } // Convert lamports to SOL const balanceInSOL = Number(balance) / 1_000_000_000; console.log(`Balance: ${balanceInSOL} SOL`); } ); // Stop watching after 10 seconds setTimeout(() => { stopWatching(); console.log("Stopped watching balance"); }, 10000);

Watch a balance and update UI state:

const [balance, setBalance] = useState<bigint | null>(null); useEffect(() => { const stopWatching = connection.watchLamportBalance( walletAddress, (error, newBalance) => { if (error) { console.error("Error:", error); return; } setBalance(newBalance); } ); // Cleanup on unmount return stopWatching; }, [walletAddress]);

Notes

  • The callback is called immediately with the current balance, then again whenever the balance changes
  • The function uses WebSocket subscriptions for real-time updates
  • Always call the cleanup function when you’re done watching to prevent memory leaks
  • The balance is returned in lamports (1 SOL = 1,000,000,000 lamports)

Error Handling

The callback receives an error as the first parameter if something goes wrong. Common errors include:

  • Invalid address
  • RPC connection failures
  • Network issues

Always check for errors in your callback before using the balance value.

See also: Get Lamport Balance, Transfer Lamports

Last updated on