useLinkAccount.ts raw
1 import { useState } from "react";
2 import { toast } from "sonner";
3 import { useAlbyMe } from "src/hooks/useAlbyMe";
4
5 import { useNodeConnectionInfo } from "src/hooks/useNodeConnectionInfo";
6 import { BudgetRenewalType, ListAppsResponse } from "src/types";
7 import { request } from "src/utils/request";
8 import { KeyedMutator } from "swr";
9
10 export enum LinkStatus {
11 SharedNode,
12 ThisNode,
13 OtherNode,
14 Unlinked,
15 }
16
17 export function useLinkAccount(
18 reloadAlbyAccountApp: KeyedMutator<ListAppsResponse>
19 ) {
20 const { data: me, mutate: reloadAlbyMe } = useAlbyMe();
21 const { data: nodeConnectionInfo } = useNodeConnectionInfo();
22 const [loading, setLoading] = useState(false);
23
24 let linkStatus: LinkStatus | undefined;
25 if (me && nodeConnectionInfo) {
26 if (me.keysend_pubkey === nodeConnectionInfo.pubkey) {
27 linkStatus = LinkStatus.ThisNode;
28 } else if (me.shared_node) {
29 linkStatus = LinkStatus.SharedNode;
30 } else if (me.keysend_pubkey) {
31 linkStatus = LinkStatus.OtherNode;
32 } else {
33 linkStatus = LinkStatus.Unlinked;
34 }
35 }
36
37 const loadingLinkStatus = linkStatus === undefined;
38
39 async function linkAccount(budget: number, renewal: BudgetRenewalType) {
40 try {
41 setLoading(true);
42
43 await request("/api/alby/link-account", {
44 method: "POST",
45 headers: {
46 "Content-Type": "application/json",
47 },
48 body: JSON.stringify({
49 budget,
50 renewal,
51 }),
52 });
53 // update the link status and get the newly-created Alby Account app
54 await Promise.all([reloadAlbyMe(), reloadAlbyAccountApp()]);
55 toast("Your Alby Hub has successfully been linked to your Alby Account");
56 } catch (e) {
57 console.error(e);
58 toast.error("Your Alby Hub couldn't be linked to your Alby Account", {
59 description: "Did you already link another Alby Hub?",
60 });
61 } finally {
62 setLoading(false);
63 }
64 }
65
66 return { loading, loadingLinkStatus, linkStatus, linkAccount };
67 }
68