Skip to content
This repository has been archived by the owner on Sep 2, 2024. It is now read-only.

Commit

Permalink
feat: fetch TVL across all networks using subgraphs
Browse files Browse the repository at this point in the history
  • Loading branch information
therealemjy committed Jun 18, 2024
1 parent 9317a18 commit a3e365c
Show file tree
Hide file tree
Showing 14 changed files with 241 additions and 115 deletions.
4 changes: 4 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
VITE_SUBGRAPH_MARKETS_URL_ETHEREUM=
VITE_SUBGRAPH_MARKETS_URL_ARBITRUM_ONE=
VITE_SUBGRAPH_MARKETS_URL_BSC_MAINNET=
VITE_SUBGRAPH_MARKETS_URL_OPBNB_MAINNET=
61 changes: 32 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,46 +1,49 @@
# Getting Started with Create React App
# Venus Protocol Landing Page

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
<p align="center">
<img src="https://venus.io/share.png">
</p>

## Available Scripts
Official repository for the [Venus protocol](https://venus.io) landing page.

In the project directory, you can run:
## Getting started

### `yarn start`
Install dependencies with yarn

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
```ssh
yarn
```

The page will reload if you make edits.\
You will also see any lint errors in the console.
Define environment variables by making a copy of `.env.example` and renaming it to `.env` (make sure to add values for each environment variable).

### `yarn test`
Start the development server

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
```ssh
yarn start
```

### `yarn build`
## Useful commands

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
Check Typescript code

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
```ssh
yarn tsc
```

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
Lint code

### `yarn eject`
```ssh
yarn lint
```

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
Generate production build

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
```ssh
yarn build
```

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
Start application with production build

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).
```ssh
yarn preview
```
9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"@testing-library/user-event": "^13.5.0",
"axios": "^0.26.1",
"classnames": "^2.3.1",
"graphql": "^16.8.1",
"graphql-request": "^7.0.1",
"normalize.css": "^8.0.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
Expand All @@ -26,7 +28,9 @@
"preview": "vite preview",
"lint:fix": "yarn lint --fix && yarn pretty --write",
"lint": "yarn run eslint .",
"pretty": "yarn prettier \"src/**/*.{js,jsx,ts,tsx,html,json,md}\" public/**/*.html --check"
"pretty": "yarn prettier \"src/**/*.{js,jsx,ts,tsx,html,json,md}\" public/**/*.html --check",
"generate-subgraph-types": "dotenv -- graphql-codegen --config src/subgraph/codegen.ts",
"postinstall": "yarn run generate-subgraph-types"
},
"browserslist": {
"production": [
Expand All @@ -41,6 +45,8 @@
]
},
"devDependencies": {
"@graphql-codegen/cli": "5.0.2",
"@graphql-codegen/client-preset": "4.2.6",
"@types/jest": "^29.5.12",
"@types/node": "^20.12.12",
"@types/react": "^18.3.3",
Expand All @@ -49,6 +55,7 @@
"@typescript-eslint/parser": "^7.11.0",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^9.0.0",
"dotenv-cli": "^7.4.2",
"eslint": "^8",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^18.0.0",
Expand Down
36 changes: 6 additions & 30 deletions src/api/hooks/useProposals.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,8 @@
import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { fetchProposalCount } from '../index';

export const useProposalsCountFromApi = () => {
const [data, setData] = useState<number>();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | undefined>();

const fetchData = () => {
fetchProposalCount()
.then(res => {
setData(res);
setIsLoading(false);
})
.catch(e => {
setError(e);
setIsLoading(false);
});
};

useEffect(() => {
setIsLoading(true);
fetchData();
}, []);

return {
data,
isLoading,
error,
fetchData,
};
};
export const useProposalsCountFromApi = () =>
useQuery({
queryKey: ['proposalCount'],
queryFn: fetchProposalCount,
});
112 changes: 78 additions & 34 deletions src/api/hooks/useVenusApi.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,86 @@
import { useEffect, useState } from 'react';
import { MarketMapped } from '../types';
import { getMarketsToRender, getTotal } from '../utils';
import fetchMarkets from '../index';
import { useQuery } from '@tanstack/react-query';
import { convertCentsToUsd, getMarketsToRender, scale } from '../utils';
import getLegacyPoolMarkets from '../index';
import { getIsolatedMarkets } from '../../subgraph/queries/getIsolatedMarkets';
import { MainChainId } from '../../subgraph/types';

const chainIds = Object.values(MainChainId).filter(
(chainId): chainId is MainChainId => !Number.isNaN(Number(chainId)),
);

export const useVenusApi = () => {
const [data, setData] = useState<MarketMapped[]>();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | undefined>();

const fetchData = () => {
fetchMarkets()
.then(res => {
setData(res);
setIsLoading(false);
})
.catch(e => {
setError(e);
setIsLoading(false);
});
};
const {
data: getLegacyPoolMarketsData,
isLoading: isGetLegacyPoolMarketsLoading,
error: getLegacyPoolMarketsError,
refetch,
} = useQuery({
queryKey: ['legacyPoolMarkets'],
queryFn: getLegacyPoolMarkets,
});

const {
data: getIsolatedPoolMarketsData,
isLoading: isGetIsolatedPoolMarketsLoading,
error: getIsolatedPoolMarketsError,
} = useQuery({
queryKey: ['isolatedPoolMarkets'],
queryFn: async () => {
const results = await Promise.all(chainIds.map(chainId => getIsolatedMarkets({ chainId })));
return results.map(result => result.markets).flat();
},
});

const topMarkets = getMarketsToRender(getLegacyPoolMarketsData);

const marketCount =
(getLegacyPoolMarketsData?.length || 0) + (getIsolatedPoolMarketsData?.length || 0);

const legacyPool = (getLegacyPoolMarketsData ?? []).reduce(
(acc, data) => ({
marketSize: acc.marketSize + data.totalSupplyUsd,
borrowedSum: acc.borrowedSum + data.totalBorrowsUsd,
liquiditySum: acc.liquiditySum + data.liquidity,
}),
{
marketSize: 0,
borrowedSum: 0,
liquiditySum: 0,
},
);

const isolatedPools = (getIsolatedPoolMarketsData ?? []).reduce(
(acc, data) => {
const underlyingTokenPriceUsd = convertCentsToUsd(data.underlyingPriceCents);

const totalSupplyTokens = scale(data.totalSupplyMantissa, data.underlyingDecimals);
const totalSupplyUsd = totalSupplyTokens * underlyingTokenPriceUsd;

useEffect(() => {
setIsLoading(true);
fetchData();
}, []);
const totalBorrowsTokens = scale(data.totalBorrowsMantissa, data.underlyingDecimals);
const totalBorrowsUsd = totalBorrowsTokens * underlyingTokenPriceUsd;

const markets = getMarketsToRender(data);
const marketSize = getTotal('totalSupplyUsd', data);
const borrowedSum = getTotal('totalBorrowsUsd', data);
const liquiditySum = getTotal('liquidity', data);
return {
marketSize: acc.marketSize + totalSupplyUsd,
borrowedSum: acc.borrowedSum + totalBorrowsUsd,
liquiditySum: acc.liquiditySum + (totalSupplyUsd - totalBorrowsUsd),
};
},
{
marketSize: 0,
borrowedSum: 0,
liquiditySum: 0,
},
);

return {
marketSize,
borrowedSum,
liquiditySum,
markets,
isLoading,
error,
fetchData,
marketSize: legacyPool.marketSize + isolatedPools.marketSize,
borrowedSum: legacyPool.borrowedSum + isolatedPools.borrowedSum,
liquiditySum: legacyPool.liquiditySum + isolatedPools.liquiditySum,
topMarkets,
marketCount,
chainCount: chainIds.length,
isLoading: isGetLegacyPoolMarketsLoading || isGetIsolatedPoolMarketsLoading,
error: getLegacyPoolMarketsError || getIsolatedPoolMarketsError,
refetch,
};
};
16 changes: 4 additions & 12 deletions src/api/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,22 +65,14 @@ export const getMarketsToRender = (markets?: MarketMapped[]) => {
return sortedMarkets.slice(0, 5).sort(sortBySupplyApy);
};

const sumArray = (numbers: number[]) => numbers.reduce((partialSum, a) => partialSum + a, 0);

const addSpaceBeforeUSDSymbol = (string: string) => string.replace(/^(\D+)/, '$\u00a0');

export const getTotal = (
key: 'totalSupplyUsd' | 'totalBorrowsUsd' | 'liquidity',
markets?: MarketMapped[],
) => {
if (!markets) return [];
const totalSupplyUsd = markets.map(i => i[key]);
const sum = sumArray(totalSupplyUsd);
const formattedSum = new Intl.NumberFormat('en-EN', {
export const formatUsd = (value: number) => {
const formattedValue = new Intl.NumberFormat('en-EN', {
style: 'currency',
currency: 'USD',
}).format(sum);
return addSpaceBeforeUSDSymbol(formattedSum);
}).format(value);
return addSpaceBeforeUSDSymbol(formattedValue);
};

export const nFormatter = (num: number, digits = 2) => {
Expand Down
13 changes: 13 additions & 0 deletions src/components/Market/Market.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@
flex-direction: column;
justify-content: space-between;
width: 100%;
border-bottom: 1px solid var(--color-card-border);
padding-bottom: 16px;
margin-bottom: 16px;

@media (min-width: 640px) {
flex-direction: row;
Expand Down Expand Up @@ -115,6 +118,16 @@
}
}

.totalDescription {
width: 100%;
text-align: center;
font-size: 0.75rem;

span {
color: #00C38E;
}
}

.launchBtnDesktop {
display: none;
@media (min-width: 1280px) {
Expand Down
Loading

0 comments on commit a3e365c

Please sign in to comment.