useOnchainAddress.ts raw
1 import useSWRImmutable from "swr/immutable";
2
3 import React from "react";
4
5 import { toast } from "sonner";
6 import { request } from "src/utils/request";
7 import { swrFetcher } from "src/utils/swr";
8
9 export function useOnchainAddress() {
10 // Use useSWRImmutable to avoid address randomly changing after deposit (e.g. on page re-focus on the channel order page)
11 const swr = useSWRImmutable<string>("/api/wallet/address", swrFetcher, {
12 revalidateOnMount: true,
13 });
14 const [isLoading, setLoading] = React.useState(false);
15
16 const getNewAddress = React.useCallback(async () => {
17 setLoading(true);
18 try {
19 const address = await request<string>("/api/wallet/new-address", {
20 method: "POST",
21 headers: {
22 "Content-Type": "application/json",
23 },
24 });
25 if (!address) {
26 throw new Error("No address in response");
27 }
28 swr.mutate(address, false);
29 return address;
30 } catch (error) {
31 toast.error("Failed to request a new address", {
32 description: "" + error,
33 });
34 } finally {
35 setLoading(false);
36 }
37 }, [swr]);
38
39 return React.useMemo(
40 () => ({
41 ...swr,
42 getNewAddress,
43 loadingAddress: isLoading || !swr.data,
44 }),
45 [swr, getNewAddress, isLoading]
46 );
47 }
48