-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathuseBalance.ts
76 lines (70 loc) · 2.12 KB
/
useBalance.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import type { BN, BytesLike } from 'fuels';
import { Address } from 'fuels';
import { type UseNamedQueryParams, useNamedQuery } from '../core';
import { QUERY_KEYS } from '../utils';
import { useProvider } from './useProvider';
type UseBalanceParams = {
/**
* The address to fetch the balance for.
* @deprecated Use `account` instead.
*/
address?: string | null;
/**
* The account to fetch the balance for.
*/
account?: string | null;
/**
* The asset ID to fetch the balance for.
*/
assetId?: BytesLike;
/**
* Additional query parameters to customize the behavior of `useNamedQuery`.
*/
query?: UseNamedQueryParams<'balance', BN | null, Error, BN | null>;
};
// @TODO: Add a link to fuel connector's documentation.
/**
* A hook that returns the balance of the user.
*
* @params {object} The options to fetch the balance for.
* - `address`: The address to fetch the balance for.
* - `assetId`: The asset ID to fetch the balance for.
*
* @returns {object} An object containing:
* - `balance`: The balance of the user.
* - {@link https://tanstack.com/query/latest/docs/framework/react/reference/useQuery | `...queryProps`}: Destructured properties from `useQuery` result.
*
* @examples
* ```ts
* const { balance } = useBalance({address: '0x1234', assetId: '0x1234'});
* console.log(balance.format());
* ```
*/
export const useBalance = ({
address,
account,
assetId,
query,
}: UseBalanceParams) => {
const { provider } = useProvider();
const _address = account ?? address ?? undefined;
return useNamedQuery('balance', {
queryKey: QUERY_KEYS.balance(_address, assetId, provider),
queryFn: async () => {
try {
if (!provider) throw new Error('Provider is needed');
const baseAssetId = assetId || provider.getBaseAssetId();
const currentFuelBalance = await provider.getBalance(
Address.fromString(_address || ''),
baseAssetId,
);
return currentFuelBalance || null;
} catch (_error: unknown) {
return null;
}
},
placeholderData: null,
enabled: !!provider && !!_address,
...query,
});
};