Skip to content

Commit

Permalink
DEV-1144 unify styling, remove redundant type, remove console log (#975)
Browse files Browse the repository at this point in the history
* DEV-1144 unify styling, remove redundant type, remove console log

* DEV-1144 improve price calculation logic, rmeove hr

* DEV-1144 code styling
  • Loading branch information
michalstruck authored Oct 12, 2024
1 parent 1aa8826 commit cf3f214
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 41 deletions.
3 changes: 2 additions & 1 deletion cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"pnpm-lock.yaml"
],
"words": [
"lokalise",
"arrayify",
"chartjs",
"clsx",
Expand All @@ -43,6 +42,7 @@
"JWTs",
"keccak",
"Localise",
"lokalise",
"merkle",
"nextjs",
"nullifer",
Expand All @@ -58,6 +58,7 @@
"timestamptz",
"toastify",
"unarchived",
"USDCE",
"Worldcoin",
"zustand"
]
Expand Down
8 changes: 0 additions & 8 deletions web/api/v2/public/apps/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,6 @@ import {
} from "./graphql/get-app-rankings.generated";
import { getSdk as getHighlightsSdk } from "./graphql/get-app-web-highlights.generated";

export type GetAppsResponse = {
app_rankings: {
top_apps: ReturnType<typeof rankApps>;
highlights: ReturnType<typeof rankApps>;
};
categories: ReturnType<typeof getAllLocalisedCategories>;
};

