xonecas.io
4436
Sl

sesame-labs-coding-assignment / files

sesame-labs-coding-assignment / ui / src / components / AuthenticationForm / index.tsx

2.1 KB
1import axios from "axios";
2import React, { useContext, useState } from "react";
3import { StyledButton } from "../../theme/button";
4import { PageContext } from "../Page";
5
6export function AuthenticationForm() {
7  const [isLoading, setIsLoading] = useState(false);
8  const context = useContext(PageContext);
9
10  if (!context)
11    throw new Error(
12      "AuthenticationForm needs to be a child of a PageContext provider"
13    );
14
15  const handleAuthenticateClick = async (e: React.MouseEvent) => {
16    e.preventDefault();
17    setIsLoading(true);
18
19    // tried to use @metamask/detect-providers but currently has an issue where the type
20    // we need here is not exported.
21    // https://github.com/MetaMask/detect-provider/issues/68
22    const provider = (window as any)?.ethereum;
23    if (provider) {
24      const accounts = await provider.request({
25        method: "eth_requestAccounts",
26      });
27
28      try {
29        const user = await axios
30          .post("/authenticate", {
31            walletAddress: accounts[0],
32          })
33          .then((response) => response.data);
34        context.setUser(user);
35      } catch (e) {
36        console.error(e);
37        context.setError("We we're unable to receive your account details.");
38      }
39    } else {
40      context.setError("Please install the metamask browser extension.");
41    }
42    setIsLoading(false);
43  };
44
45  const handleDeauthenticateClick = async (e: React.MouseEvent) => {
46    e.preventDefault();
47    setIsLoading(true);
48
49    try {
50      await axios.post("/deauthenticate");
51      context.setUser(null);
52    } catch (e) {
53      console.error(e);
54      context.setError(
55        "We are not able to reach the api server, please try again later."
56      );
57    }
58
59    setIsLoading(false);
60  };
61
62  return (
63    <div>
64      {isLoading ? (
65        <div>Loading...</div>
66      ) : context.user ? (
67        <StyledButton onClick={handleDeauthenticateClick}>
68          Sign out
69        </StyledButton>
70      ) : (
71        <StyledButton onClick={handleAuthenticateClick}>
72          Connect with your wallet via MetaMask
73        </StyledButton>
74      )}
75    </div>
76  );
77}