Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Validate data coming from api.curve.fi #191

Merged
merged 3 commits into from
May 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 29 additions & 39 deletions apps/common/contexts/useCurve.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,26 @@
import React, {createContext, useContext, useMemo} from 'react';
import useSWR from 'swr';
import {toAddress} from '@yearn-finance/web-lib/utils/address';
import {baseFetcher, curveFetcher} from '@yearn-finance/web-lib/utils/fetchers';
import {baseFetcher} from '@yearn-finance/web-lib/utils/fetchers';
import {useFetch} from '@common/hooks/useFetch';
import {curveAllGaugesSchema, curveWeeklyFeesSchema} from '@common/schemas/curveSchemas';

import type {SWRResponse} from 'swr';
import type {TDict} from '@yearn-finance/web-lib/types';
import type {TCurveGauges, TCurveGaugesFromYearn} from '@common/types/curves';
import type {TCurveAllGauges, TCurveGauge, TCurveWeeklyFees} from '@common/schemas/curveSchemas';
import type {TCurveGaugesFromYearn} from '@common/types/curves';

type TCurveWeeklyFees = {
weeklyFeesTable: {
date: string;
ts: number;
rawFees: number;
}[];
totalFees: {
fees: number
}
}
type TCoinGeckoPrices = {
usd: number
}
export type TCurveContext = {
curveWeeklyFees: TCurveWeeklyFees;
curveWeeklyFees: TCurveWeeklyFees['data'];
cgPrices: TDict<TCoinGeckoPrices>;
gauges: TCurveGauges[];
gauges: TCurveGauge[];
isLoadingGauges: boolean;
gaugesFromYearn: TCurveGaugesFromYearn[];
}
const defaultProps: TCurveContext = {
const defaultProps: TCurveContext = {
curveWeeklyFees: {
weeklyFeesTable: [],
totalFees: {
Expand All @@ -42,37 +35,35 @@ const defaultProps: TCurveContext = {


const CurveContext = createContext<TCurveContext>(defaultProps);
export const CurveContextApp = ({children}: {children: React.ReactElement}): React.ReactElement => {
/* 🔵 - Yearn Finance ******************************************************
** Fetch all the CurveGauges to be able to create some new if required
***************************************************************************/
const {data: curveWeeklyFees} = useSWR(
'https://api.curve.fi/api/getWeeklyFees',
curveFetcher,
{revalidateOnFocus: false}
) as SWRResponse<TCurveWeeklyFees>;

const {data: cgPrices} = useSWR(
export const CurveContextApp = ({children}: { children: React.ReactElement }): React.ReactElement => {
const {data: curveWeeklyFees} = useFetch<TCurveWeeklyFees>({
endpoint: 'https://api.curve.fi/api/getWeeklyFees',
schema: curveWeeklyFeesSchema
});

const {data: cgPrices} = useSWR(
'https://api.coingecko.com/api/v3/simple/price?ids=curve-dao-token&vs_currencies=usd',
baseFetcher,
{revalidateOnFocus: false}
) as SWRResponse<TDict<TCoinGeckoPrices>>;

/* 🔵 - Yearn Finance ******************************************************
** Fetch all the CurveGauges to be able to create some new if required
***************************************************************************/
const {data: gaugesWrapper, isLoading: isLoadingGauges} = useFetch<TCurveAllGauges>({
endpoint: 'https://api.curve.fi/api/getAllGauges?blockchainId=ethereum',
schema: curveAllGaugesSchema
});

const {data: gaugesWrapper, isLoading: isLoadingGauges} = useSWR(
'https://api.curve.fi/api/getAllGauges?blockchainId=ethereum',
curveFetcher,
{revalidateOnFocus: false}
);

const {data: gaugesFromYearn} = useSWR(
const {data: gaugesFromYearn} = useSWR(
'https://api.yearn.finance/v1/chains/1/apy-previews/curve-factory',
baseFetcher,
{revalidateOnFocus: false}
) as SWRResponse<TCurveGaugesFromYearn[]>;

const gauges = useMemo((): TCurveGauges[] => {
const _gaugesForMainnet: TCurveGauges[] = [];
for (const gauge of Object.values(gaugesWrapper || {})) {
const gauges = useMemo((): TCurveGauge[] => {
const _gaugesForMainnet: TCurveGauge[] = [];
for (const gauge of Object.values(gaugesWrapper?.data || {})) {
if (gauge.is_killed) {
continue;
}
Expand All @@ -93,8 +84,8 @@ export const CurveContextApp = ({children}: {children: React.ReactElement}): Rea
/* 🔵 - Yearn Finance ******************************************************
** Setup and render the Context provider to use in the app.
***************************************************************************/
const contextValue = useMemo((): TCurveContext => ({
curveWeeklyFees: curveWeeklyFees || defaultProps.curveWeeklyFees,
const contextValue = useMemo((): TCurveContext => ({
curveWeeklyFees: curveWeeklyFees?.data || defaultProps.curveWeeklyFees,
cgPrices: cgPrices || defaultProps.cgPrices,
gauges: gauges || defaultProps.gauges,
isLoadingGauges: isLoadingGauges || defaultProps.isLoadingGauges,
Expand All @@ -108,6 +99,5 @@ export const CurveContextApp = ({children}: {children: React.ReactElement}): Rea
);
};


export const useCurve = (): TCurveContext => useContext(CurveContext);
export default useCurve;
67 changes: 67 additions & 0 deletions apps/common/schemas/curveSchemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {z} from 'zod';

export const curveWeeklyFeesSchema = z.object({
success: z.boolean().optional(),
data: z.object({
weeklyFeesTable: z
.object({
date: z.string(),
ts: z.number(),
rawFees: z.number()
})
.array()
.optional()
.nullable(),
totalFees: z.object({
fees: z.number()
})
}),
generatedTimeMs: z.number().optional()
});

const curveGaugeSchema = z.object({
poolUrls: z.object({
swap: z.string().array().optional().nullable(),
deposit: z.string().array().optional().nullable(),
withdraw: z.string().array().optional().nullable()
}).optional(),
swap: z.string().optional(),
swap_token: z.string().optional(),
name: z.string(),
shortName: z.string().optional(),
gauge: z.string().optional(),
swap_data: z
.object({virtual_price: z.string().or(z.number().optional())})
.optional(),
gauge_data: z.object({
inflation_rate: z.string().optional(),
working_supply: z.string().optional()
}).optional(),
gauge_controller: z.object({
gauge_relative_weight: z.string().optional(),
get_gauge_weight: z.string().optional(),
inflation_rate: z.string().optional()
}).optional(),
factory: z.boolean(),
side_chain: z.boolean().optional(),
is_killed: z.boolean().optional(),
hasNoCrv: z.boolean().optional(),
type: z.string().optional(),
lpTokenPrice: z.number().nullable().optional(),
rewardPerGauge: z.string().array().optional()
});

export const curveAllGaugesSchema = z.object({
success: z.boolean().optional(),
data: z.record(
z.string(),
curveGaugeSchema
),
generatedTimeMs: z.number().optional()
});

export type TCurveWeeklyFees = z.infer<typeof curveWeeklyFeesSchema>;

export type TCurveGauge = z.infer<typeof curveGaugeSchema>;

export type TCurveAllGauges = z.infer<typeof curveAllGaugesSchema>;
26 changes: 0 additions & 26 deletions apps/common/types/curves.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,32 +18,6 @@ export type TCurveGaugesFromYearn = {
block: number,
}

export type TCurveGauges = {
gauge_name: string
swap: string
swap_token: string
name: string
gauge: string
type: string
side_chain: boolean
is_killed: boolean
factory: boolean
gauge_controller: {
get_gauge_weight: string
gauge_relative_weight: string
inflation_rate: string
}
gauge_data: {
working_supply: string
inflation_rate: string
}
swap_data: {
virtual_price: string
},
rewardPerGauge?: string[]
rewardPerTokenPerGauge?: TDict<BigNumber>
}

export type TCurveGaugeVersionRewards = {
v3: TDict<TDict<BigNumber>>,
}
4 changes: 2 additions & 2 deletions apps/ybribe/components/bribe/GaugeBribeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ import {addReward} from '@yBribe/utils/actions/addReward';

import type {BigNumber} from 'ethers';
import type {ChangeEvent, ReactElement} from 'react';
import type {TCurveGauges} from '@common/types/curves';
import type {TCurveGauge} from '@common/schemas/curveSchemas';
import type {TNormalizedBN} from '@common/types/types';


function GaugeBribeModal({currentGauge, onClose}: {currentGauge: TCurveGauges, onClose: VoidFunction}): ReactElement {
function GaugeBribeModal({currentGauge, onClose}: {currentGauge: TCurveGauge, onClose: VoidFunction}): ReactElement {
const {chainID, safeChainID} = useChainID();
const {address, provider, isActive, openLoginModal, onSwitchChain} = useWeb3();
const {refresh} = useBribes();
Expand Down
4 changes: 2 additions & 2 deletions apps/ybribe/components/bribe/GaugeListRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {useBribes} from '@yBribe/contexts/useBribes';
import type {BigNumber} from 'ethers';
import type {ReactElement} from 'react';
import type {TAddress, TDict} from '@yearn-finance/web-lib/types';
import type {TCurveGauges} from '@common/types/curves';
import type {TCurveGauge} from '@common/schemas/curveSchemas';

function GaugeRowItemWithExtraData({address, value}: {address: TAddress, value: BigNumber}): ReactElement {
const {tokens, prices} = useYearn();
Expand All @@ -40,7 +40,7 @@ function GaugeRowItemWithExtraData({address, value}: {address: TAddress, value:
);
}

function GaugeListRow({currentGauge}: {currentGauge: TCurveGauges}): ReactElement {
function GaugeListRow({currentGauge}: {currentGauge: TCurveGauge}): ReactElement {
const {isActive} = useWeb3();
const {currentRewards, nextRewards} = useBribes();
const [hasModal, set_hasModal] = useState(false);
Expand Down
4 changes: 2 additions & 2 deletions apps/ybribe/components/claim/GaugeListRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {claimReward} from '@yBribe/utils/actions/claimReward';
import type {BigNumber} from 'ethers';
import type {ReactElement} from 'react';
import type {TAddress, TDict} from '@yearn-finance/web-lib/types';
import type {TCurveGauges} from '@common/types/curves';
import type {TCurveGauge} from '@common/schemas/curveSchemas';

function GaugeRowItemWithExtraData({
address,
Expand Down Expand Up @@ -78,7 +78,7 @@ function GaugeRowItemAPR({address, value}: {address: TAddress, value: BigNumber}
}


function GaugeListRow({currentGauge, category}: {currentGauge: TCurveGauges, category: string}): ReactElement {
function GaugeListRow({currentGauge, category}: {currentGauge: TCurveGauge, category: string}): ReactElement {
const {isActive, provider} = useWeb3();
const {currentRewards, nextRewards, claimable, dryRunClaimRewards, refresh} = useBribes();
const [txStatusClaim, set_txStatusClaim] = useState(defaultTxStatus);
Expand Down
6 changes: 3 additions & 3 deletions apps/ybribe/components/rewardFeed/RewardFeedTableRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import {useYearn} from '@common/contexts/useYearn';
import type {BigNumber} from 'ethers';
import type {ReactElement} from 'react';
import type {TAddress} from '@yearn-finance/web-lib/types';
import type {TCurveGauge} from '@common/schemas/curveSchemas';
import type {TYDaemonGaugeRewardsFeed} from '@common/schemas/yDaemonGaugeRewardsFeedSchema';
import type {TCurveGauges} from '@common/types/curves';

function RewardFeedRowItemWithExtraData({
address,
Expand Down Expand Up @@ -43,8 +43,8 @@ function RewardFeedRowItemWithExtraData({
function RewardFeedTableRow({currentRewardAdded}: {currentRewardAdded: TYDaemonGaugeRewardsFeed[0]}): ReactElement | null {
const {gauges} = useCurve();

const gaugesObject = useMemo((): {[key: string]: TCurveGauges} => {
const _gaugesObject: {[key: string]: TCurveGauges} = {};
const gaugesObject = useMemo((): {[key: string]: TCurveGauge} => {
const _gaugesObject: {[key: string]: TCurveGauge} = {};
for (const gauge of gauges) {
_gaugesObject[toAddress(gauge.gauge)] = gauge;
}
Expand Down
8 changes: 4 additions & 4 deletions pages/ybribe/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import type {BigNumber} from 'ethers';
import type {NextRouter} from 'next/router';
import type {ReactElement, ReactNode} from 'react';
import type {TAddress} from '@yearn-finance/web-lib/types';
import type {TCurveGauges} from '@common/types/curves';
import type {TCurveGauge} from '@common/schemas/curveSchemas';
import type {TSortDirection} from '@common/types/types';

function GaugeList(): ReactElement {
Expand All @@ -43,7 +43,7 @@ function GaugeList(): ReactElement {
return bribeValue;
}, [prices, tokens]);

const filteredGauges = useMemo((): TCurveGauges[] => {
const filteredGauges = useMemo((): TCurveGauge[] => {
if (category === 'claimable') {
return gauges.filter((gauge): boolean => {
const currentClaimableMapV3 = Object.values(claimable?.v3?.[toAddress(gauge.gauge)] || {});
Expand All @@ -57,7 +57,7 @@ function GaugeList(): ReactElement {
});
}, [category, gauges, currentRewards, nextRewards, claimable]);

const searchedGauges = useMemo((): TCurveGauges[] => {
const searchedGauges = useMemo((): TCurveGauge[] => {
const gaugesToSearch = [...filteredGauges];

if (searchValue === '') {
Expand All @@ -69,7 +69,7 @@ function GaugeList(): ReactElement {
});
}, [filteredGauges, searchValue]);

const sortedGauges = useMemo((): TCurveGauges[] => {
const sortedGauges = useMemo((): TCurveGauge[] => {
if (sort.sortBy === 'name') {
return searchedGauges.sort((a, b): number => stringSort({a: a.name, b: b.name, sortDirection: sort.sortDirection}));
}
Expand Down
12 changes: 6 additions & 6 deletions pages/ybribe/offer-bribe.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import Wrapper from '@yBribe/Wrapper';
import type {BigNumber} from 'ethers';
import type {NextRouter} from 'next/router';
import type {ReactElement, ReactNode} from 'react';
import type {TCurveGauges} from '@common/types/curves';
import type {TCurveGauge} from '@common/schemas/curveSchemas';
import type {TSortDirection} from '@common/types/types';

function GaugeList(): ReactElement {
Expand All @@ -45,9 +45,9 @@ function GaugeList(): ReactElement {
return bribeValue;
}, [prices, tokens]);

const standardGauges = useMemo((): TCurveGauges[] => gauges.filter((gauge): boolean => !gauge.factory), [gauges]);
const factoryGauges = useMemo((): TCurveGauges[] => gauges.filter((gauge): boolean => gauge.factory), [gauges]);
const filteredGauges = useMemo((): TCurveGauges[] => {
const standardGauges = useMemo((): TCurveGauge[] => gauges.filter((gauge): boolean => !gauge.factory), [gauges]);
const factoryGauges = useMemo((): TCurveGauge[] => gauges.filter((gauge): boolean => gauge.factory), [gauges]);
const filteredGauges = useMemo((): TCurveGauge[] => {
if (category === 'standard') {
return standardGauges;
}
Expand All @@ -57,7 +57,7 @@ function GaugeList(): ReactElement {
return gauges;
}, [category, gauges, factoryGauges, standardGauges]);

const searchedGauges = useMemo((): TCurveGauges[] => {
const searchedGauges = useMemo((): TCurveGauge[] => {
const gaugesToSearch = [...filteredGauges];

if (searchValue === '') {
Expand All @@ -69,7 +69,7 @@ function GaugeList(): ReactElement {
});
}, [filteredGauges, searchValue]);

const sortedGauges = useMemo((): TCurveGauges[] => {
const sortedGauges = useMemo((): TCurveGauge[] => {
if (sort.sortBy === 'name') {
return searchedGauges.sort((a, b): number => stringSort({a: a.name, b: b.name, sortDirection: sort.sortDirection}));
}
Expand Down
12 changes: 9 additions & 3 deletions pages/ycrv/holdings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,17 @@ function Holdings(): ReactElement {
}, []);

const latestCurveFeesValue = useMemo((): number => {
if (curveWeeklyFees?.weeklyFeesTable?.[0]?.rawFees > 0) {
Majorfi marked this conversation as resolved.
Show resolved Hide resolved
return curveWeeklyFees.weeklyFeesTable[0].rawFees;
const {weeklyFeesTable} = curveWeeklyFees;

if (!weeklyFeesTable) {
return 0;
}

if (weeklyFeesTable[0]?.rawFees > 0) {
return weeklyFeesTable[0].rawFees;
}
return curveWeeklyFees?.weeklyFeesTable?.[1]?.rawFees || 0;

return weeklyFeesTable[1]?.rawFees || 0;
}, [curveWeeklyFees]);

const currentVeCRVAPY = useMemo((): number => {
Expand Down