const queryParamsSchema = yup.object({
page: yup.number().integer().min(1).default(1).notRequired(),
limit: yup.number().integer().min(1).max(500).notRequired().default(250),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,19 @@ export type GetAccumulativeTransactionDataReturnType = Awaited<
ReturnType<typeof getAccumulativeTransactionData>
>;

const calculateUSDAmount = (
tokenAmount: number,
tokenPrice: number,
tokenDecimals: number,
) => {
return (tokenAmount * tokenPrice) / 10 ** tokenDecimals;
};

export const getAccumulativeTransactionData = async (
appId: string,
): Promise<{
accumulativeTransactions: PaymentMetadata[];
accumulatedAmountUSD: number;
accumulatedTokenAmountUSD: number;
}> => {
try {
if (!process.env.NEXT_SERVER_INTERNAL_PAYMENTS_ENDPOINT) {
Expand Down Expand Up @@ -46,41 +54,61 @@ export const getAccumulativeTransactionData = async (
new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
) as PaymentMetadata[];

let accumulatedTokenAmount = 0;
const accumulativeTransactions = sortedTransactions.map((transaction) => {
// TODO - floating point issues here? test on real data
accumulatedTokenAmount += Number(transaction.inputTokenAmount);

return {
...transaction,
inputTokenAmount: String(accumulatedTokenAmount),
};
});

// NOTE fetch all tokens, we need to know them before we can calculate the accumulated amount
const tokenPriceResponse = (await (
await fetch(
`${process.env.NEXT_PUBLIC_PRICES_ENDPOINT}?cryptoCurrencies=WLD&fiatCurrencies=USD`,
`${process.env.NEXT_PUBLIC_PRICES_ENDPOINT}?cryptoCurrencies=WLD,USDCE&fiatCurrencies=USD`,
)
).json()) as {
result: {
prices: { WLD: { USD: { amount: string; decimals: number } } };
prices: {
WLD: { USD: { amount: string; decimals: number } };
USDCE: { USD: { amount: string; decimals: number } };
};
};
};

const accumulatedAmountUSD =
(accumulatedTokenAmount *
Number(tokenPriceResponse.result.prices.WLD.USD.amount)) /
10 ** tokenPriceResponse.result.prices.WLD.USD.decimals;
let accumulatedTokenAmountWLD = 0;
let accumulatedTokenAmountUSDCE = 0;
let accumulatedTokenAmountUSD = 0;
const cryptoCurrencies = new Set<"WLD" | "USDCE">();
const accumulativeTransactions = sortedTransactions.map((transaction) => {
cryptoCurrencies.add(transaction.inputToken as "WLD" | "USDCE");

if (transaction.inputToken === "WLD") {
// TODO - floating point issues here? test on real data
accumulatedTokenAmountWLD += Number(transaction.inputTokenAmount);

accumulatedTokenAmountUSD += calculateUSDAmount(
accumulatedTokenAmountWLD,
Number(tokenPriceResponse.result.prices.WLD.USD.amount),
tokenPriceResponse.result.prices.WLD.USD.decimals,
);
} else if (transaction.inputToken === "USDCE") {
accumulatedTokenAmountUSDCE += Number(transaction.inputTokenAmount);

accumulatedTokenAmountUSD += calculateUSDAmount(
accumulatedTokenAmountUSDCE,
Number(tokenPriceResponse!.result.prices.USDCE!.USD.amount),
tokenPriceResponse!.result.prices.USDCE!.USD.decimals,
);
}

return {
...transaction,
inputTokenAmount: String(accumulatedTokenAmountUSD),
};
});

return {
accumulativeTransactions,
accumulatedAmountUSD,
accumulatedTokenAmountUSD,
};
} catch (error) {
logger.warn("Error fetching transaction data", { error });
return {
accumulativeTransactions: [],
accumulatedAmountUSD: 0,
accumulatedTokenAmountUSD: 0,
};
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Chart, ChartProps } from "@/components/Chart";
import { TYPOGRAPHY, Typography } from "@/components/Typography";
import { EngineType, TransactionStatus } from "@/lib/types";
import { ChartData, ChartOptions } from "chart.js";
import clsx from "clsx";
import dayjs from "dayjs";
import tz from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
Expand Down Expand Up @@ -83,8 +84,8 @@ export const GraphsSection = () => {
[transactionsData?.accumulativeTransactions],
);
const accumulatedTransactionAmountUSD = useMemo(
() => transactionsData?.accumulatedAmountUSD,
[transactionsData?.accumulatedAmountUSD],
() => transactionsData?.accumulatedTokenAmountUSD,
[transactionsData?.accumulatedTokenAmountUSD],
);

const stats = useMemo(
Expand All @@ -100,7 +101,6 @@ export const GraphsSection = () => {
() => appStatsData?.app_stats_aggregate.aggregate?.sum?.unique_users ?? 0,
[appStatsData?.app_stats_aggregate.aggregate?.sum?.unique_users],
);
console.log({ totalVerifications, totalUniqueUsers });

const engine = useMemo(
() => appStatsData?.app?.[0]?.engine,
Expand Down Expand Up @@ -171,7 +171,17 @@ export const GraphsSection = () => {
</div>
)}
{!appStatsLoading && !formattedVerificationsChartData && (
<div className="pointer-events-none grid size-full select-none content-center justify-center justify-items-center gap-y-1 rounded-2xl border border-grey-200 px-12">
<div
className={clsx(
{
"size-full":
transactionsLoading || formattedTransactionsChartData,
"aspect-[580/350]":
!transactionsLoading && !formattedTransactionsChartData,
},
"pointer-events-none grid w-full select-none content-center justify-center justify-items-center gap-y-1 rounded-2xl border border-grey-200 px-12",
)}
>
<Typography variant={TYPOGRAPHY.H7} className="text-grey-500">
{engine === EngineType.OnChain
? "Analytics are not available for on-chain apps yet"
Expand All @@ -189,7 +199,7 @@ export const GraphsSection = () => {
)}
{!appStatsLoading && formattedVerificationsChartData && (
<div className="block rounded-2xl border border-grey-200 py-5 sm:hidden">
<div className="flex flex-row gap-x-8 pl-6">
<div className="pl-6">
<Stat
title="Verifications"
mainColorClassName="bg-additional-blue-500"
Expand All @@ -215,8 +225,8 @@ export const GraphsSection = () => {
</div>
)}
{!appStatsLoading && formattedVerificationsChartData && (
<div className="hidden rounded-2xl border border-grey-200 py-5 sm:block">
<div className="flex flex-row gap-x-8 pl-6">
<div className="hidden rounded-2xl border border-grey-200 py-5 sm:block ">
<div className="pl-6">
<Stat
title="Verifications"
mainColorClassName="bg-additional-blue-500"
Expand Down Expand Up @@ -246,7 +256,16 @@ export const GraphsSection = () => {
</div>
)}
{!transactionsLoading && !formattedTransactionsChartData && (
<div className="pointer-events-none grid aspect-[580/350] w-full select-none content-center justify-center justify-items-center gap-y-1 rounded-2xl border border-grey-200 px-12">
<div
className={clsx(
{
"size-full": appStatsLoading || formattedVerificationsChartData,
"aspect-[580/350]":
!appStatsLoading && !formattedVerificationsChartData,
},
"pointer-events-none grid w-full select-none content-center justify-center justify-items-center gap-y-1 rounded-2xl border border-grey-200 px-12",
)}
>
<Typography variant={TYPOGRAPHY.H7} className="text-grey-500">
{engine === EngineType.OnChain
? "Analytics are not available for on-chain apps yet"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const StatCard = (props: {
mainColorClassName: string;
title: string;
value: number | undefined | null;
isLoading: boolean;
changePercentage?: number;
}) => {
return (
Expand All @@ -31,7 +32,8 @@ export const StatCard = (props: {
</div>
<div className="flex items-center gap-x-2">
<Typography variant={TYPOGRAPHY.H3} className="text-grey-700">
{props.value?.toLocaleString() ?? <Skeleton width={65} />}
{props.value?.toLocaleString() ??
(props.isLoading ? <Skeleton width={65} /> : 0)}
</Typography>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ export const StatCards = ({ appId }: { appId: string }) => {
const [timespan] = useAtom(timespanAtom);
const timespanValue = timespan.value;

const { metrics: appMetrics } = useGetMetrics(appId);
const { metrics: appMetrics, loading: isMetricsLoading } =
useGetMetrics(appId);

const impressionsTotal = appMetrics?.impressions;
const impressionsLast7Days = appMetrics?.impressions_7days;
Expand Down Expand Up @@ -68,6 +69,7 @@ export const StatCards = ({ appId }: { appId: string }) => {
timespanValue,
})}
changePercentage={impressionsPercentageChange}
isLoading={isMetricsLoading}
/>
<StatCard
mainColorClassName="bg-blue-500"
Expand All @@ -77,6 +79,7 @@ export const StatCards = ({ appId }: { appId: string }) => {
weekValue: newUsersLast7Days,
timespanValue,
})}
isLoading={isMetricsLoading}
/>
<StatCard
mainColorClassName="bg-blue-500"
Expand All @@ -86,6 +89,7 @@ export const StatCards = ({ appId }: { appId: string }) => {
weekValue: usersLast7Days,
timespanValue,
})}
isLoading={isMetricsLoading}
/>
<StatCard
mainColorClassName="bg-blue-500"
Expand All @@ -95,11 +99,10 @@ export const StatCards = ({ appId }: { appId: string }) => {
weekValue: uniqueUsersLast7Days,
timespanValue,
})}
isLoading={isMetricsLoading}
/>
<div className="h-6 w-px bg-grey-200" />
</div>
</div>
<hr className="border border-grey-200" />
</>
);
};

0 comments on commit cf3f214

Please sign in to comment.