-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseTokenBalance.ts
More file actions
56 lines (51 loc) · 1.44 KB
/
useTokenBalance.ts
File metadata and controls
56 lines (51 loc) · 1.44 KB
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
import { queryOptions, useQuery } from "@tanstack/react-query";
import { type Address, type Chain, type Client, isAddress } from "viem";
import { balanceOf } from "viem-erc20/actions";
import { useAccount, usePublicClient } from "wagmi";
type TokenBalanceParams = {
address: Address;
chainId: Chain["id"];
};
/**
* Generates a query key for the token balance query.
*/
export const tokenBalanceQueryKey = (
token: TokenBalanceParams,
account: Address | undefined,
) => ["tokenBalance", token.chainId, token.address, account] as const;
/**
* Generates query options for the token balance query.
* Can be used with `queryClient.ensureQueryData` to read from cache.
*/
export const tokenBalanceQueryOptions = ({
account,
client,
token,
}: {
account: Address;
client: Client;
token: TokenBalanceParams;
}) =>
queryOptions({
enabled: isAddress(account) && isAddress(token.address) && !!client,
queryFn: () =>
balanceOf(client, {
account,
address: token.address,
}),
queryKey: tokenBalanceQueryKey(token, account),
});
/**
* Fetches the ERC20 token balance for the connected account.
*/
export const useTokenBalance = function (token: TokenBalanceParams) {
const { address: account } = useAccount();
const publicClient = usePublicClient({ chainId: token.chainId });
return useQuery(
tokenBalanceQueryOptions({
account: account!,
client: publicClient!,
token,
}),
);
};