-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAddTokenToWallet.ts
More file actions
50 lines (43 loc) · 1.26 KB
/
useAddTokenToWallet.ts
File metadata and controls
50 lines (43 loc) · 1.26 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
import { useMutation } from "@tanstack/react-query";
import { type Address, type Chain } from "viem";
import { useAccount, useWalletClient } from "wagmi";
import watchAsset from "@hemilabs/wallet-watch-asset";
import { useEnsureConnectedTo } from "./useEnsureConnectedTo";
type Token = {
address: Address;
chainId: Chain["id"];
extensions?: {
logoURI?: string;
};
};
type Options = {
token: Token;
};
/**
* Provides a mutation to add a token to the user's wallet.
* Ensures the wallet is connected to the correct chain before adding.
*/
export const useAddTokenToWallet = function (options: Options) {
const { address } = useAccount();
const ensureConnectedTo = useEnsureConnectedTo();
const { data: walletClient } = useWalletClient({
chainId: options.token.chainId,
});
return useMutation({
async mutationFn() {
const { token } = options;
await ensureConnectedTo(options.token.chainId);
return watchAsset(
// @ts-expect-error walletClient is a different type, but it matches the Provider interface
walletClient,
address,
{
address: token.address,
chainId: token.chainId,
logoURI: token.extensions?.logoURI,
},
localStorage,
);
},
});
};