Skip to content

Commit

Permalink
fix(mfi-v2-ui): points improvement
Browse files Browse the repository at this point in the history
  • Loading branch information
k0beLeenders committed Nov 22, 2023
1 parent a9d5e2c commit db561eb
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { firebaseApi } from "@mrgnlabs/marginfi-v2-ui-state";
import { WalletButton } from "~/components/common/Wallet";
import { useWalletContext } from "~/hooks/useWalletContext";
import { MrgnTooltip } from "~/components/common/MrgnTooltip";

interface PointsSignInProps {}

export const PointsSignIn: FC<PointsSignInProps> = ({}) => {
Expand All @@ -23,10 +22,8 @@ export const PointsSignIn: FC<PointsSignInProps> = ({}) => {
return;
}
toast.info("Logging in...");
const blockhashInfo = await connection.getLatestBlockhash();
try {
await firebaseApi.login(wallet);
// localStorage.setItem("authData", JSON.stringify(signedAuthData));
await firebaseApi.login(wallet.publicKey.toBase58());
toast.success("Logged in successfully");
} catch (loginError: any) {
toast.error(loginError.message);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,8 @@ export const PointsSignUp: FC<PointsSignUpProps> = ({ referralCode }) => {
return;
}
toast.info("Logging in...");
const blockhashInfo = await connection.getLatestBlockhash();
try {
await firebaseApi.signup(wallet, finalReferralCode);
// localStorage.setItem("authData", JSON.stringify(signedAuthData));
await firebaseApi.signup(wallet.publicKey.toBase58(), finalReferralCode);
toast.success("Signed up successfully");
} catch (signupError: any) {
toast.error(signupError.message);
Expand Down
14 changes: 9 additions & 5 deletions apps/marginfi-v2-ui/src/hooks/useFirebaseAccount.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { firebaseApi } from "@mrgnlabs/marginfi-v2-ui-state";
import { onAuthStateChanged } from "firebase/auth";
import { useEffect } from "react";
import { useRouter } from "next/router";

import { toast } from "react-toastify";
import { useUserProfileStore } from "~/store";
import { useWalletContext } from "./useWalletContext";
import React from "react";

const useFirebaseAccount = () => {
const { connected, walletAddress } = useWalletContext();
const { query: routerQuery } = useRouter();

const referralCode = React.useMemo(() => routerQuery.referralCode as string | undefined, [routerQuery.referralCode]);

const [checkForFirebaseUser, setFirebaseUser, signoutFirebaseUser, fetchPoints, resetPoints, hasUser] =
useUserProfileStore((state) => [
Expand All @@ -18,10 +24,6 @@ const useFirebaseAccount = () => {
state.hasUser,
]);

useEffect(() => {
console.log({ hasUser });
}, [hasUser]);

useEffect(() => {
// NOTE: if more point-specific logic is added, move this to a separate hook
const unsubscribe = onAuthStateChanged(firebaseApi.auth, (newUser) => {
Expand All @@ -39,8 +41,10 @@ const useFirebaseAccount = () => {
// Wallet connection side effect (auto-login attempt)
useEffect(() => {
if (!walletAddress) return;

firebaseApi.loginOrSignup(walletAddress.toBase58(), referralCode).catch(console.error);
checkForFirebaseUser(walletAddress.toBase58());
}, [walletAddress, checkForFirebaseUser]);
}, [walletAddress, checkForFirebaseUser, referralCode]);

// Wallet disconnection/change side effect (auto-logout)
useEffect(() => {
Expand Down
6 changes: 1 addition & 5 deletions apps/marginfi-v2-ui/src/pages/api/user/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ initFirebaseIfNeeded();

export interface LoginRequest {
walletAddress: string;
// method: SigningMethod;
// signedAuthDataRaw: string;
}

export default async function handler(req: NextApiRequest<LoginRequest>, res: any) {
Expand Down Expand Up @@ -50,17 +48,15 @@ export default async function handler(req: NextApiRequest<LoginRequest>, res: an
return res.status(status).json({ error: error.message });
}*/

let user;
try {
const userResult = await getFirebaseUserByWallet(walletAddress);
if (userResult === undefined) {
await logLoginAttempt(walletAddress, null, "", false);
Sentry.captureException({ message: "User not found" });
return res.status(STATUS_NOT_FOUND).json({ error: "User not found" });
} else {
await logLoginAttempt(walletAddress, user.uid, "", true);
await logLoginAttempt(walletAddress, userResult.uid, "", true);
}
user = userResult;
} catch (error: any) {
Sentry.captureException(error);
return res.status(STATUS_INTERNAL_ERROR).json({ error: error.message }); // An unexpected error occurred
Expand Down
46 changes: 22 additions & 24 deletions apps/marginfi-v2-ui/src/pages/api/user/signup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import base58 from "bs58";
import nacl from "tweetnacl";
import {
SigningMethod,
SignupPayload,
STATUS_BAD_REQUEST,
STATUS_UNAUTHORIZED,
STATUS_INTERNAL_ERROR,
Expand All @@ -21,9 +20,7 @@ initFirebaseIfNeeded();

export interface SignupRequest {
walletAddress: string;
payload: SignupPayload;
// method: SigningMethod;
// signedAuthDataRaw: string;
payload: firebaseApi.SignupPayload;
}

export default async function handler(req: NextApiRequest<SignupRequest>, res: any) {
Expand All @@ -33,26 +30,27 @@ export default async function handler(req: NextApiRequest<SignupRequest>, res: a
walletAddress,
});

// try {
// const signupData = validateAndUnpackSignupData(signedAuthDataRaw, method);
// signer = signupData.signer.toBase58();
// payload = signupData.payload;
// } catch (error: any) {
// Sentry.captureException(error);
// let status;
// switch (error.message) {
// case "Invalid signup tx":
// case "Invalid signup payload":
// status = STATUS_BAD_REQUEST;
// break;
// case "Invalid signature":
// status = STATUS_UNAUTHORIZED;
// break;
// default:
// status = STATUS_INTERNAL_ERROR;
// }
// return res.status(status).json({ error: error.message });
// }
/* signing logic
try {
const signupData = validateAndUnpackSignupData(signedAuthDataRaw, method);
signer = signupData.signer.toBase58();
payload = signupData.payload;
} catch (error: any) {
Sentry.captureException(error);
let status;
switch (error.message) {
case "Invalid signup tx":
case "Invalid signup payload":
status = STATUS_BAD_REQUEST;
break;
case "Invalid signature":
status = STATUS_UNAUTHORIZED;
break;
default:
status = STATUS_INTERNAL_ERROR;
}
return res.status(status).json({ error: error.message });
}*/

try {
const user = await getFirebaseUserByWallet(walletAddress);
Expand Down
11 changes: 1 addition & 10 deletions apps/marginfi-v2-ui/src/pages/points.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from "react";

import Link from "next/link";
import { useRouter } from "next/router";

import { Button } from "@mui/material";
import FileCopyIcon from "@mui/icons-material/FileCopy";
Expand All @@ -14,23 +13,19 @@ import { PageHeader } from "~/components/common/PageHeader";
import {
PointsLeaderBoard,
PointsOverview,
PointsSignIn,
PointsSignUp,
PointsCheckingUser,
PointsConnectWallet,
} from "~/components/desktop/Points";

const Points = () => {
const { connected } = useWalletContext();
const { query: routerQuery } = useRouter();

const [currentFirebaseUser, hasUser, userPointsData] = useUserProfileStore((state) => [
state.currentFirebaseUser,
state.hasUser,
state.userPointsData,
]);

const referralCode = React.useMemo(() => routerQuery.referralCode as string | undefined, [routerQuery.referralCode]);
const [isReferralCopied, setIsReferralCopied] = React.useState(false);

return (
Expand All @@ -41,12 +36,8 @@ const Points = () => {
<PointsConnectWallet />
) : currentFirebaseUser ? (
<PointsOverview userPointsData={userPointsData} />
) : hasUser === null ? (
<PointsCheckingUser />
) : hasUser ? (
<PointsSignIn />
) : (
<PointsSignUp referralCode={referralCode} />
<PointsCheckingUser />
)}
<div className="w-2/3 flex justify-center items-center gap-5">
<Button
Expand Down
26 changes: 8 additions & 18 deletions packages/marginfi-v2-ui-state/src/lib/firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,13 @@ interface UserData {
id: string;
}

async function loginOrSignup(wallet: Wallet) {
const walletAddress = wallet.publicKey.toBase58();
async function loginOrSignup(walletAddress: string, referralCode?: string) {
const user = await getUser(walletAddress);

if (user) {
await login(wallet);
await login(walletAddress);
} else {
await signup(wallet);
await signup(walletAddress, referralCode);
}
}

Expand Down Expand Up @@ -71,13 +70,8 @@ const LoginPayloadStruct = object({
});
type LoginPayload = Infer<typeof LoginPayloadStruct>;

async function login(wallet: Wallet) {
// const authData = { uuid: uuidv4() };
// const signedAuthDataRaw =
// signingMethod === "tx" ? await signLoginTx(wallet, authData, blockhash) : await signLoginMemo(wallet, authData);
await loginWithAddress(wallet.publicKey.toBase58());

// return { signingMethod, signedAuthDataRaw };
async function login(walletAddress: string) {
await loginWithAddress(walletAddress);
}

const SignupPayloadStruct = object({
Expand All @@ -86,7 +80,7 @@ const SignupPayloadStruct = object({
});
type SignupPayload = Infer<typeof SignupPayloadStruct>;

async function signup(wallet: Wallet, referralCode?: string) {
async function signup(walletAddress: string, referralCode?: string) {
if (referralCode !== undefined && typeof referralCode !== "string") {
throw new Error("Invalid referral code provided.");
}
Expand All @@ -96,15 +90,11 @@ async function signup(wallet: Wallet, referralCode?: string) {
uuid,
referralCode,
};
// const signedAuthDataRaw =
// signingMethod === "tx" ? await signSignupTx(wallet, authData, blockhash) : await signSignupMemo(wallet, authData);

await signupWithAddress(wallet.publicKey.toBase58(), authData);

// return { signingMethod, signedAuthDataRaw };
await signupWithAddress(walletAddress, authData);
}

export { getUser, signup, login, SignupPayloadStruct, LoginPayloadStruct };
export { getUser, loginOrSignup, signup, login, SignupPayloadStruct, LoginPayloadStruct };
export type { UserData, SignupPayload };

// ----------------------------------------------------------------------------
Expand Down

0 comments on commit db561eb

Please sign in to comment.