-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAllowance.ts
More file actions
90 lines (85 loc) · 2.07 KB
/
useAllowance.ts
File metadata and controls
90 lines (85 loc) · 2.07 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { queryOptions, useQuery } from "@tanstack/react-query";
import type { UseQueryOptions, DefaultError } from "@tanstack/react-query";
import { isAddress, type Address, type Chain, type Client } from "viem";
import { allowance } from "viem-erc20/actions";
import { usePublicClient } from "wagmi";
type UseAllowanceParameters<TData = bigint> = {
owner: Address | undefined;
spender: Address | undefined;
query?: Omit<
UseQueryOptions<bigint, DefaultError, TData>,
"queryFn" | "queryKey" | "enabled"
>;
token: {
address: Address;
chainId: Chain["id"];
};
};
/**
* Generates a query key for the allowance query.
*/
export const allowanceQueryKey = ({
owner,
spender,
token,
}: Omit<UseAllowanceParameters<unknown>, "query">) =>
["allowance", token.chainId, token.address, owner, spender] as const;
/**
* Generates query options for the allowance query.
* Can be used with `queryClient.ensureQueryData` to read from cache.
*/
export const allowanceQueryOptions = <TData = bigint>({
client,
owner,
query,
spender,
token,
}: {
client: Client | undefined;
owner: Address | undefined;
query?: Omit<
UseQueryOptions<bigint, DefaultError, TData>,
"queryFn" | "queryKey" | "enabled"
>;
spender: Address | undefined;
token: {
address: Address;
chainId: Chain["id"];
};
}) =>
queryOptions({
enabled:
!!owner &&
isAddress(owner) &&
!!spender &&
isAddress(spender) &&
!!client,
queryFn: () =>
allowance(client!, {
address: token.address,
owner: owner!,
spender: spender!,
}),
queryKey: allowanceQueryKey({ owner, spender, token }),
...query,
});
/**
* Fetches the ERC20 token allowance for an owner-spender pair.
*/
export const useAllowance = function <TData = bigint>({
owner,
query,
spender,
token,
}: UseAllowanceParameters<TData>) {
const publicClient = usePublicClient({ chainId: token.chainId });
return useQuery(
allowanceQueryOptions({
client: publicClient,
owner,
query,
spender,
token,
}),
);
};