Function.useKeybanAccountBalance
function useKeybanAccountBalance(account: KeybanAccount): ApiResult<string>;
Hook to retrieve and subscribe to the balance of a Keyban account.
This React hook allows you to fetch the native balance of a Keyban account and automatically updates when the balance changes.
It returns an ApiResult tuple containing the balance or an error if one occurred during retrieval.
Parameters
| Parameter | Type | Description |
|---|---|---|
account | KeybanAccount | The KeybanAccount object representing the user account. |
Returns
ApiResult<string>
- An
ApiResult<string>tuple containing: - First element (
balance): Astringrepresenting the account's native token balance in the smallest unit (e.g., wei for Ethereum). This value automatically updates when the balance changes. - Second element (
error): AnErrorobject if an error occurred during retrieval, ornullif the balance was fetched successfully.
Return Structure:
[balance: string, error: Error | null]
balance: The current balance of the Keyban account as a string.error: AnErrorobject if there was an error fetching the balance, otherwisenull.
Example
import { useKeybanAccount, useKeybanAccountBalance } from "@keyban/sdk-react";
const AccountBalance: React.FC = () => {
const [account, accountError] = useKeybanAccount();
if (accountError) throw accountError;
const [balance, balanceError] = useKeybanAccountBalance(account);
if (balanceError) throw balanceError;
return <div>Balance: {balance}</div>;
};
Remarks
- Balance Format: The balance is returned as a string representing the amount in the smallest denomination (e.g., wei). You may need to format it to a human-readable format (e.g., Ether) using utility functions.
- Real-Time Updates: The hook subscribes to balance changes, so your component will re-render automatically when the balance updates.
- Error Handling: Always check the
errorelement to handle any issues that might occur during balance retrieval. - Ensure that your component is wrapped within a
KeybanProviderto have access to the Keyban client context.
Throws
- Will throw an error if used outside of a
KeybanProvideror if there's an issue retrieving the balance.