diff --git a/src/@utils/subgraph.ts b/src/@utils/subgraph.ts index 621381613..8607c0995 100644 --- a/src/@utils/subgraph.ts +++ b/src/@utils/subgraph.ts @@ -25,7 +25,7 @@ import { } from '../@types/subgraph/PoolShares' import { OrdersData_orders as OrdersData } from '../@types/subgraph/OrdersData' import { UserSalesQuery as UsersSalesList } from '../@types/subgraph/UserSalesQuery' -import { PoolLiquidity } from 'src/@types/subgraph/PoolLiquidity' +import { PoolData } from 'src/@types/subgraph/PoolData' export interface UserLiquidity { price: string @@ -285,9 +285,9 @@ const TopSalesQuery = gql` } ` -const poolLiquidityQuery = gql` - query PoolLiquidity($pool: ID!, $owner: String!) { - pool(id: $pool) { +const poolDataQuery = gql` + query PoolData($pool: ID!, $owner: String!, $user: String) { + poolData: pool(id: $pool) { id totalShares poolFee @@ -310,16 +310,20 @@ const poolLiquidityQuery = gql` shares } } - } -` -const userPoolShareQuery = gql` - query PoolShare($pool: ID!, $user: String!) { - pool(id: $pool) { + poolDataUser: pool(id: $pool) { shares(where: { user: $user }) { shares } } + + poolSnapshots(first: 1000, where: { pool: $pool }, orderBy: date) { + date + spotPrice + baseTokenLiquidity + datatokenLiquidity + swapVolume + } } ` @@ -822,33 +826,19 @@ export async function getTopAssetsPublishers( export async function getPoolData( chainId: number, pool: string, - owner: string + owner: string, + user: string ) { const queryVariables = { pool: pool.toLowerCase(), - owner: owner.toLowerCase() + owner: owner.toLowerCase(), + user: user.toLowerCase() } - const response: OperationResult = await fetchData( - poolLiquidityQuery, - queryVariables, - getQueryContext(chainId) - ) - return response?.data?.pool -} -export async function getUserPoolShareBalance( - chainId: number, - pool: string, - accountId: string -): Promise { - const queryVariables = { - pool: pool.toLowerCase(), - user: accountId.toLowerCase() - } - const response: OperationResult = await fetchData( - userPoolShareQuery, + const response: OperationResult = await fetchData( + poolDataQuery, queryVariables, getQueryContext(chainId) ) - return response?.data?.pool?.shares[0]?.shares || '0' + return response?.data } diff --git a/src/components/Asset/AssetActions/Pool/Graph/_constants.ts b/src/components/Asset/AssetActions/Pool/Graph/_constants.ts index 54554876b..6fe4ac566 100644 --- a/src/components/Asset/AssetActions/Pool/Graph/_constants.ts +++ b/src/components/Asset/AssetActions/Pool/Graph/_constants.ts @@ -12,24 +12,11 @@ import { TooltipOptions, defaults } from 'chart.js' -import { gql } from 'urql' export declare type GraphType = 'liquidity' | 'price' | 'volume' export const graphTypes = ['Liquidity', 'Price', 'Volume'] -export const poolHistoryQuery = gql` - query PoolHistory($id: String!) { - poolSnapshots(first: 1000, where: { pool: $id }, orderBy: date) { - date - spotPrice - baseTokenLiquidity - datatokenLiquidity - swapVolume - } - } -` - // Chart.js global defaults ChartJS.register( LineElement, diff --git a/src/components/Asset/AssetActions/Pool/Graph/index.tsx b/src/components/Asset/AssetActions/Pool/Graph/index.tsx index 843903f1a..3cd3fc478 100644 --- a/src/components/Asset/AssetActions/Pool/Graph/index.tsx +++ b/src/components/Asset/AssetActions/Pool/Graph/index.tsx @@ -1,71 +1,29 @@ -import React, { ReactElement, useCallback, useEffect, useState } from 'react' +import React, { ReactElement, useEffect, useState } from 'react' import { ChartData, ChartOptions } from 'chart.js' -import { Bar, Chart, Line } from 'react-chartjs-2' +import { Bar, Line } from 'react-chartjs-2' import Loader from '@shared/atoms/Loader' import { useUserPreferences } from '@context/UserPreferences' import useDarkMode from 'use-dark-mode' import { darkModeConfig } from '../../../../../../app.config' import { LoggerInstance } from '@oceanprotocol/lib' -import { useAsset } from '@context/Asset' -import { OperationResult } from 'urql' -import { PoolHistory } from '../../../../../@types/subgraph/PoolHistory' -import { fetchData, getQueryContext } from '@utils/subgraph' import styles from './index.module.css' import Decimal from 'decimal.js' -import { poolHistoryQuery, lineStyle, GraphType } from './_constants' +import { lineStyle, GraphType } from './_constants' import Nav from './Nav' import { getOptions } from './_utils' +import { PoolData_poolSnapshots as PoolDataPoolSnapshots } from 'src/@types/subgraph/PoolData' -export default function Graph(): ReactElement { +export default function Graph({ + poolSnapshots +}: { + poolSnapshots: PoolDataPoolSnapshots[] +}): ReactElement { const { locale } = useUserPreferences() - const { price, ddo, refreshInterval } = useAsset() const darkMode = useDarkMode(false, darkModeConfig) const [options, setOptions] = useState>() const [graphType, setGraphType] = useState('liquidity') - const [error, setError] = useState() - const [isLoading, setIsLoading] = useState(true) - const [dataHistory, setDataHistory] = useState() const [graphData, setGraphData] = useState>() - const [graphFetchInterval, setGraphFetchInterval] = useState() - - // Helper: fetch pool snapshots data - const fetchPoolHistory = useCallback(async () => { - try { - const queryResult: OperationResult = await fetchData( - poolHistoryQuery, - { id: price.address.toLowerCase() }, - getQueryContext(ddo.chainId) - ) - setDataHistory(queryResult?.data) - setIsLoading(false) - - LoggerInstance.log( - `[pool graph] Fetched pool snapshots:`, - queryResult?.data - ) - } catch (error) { - LoggerInstance.error('[pool graph] Error fetchData: ', error.message) - setError(error) - } - }, [ddo?.chainId, price?.address]) - - // Helper: start interval fetching - const initFetchInterval = useCallback(() => { - if (graphFetchInterval) return - - const newInterval = setInterval(() => { - fetchPoolHistory() - LoggerInstance.log( - `[pool graph] Refetch interval fired after ${refreshInterval / 1000}s` - ) - }, refreshInterval) - setGraphFetchInterval(newInterval) - }, [fetchPoolHistory, graphFetchInterval, refreshInterval]) - - useEffect(() => { - return () => clearInterval(graphFetchInterval) - }, [graphFetchInterval]) // // 0 Get Graph options @@ -77,38 +35,28 @@ export default function Graph(): ReactElement { }, [locale, darkMode.value, graphType]) // - // 1 Fetch all the data on mount - // All further effects depend on the fetched data - // and only do further data checking and manipulation. + // 1 Data manipulation // useEffect(() => { - fetchPoolHistory() - initFetchInterval() - }, [fetchPoolHistory, initFetchInterval]) + if (!poolSnapshots) return - // - // 2 Data manipulation - // - useEffect(() => { - if (!dataHistory?.poolSnapshots) return - - const timestamps = dataHistory.poolSnapshots.map((item) => { + const timestamps = poolSnapshots.map((item) => { const date = new Date(item.date * 1000) return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}` }) let baseTokenLiquidityCumulative = '0' - const liquidityHistory = dataHistory.poolSnapshots.map((item) => { + const liquidityHistory = poolSnapshots.map((item) => { baseTokenLiquidityCumulative = new Decimal(baseTokenLiquidityCumulative) .add(item.baseTokenLiquidity) .toString() return baseTokenLiquidityCumulative }) - const priceHistory = dataHistory.poolSnapshots.map((item) => item.spotPrice) + const priceHistory = poolSnapshots.map((item) => item.spotPrice) let volumeCumulative = '0' - const volumeHistory = dataHistory.poolSnapshots.map((item) => { + const volumeHistory = poolSnapshots.map((item) => { volumeCumulative = new Decimal(volumeCumulative) .add(item.swapVolume) .toString() @@ -133,15 +81,13 @@ export default function Graph(): ReactElement { datasets: [{ ...lineStyle, data, borderColor: `#8b98a9` }] } setGraphData(newGraphData) - LoggerInstance.log('[pool graph] New graph data:', newGraphData) - }, [dataHistory?.poolSnapshots, graphType]) + LoggerInstance.log('[pool graph] New graph data created:', newGraphData) + }, [poolSnapshots, graphType]) return (
- {isLoading ? ( + {!graphData ? ( - ) : error ? ( - {error.message} ) : ( <>