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

Handle all external APIs failure gracefully #146

Merged
merged 6 commits into from
Oct 11, 2024
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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,6 @@
},
"engines": {
"node": "20.x"
}
},
"packageManager": "[email protected]+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}
10 changes: 8 additions & 2 deletions src/app/community/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
Text,
useDisclosure,
} from '@chakra-ui/react';
import fetchWithRetry from '@/utils/fetchWithRetry';

interface OGNFTUserData {
address: string;
Expand All @@ -50,8 +51,13 @@
queryFn: async ({ _queryKey }: any): Promise<OGNFTUserData | null> => {
const address = get(addressAtom) || '0x0';
if (!address) return null;
const data = await fetch(`/api/users/ognft/${address}`);
return data.json();
const data = await fetchWithRetry(
`/api/users/ognft/${address}`,
{},
'Error fetching OG NFT eligibility',
);
if (!data) return null;
return await data.json();
},
refetchInterval: 5000,
};
Expand Down Expand Up @@ -367,7 +373,7 @@
) : !address ? (
'Connect wallet to check eligibility'
) : isOGNFTEligible.isLoading ||
balanceQueryStatus == 'pending' ? (

Check warning on line 376 in src/app/community/page.tsx

View workflow job for this annotation

GitHub Actions / Performs linting, formatting on the application

Expected '===' and instead saw '=='
<Spinner size="sm" />
) : hasNFT ? (
'Claimed'
Expand Down
1 change: 1 addition & 0 deletions src/components/TxButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import mixpanel from 'mixpanel-browser';
import { useEffect, useMemo } from 'react';
import { isMobile } from 'react-device-detect';
import toast from 'react-hot-toast';

Check failure on line 24 in src/components/TxButton.tsx

View workflow job for this annotation

GitHub Actions / Performs linting, formatting on the application

'toast' is defined but never used
import { TwitterShareButton } from 'react-share';
import { Call } from 'starknet';

Expand Down
47 changes: 43 additions & 4 deletions src/store/carmine.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,20 @@ import { PoolInfo, ProtocolAtoms } from './pools';
import { Jediswap } from './jedi.store';
import { atomWithQuery } from 'jotai-tanstack-query';
import { StrategyLiveStatus } from '@/strategies/IStrategy';
import fetchWithRetry from '@/utils/fetchWithRetry';

type CarminePoolData = {
week: number;
week_annualized: number;
launch: number;
launch_annualized: number;
};

type CarmineAPRData = {
tvl: number;
allocation: number;
apy: number;
};

const poolConfigs = [
{ name: 'STRK/USDC Call Pool (STRK)', tokenA: 'STRK', tokenB: 'USDC' },
Expand Down Expand Up @@ -122,15 +136,40 @@ const poolEndpoints = [
export const CarmineAtom = atomWithQuery((get) => ({
queryKey: ['isCarmine'],
queryFn: async ({ queryKey }) => {
const fetchPool = async (endpoint: any) => {
const res = await fetch(`${CONSTANTS.CARMINE_URL}/${endpoint}/apy`);
const fetchPool = async (
endpoint: string,
): Promise<{ data: CarminePoolData }> => {
const res = await fetchWithRetry(
`${CONSTANTS.CARMINE_URL}/${endpoint}/apy`,
{},
'Failed to fetch Carmine data',
);

if (!res) {
return {
data: {
week_annualized: 0,
week: 0,
launch_annualized: 0,
launch: 0,
},
};
}
let data = await res.text();
data = data.replaceAll('NaN', '0');
return JSON.parse(data);
};

const fetchRewardApr = async () => {
const res = await fetch(CONSTANTS.CARMINE_INCENTIVES_URL);
const fetchRewardApr = async (): Promise<{ data: CarmineAPRData }> => {
const res = await fetchWithRetry(
CONSTANTS.CARMINE_INCENTIVES_URL,
{},
'Failed to fetch Carmine incentives data',
);

if (!res) {
return { data: { apy: 0, tvl: 0, allocation: 0 } };
}
let data = await res.text();
data = data.replaceAll('NaN', '0');
return JSON.parse(data);
Expand Down
6 changes: 1 addition & 5 deletions src/store/ekobu.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,9 @@
StrkDexIncentivesAtom,
} from './pools';
import { StrategyLiveStatus } from '@/strategies/IStrategy';
import fetchWithRetry from '@/utils/fetchWithRetry';

Check failure on line 15 in src/store/ekobu.store.ts

View workflow job for this annotation

GitHub Actions / Performs linting, formatting on the application

'fetchWithRetry' is defined but never used
import { getPrice } from '@/utils';

const _fetcher = async (...args: any[]) => {
return fetch(args[0], args[1]).then((res) => res.json());
};

interface EkuboBaseAprDoc {
tokens: Token[];
defiSpringData: DefiSpringData;
Expand Down Expand Up @@ -309,7 +306,6 @@
});

const [ethPrice, strkPrice, usdcPrice] = await Promise.all(pricePromises);

return {
tokens,
defiSpringData,
Expand Down
17 changes: 12 additions & 5 deletions src/store/haiko.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { atom } from 'jotai';
import { AtomWithQueryResult, atomWithQuery } from 'jotai-tanstack-query';
import { IDapp } from './IDapp.store';
import { StrategyLiveStatus } from '@/strategies/IStrategy';
import fetchWithRetry from '@/utils/fetchWithRetry';

type Token = {
address: string;
Expand Down Expand Up @@ -187,13 +188,19 @@ export const haiko = new Haiko();
const HaikoAtoms: ProtocolAtoms = {
baseAPRs: atomWithQuery((get) => ({
queryKey: ['haiko_base_aprs'],
queryFn: async ({ queryKey }) => {
const response = await fetch(`${CONSTANTS.HAIKO.BASE_APR_API}`);
const data = await response.json();

return data;
queryFn: async ({ queryKey }): Promise<Pool[]> => {
const response = await fetchWithRetry(`${CONSTANTS.HAIKO.BASE_APR_API}`, {
headers: {
'Content-Type': 'application/json',
},
}, 'Error fetching haiko base APRs');
if (!response) return [];
const data = await response.json();

return data;
},
})),

pools: atom((get) => {
const poolsInfo = get(StrkDexIncentivesAtom);
const empty: PoolInfo[] = [];
Expand Down
9 changes: 6 additions & 3 deletions src/store/jedi.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { IDapp } from './IDapp.store';
import { AtomWithQueryResult, atomWithQuery } from 'jotai-tanstack-query';
import { BlockInfo, getBlock } from './utils.atoms';
import { StrategyLiveStatus } from '@/strategies/IStrategy';
import fetchWithRetry from '@/utils/fetchWithRetry';

interface MyBaseAprDoc {
id: string;
Expand Down Expand Up @@ -147,15 +148,17 @@ async function getVolumes(block: number) {
variables: {},
});

const res = await fetch(CONSTANTS.JEDI.BASE_API, {
const res = await fetchWithRetry(CONSTANTS.JEDI.BASE_API, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: data,
});
return res.json();
}, 'Error fetching jedi volumes');

if (!res) return { data: { pairs: [] } };
return await res.json();
}

export const jedi = new Jediswap();
Expand Down
18 changes: 13 additions & 5 deletions src/store/myswap.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { IDapp } from './IDapp.store';
import CONSTANTS, { TokenName } from '@/constants';
import { AtomWithQueryResult, atomWithQuery } from 'jotai-tanstack-query';
import { StrategyLiveStatus } from '@/strategies/IStrategy';
import fetchWithRetry from '@/utils/fetchWithRetry';

interface Token {
symbol: string;
Expand Down Expand Up @@ -181,8 +182,13 @@ export class MySwap extends IDapp<IndexedPoolData> {
}
}

const fetch_pools = async () => {
const response = await fetch(`${CONSTANTS.MY_SWAP.POOLS_API}`);
const fetch_pools = async (): Promise<Pools> => {
const response = await fetchWithRetry(
`${CONSTANTS.MY_SWAP.POOLS_API}`,
{},
'Error fetching myswap pools',
);
if (!response) return { pools: [] };
const data = await response.json();
return data;
};
Expand Down Expand Up @@ -213,14 +219,16 @@ const fetchAprData = async (
if (pool_keys.length) {
const pools = await Promise.all(
pool_keys.map(async (pool_key) => {
const response = await fetch(
const response = await fetchWithRetry(
`${CONSTANTS.MY_SWAP.BASE_APR_API}/${pool_key}/overview.json`,
{},
'Error fetching myswap apr data',
);

if (!response) return null;
const data = await response.json();
return data;
}),
);
).then((results) => results.filter((result) => result !== null));

return [pool_name, pools];
}
Expand Down
56 changes: 43 additions & 13 deletions src/store/pools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { AtomWithQueryResult, atomWithQuery } from 'jotai-tanstack-query';
import { CustomAtomWithQueryResult } from '@/utils/customAtomWithQuery';
import { customAtomWithFetch } from '@/utils/customAtomWithFetch';
import { StrategyLiveStatus } from '@/strategies/IStrategy';
import fetchWithRetry from '@/utils/fetchWithRetry';

export enum Category {
Stable = 'Stable Pools',
Expand Down Expand Up @@ -59,6 +60,25 @@ export interface PoolInfo extends PoolMetadata {
};
}

type NostraPoolData = {
id?: string;
address?: string;
isDegen?: boolean;
tokenA?: string;
tokenAAddress?: string;
tokenB?: string;
tokenBAddress?: string;
volume?: string;
fee?: string;
swap?: number;
tvl?: string;
baseApr?: string;
rewardApr?: string;
rewardAllocation?: string;
};

type NostraPools = Record<string, NostraPoolData>;

export interface ProtocolAtoms {
pools: Atom<PoolInfo[]>;
baseAPRs?: Atom<AtomWithQueryResult<any, Error>>;
Expand Down Expand Up @@ -86,20 +106,30 @@ export const StrkDexIncentivesAtom = atom((get) => {

export const StrkIncentivesAtom = atomWithQuery((get) => ({
queryKey: get(StrkIncentivesQueryKeyAtom),
queryFn: async ({ queryKey }) => {
const res = await fetch(CONSTANTS.NOSTRA_DEGEN_INCENTIVE_URL);
let data = await res.text();
data = data.replaceAll('NaN', '0');
const parsedData = JSON.parse(data);

if (queryKey[1] === 'isNostraDex') {
// Filter the data to include only the specific nostra dex pools we are tracking
return Object.values(parsedData).filter((item: any) => {
const id = item.id;
return id === 'ETH-USDC' || id === 'STRK-ETH' || id === 'STRK-USDC';
});
queryFn: async ({ queryKey }): Promise<NostraPools | NostraPoolData[]> => {
try {
const res = await fetchWithRetry(
CONSTANTS.NOSTRA_DEGEN_INCENTIVE_URL,
{},
'Error fetching nostra incentives',
);
if (!res) return [];
let data = await res.text();
data = data.replaceAll('NaN', '0');
const parsedData: NostraPools = JSON.parse(data);

if (queryKey[1] === 'isNostraDex') {
// Filter the data to include only the specific nostra dex pools we are tracking
return Object.values(parsedData).filter((item: any) => {
const id = item.id;
return id === 'ETH-USDC' || id === 'STRK-ETH' || id === 'STRK-USDC';
});
}
return parsedData;
} catch (error) {
console.error('Error fetching nostra incentives: ', error);
return [];
}
return parsedData;
},
}));

Expand Down
20 changes: 12 additions & 8 deletions src/store/utils.atoms.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import CONSTANTS from '@/constants';
import axios from 'axios';
import { atomWithQuery } from 'jotai-tanstack-query';
import { atomWithStorage, createJSONStorage } from 'jotai/utils';
import { addressAtom } from './claims.atoms';
import fetchWithRetry from '@/utils/fetchWithRetry';

export interface BlockInfo {
data: {
Expand Down Expand Up @@ -71,8 +71,9 @@ interface DAppStats {
export const dAppStatsAtom = atomWithQuery((get) => ({
queryKey: ['stats'],
queryFn: async (): Promise<DAppStats> => {
const res = await axios.get('/api/stats');
return res.data;
const res = await fetchWithRetry('/api/stats', {}, 'Error fetching dApp stats');
if (!res) return { tvl: 0 };
return await res.json();
},
}));

Expand Down Expand Up @@ -102,8 +103,9 @@ export const userStatsAtom = atomWithQuery((get) => ({
if (!addr) {
return null;
}
const res = await axios.get(`/api/stats/${addr}`);
return res.data;
const res = await fetchWithRetry(`/api/stats/${addr}`, {}, 'Error fetching user stats');
if (!res) return null;
return await res.json();
},
}));

Expand Down Expand Up @@ -171,16 +173,18 @@ export const blockInfoMinus1DAtom = atomWithQuery((get) => ({
variables: {},
});
console.log('jedi base', 'data', data);
const res = await fetch(CONSTANTS.JEDI.BASE_API, {

const res = await fetchWithRetry(CONSTANTS.JEDI.BASE_API, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: data,
});
}, 'Error fetching block minus 1d');
if (!res) return { data: { blocks: [] } };
console.log('jedi base', 'data2', res.json());
return res.json();
return await res.json();
},
}));

Expand Down
10 changes: 7 additions & 3 deletions src/strategies/delta_neutral_mm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,13 @@ export class DeltaNeutralMM extends IStrategy {
usdValue: Number(amount.toEtherStr()) * price,
tokenInfo: this.token,
};
} catch (e) {
console.log('getTVL err', e);
throw e;
} catch (error) {
console.error('Error fetching TVL:', error);
return {
amount: MyNumber.fromEther('0', this.token.decimals),
usdValue: 0,
tokenInfo: this.token,
};
}
};

Expand Down
Loading
Loading