Skip to content

getBalance

Usage

connect() must be called and WalletConnect session must be initiated before account information will be returned.

The getBalance() function returns an account’s balance. If an address is provided, the wallet will return that address’ balance if that address is in the wallet. Otherwise, it will return the currently selected account’s balance. If you want the balance state to automatically be reflected in the dApp, you should use the useBalance hook.

import { Balance, getBalance } from '@puzzlehq/sdk-core';
import { useState } from 'react';
export const Page = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | undefined>();
const [balance, setBalances] = useState<Balance[] | undefined>();
const onClick = async () => {
setLoading(true);
setError(undefined);
try {
const response: GetBalancesResponse = await getBalance({
address: 'aleo1t5ympyhrn6rgk7d0h0ktvmvzlymsnwg6w0c0ns5nac7s8d39x5qqtlaynz',
})
if (response.balances) setBalances(response.balances);
else if (response.error) setError(response.error);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}
return (
<div>
<button
onClick={ onClick }
disabled={ loading }
>
get selected account's balance
</button>
{ balances && balances.map((balance) => (
<>
<p>privateBalance: {balance.privateBalance}</p>
<p>publicBalance: {balance.publicBalance}</p>
</>
))}
{ error && <p>error getting balance: {error}</p> }
</div>
)
}

Types

type GetBalancesResponse = {
balances: Balance[], // balances of currently selected account's Aleo credits
error?: string, // WalletConnect error or Puzzle wallet error
}
type Balance = {
privateBalance: number;
publicBalance: number;
};