Checking balances
To check the balance of a specific asset, you can use getBalance
method. This function aggregates the amounts of all unspent coins of the given asset in your wallet.
ts
See code in contextimport type { BN } from 'fuels';
import { Provider, Wallet } from 'fuels';
import { LOCAL_NETWORK_URL, WALLET_PVT_KEY, WALLET_PVT_KEY_2 } from '../env';
const provider = await Provider.create(LOCAL_NETWORK_URL);
const myWallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);
// The returned amount is a BigNumber
const balance: BN = await myWallet.getBalance(provider.getBaseAssetId());
console.log('balance', balance);
To retrieve the balances of all assets in your wallet, use the getBalances
method, it returns an array of CoinQuantity
. This is useful for getting a comprehensive view of your holdings.
ts
See code in contextimport { Provider, Wallet } from 'fuels';
import { WALLET_PVT_KEY_2, LOCAL_NETWORK_URL } from '../env';
const provider = await Provider.create(LOCAL_NETWORK_URL);
const myOtherWallet = Wallet.fromPrivateKey(WALLET_PVT_KEY_2, provider);
const { balances } = await myOtherWallet.getBalances();
Full Example
For a full example of how to check balances, see the snippet below:
ts
See code in contextimport type { BN } from 'fuels';
import { Provider, Wallet } from 'fuels';
import { LOCAL_NETWORK_URL, WALLET_PVT_KEY, WALLET_PVT_KEY_2 } from '../env';
const provider = await Provider.create(LOCAL_NETWORK_URL);
const myWallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);
// The returned amount is a BigNumber
const balance: BN = await myWallet.getBalance(provider.getBaseAssetId());
console.log('balance', balance);
const myOtherWallet = Wallet.fromPrivateKey(WALLET_PVT_KEY_2, provider);
const { balances } = await myOtherWallet.getBalances();