import { QueryKey, useQuery, UseQueryOptions, UseQueryResult, } from "@tanstack/react-query" import { ONE_MINUTE_MS } from "../utils/time" import { QUERY_KEYS } from "./constants" import { useAuthApiClient } from "./useAuthApiClient" import type { GetCurrentAccountResponse, RewardsMats } from "../api" import { useRewardsApiClient } from "./useRewardsApiClient" type GetCurrentAccountResponseWithMats = GetCurrentAccountResponse & { mats: RewardsMats[] totalMats: number } type UseGetCurrentAccountOptions = Omit< UseQueryOptions, "queryKey" | "queryFn" > /** * Hook to fetch current account with mats */ export function useGetCurrentAccount< TSelected = GetCurrentAccountResponseWithMats, >( options: UseGetCurrentAccountOptions = {}, ): UseQueryResult & { queryKey: QueryKey } { const authApiClient = useAuthApiClient() const rewardsApiClient = useRewardsApiClient() const queryKey = [QUERY_KEYS.ACCOUNT, QUERY_KEYS.CURRENT] const query = useQuery({ queryKey, queryFn: async () => { const currentAccount = await authApiClient.getCurrentAccount() if (!currentAccount) { throw new Error("No current account found") } const linkedWallets = currentAccount?.linkedAccounts?.filter( (account) => account.type === "wallet", ) if (!linkedWallets || linkedWallets.length === 0) { throw new Error("No linked wallets found for the current account") } const addresses = linkedWallets.map((account) => account.evmAddress) try { /** Mats balances aggregated from all linked wallets */ const mats = await Promise.all( addresses.map((address) => rewardsApiClient.getRewardsMats(address)), ) const totalMats = mats.reduce( (sumMats, currentMats) => sumMats + currentMats.seasonTwo.mats, 0, ) return { ...currentAccount, mats, totalMats, } } catch { // If account is not recognized by Rewards API, it will return 404. // To prevent errors we return default values return { ...currentAccount, mats: [ { seasonOne: { mats: 0, rank: null }, seasonTwo: { mats: 0, rank: null }, }, ], totalMats: 0, } } }, staleTime: options.staleTime ?? ONE_MINUTE_MS, retry: options.retry ?? 1, ...options, }) return { ...query, queryKey, } }