1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-12-02 05:57:29 +01:00

Display TVL (#353)

* get  pools data from graph

* TVL displayed

* ESlint fixes

* Code style fixed on App.tsx

* footer stats display changes

* ApolloProvider wrapping

* config subgraphUri verified

* pool number taken from graph

* Apollo provider fix

* Pools number set fixed

* deleted unused imports

* fix fetch, gatsby build

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* remove apollo client redundant init

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* fix prop

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* update pool count

Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro>

* tooltip added

* small development config refactor

* make sure initial config is actually overwritten with local addresses

* log error on missing subgraphUri

* copy change

Co-authored-by: claudia.holhos <claudia.holhos@hpm.ro>
Co-authored-by: mihaisc <mihai.scarlat@smartcontrol.ro>
Co-authored-by: Matthias Kretschmann <m@kretschmann.io>
This commit is contained in:
claudiaHash 2021-02-11 14:30:29 +02:00 committed by GitHub
parent b043eab047
commit 9991b6dfeb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 130 additions and 115 deletions

View File

@ -1,4 +1,4 @@
import React, { ReactElement, useEffect, useState } from 'react' import React, { ReactElement } from 'react'
import Footer from './organisms/Footer' import Footer from './organisms/Footer'
import Header from './organisms/Header' import Header from './organisms/Header'
import Styles from '../global/Styles' import Styles from '../global/Styles'
@ -7,15 +7,7 @@ import { useSiteMetadata } from '../hooks/useSiteMetadata'
import { useOcean } from '@oceanprotocol/react' import { useOcean } from '@oceanprotocol/react'
import Alert from './atoms/Alert' import Alert from './atoms/Alert'
import { graphql, PageProps, useStaticQuery } from 'gatsby' import { graphql, PageProps, useStaticQuery } from 'gatsby'
import {
ApolloClient,
ApolloProvider,
HttpLink,
InMemoryCache,
NormalizedCacheObject
} from '@apollo/client'
import fetch from 'cross-fetch'
import { ConfigHelperConfig } from '@oceanprotocol/lib/dist/node/utils/ConfigHelper'
const contentQuery = graphql` const contentQuery = graphql`
query AppQuery { query AppQuery {
purgatory: allFile(filter: { relativePath: { eq: "purgatory.json" } }) { purgatory: allFile(filter: { relativePath: { eq: "purgatory.json" } }) {
@ -45,24 +37,9 @@ export default function App({
const { warning } = useSiteMetadata() const { warning } = useSiteMetadata()
const { const {
isInPurgatory: isAccountInPurgatory, isInPurgatory: isAccountInPurgatory,
purgatoryData: accountPurgatory, purgatoryData: accountPurgatory
config
} = useOcean() } = useOcean()
const [client, setClient] = useState<ApolloClient<NormalizedCacheObject>>()
useEffect(() => {
const newClient = new ApolloClient({
link: new HttpLink({
uri: `${
(config as ConfigHelperConfig).subgraphUri
}/subgraphs/name/oceanprotocol/ocean-subgraph`,
fetch
}),
cache: new InMemoryCache()
})
setClient(newClient)
}, [config])
return ( return (
<Styles> <Styles>
<div className={styles.app}> <div className={styles.app}>
@ -78,13 +55,7 @@ export default function App({
state="error" state="error"
/> />
)} )}
{client ? (
<ApolloProvider client={client}>
<main className={styles.main}>{children}</main> <main className={styles.main}>{children}</main>
</ApolloProvider>
) : (
<></>
)}
<Footer /> <Footer />
</div> </div>
</Styles> </Styles>

View File

@ -28,7 +28,9 @@ export default function Tooltip({
trigger, trigger,
disabled, disabled,
className, className,
placement placement,
link,
reference
}: { }: {
content: ReactNode content: ReactNode
children?: ReactNode children?: ReactNode
@ -36,6 +38,8 @@ export default function Tooltip({
disabled?: boolean disabled?: boolean
className?: string className?: string
placement?: Placement placement?: Placement
link?: string
reference?: string
}): ReactElement { }): ReactElement {
const [props, setSpring] = useSpring(() => animation.from) const [props, setSpring] = useSpring(() => animation.from)
@ -72,6 +76,7 @@ export default function Tooltip({
<animated.div style={props}> <animated.div style={props}>
<div className={styles.content} {...attrs}> <div className={styles.content} {...attrs}>
{content} {content}
{link && <a href={link}>{reference}</a>}
<div className={styles.arrow} data-popper-arrow /> <div className={styles.arrow} data-popper-arrow />
</div> </div>
</animated.div> </animated.div>

View File

@ -12,3 +12,7 @@
color: var(--color-secondary) !important; color: var(--color-secondary) !important;
font-size: var(--font-size-small) !important; font-size: var(--font-size-small) !important;
} }
.info {
width: .85rem
}

View File

@ -1,83 +1,47 @@
import { Logger } from '@oceanprotocol/lib'
import React, { ReactElement, useEffect, useState } from 'react' import React, { ReactElement, useEffect, useState } from 'react'
import PriceUnit from '../atoms/Price/PriceUnit'
import axios from 'axios'
import styles from './MarketStats.module.css' import styles from './MarketStats.module.css'
import { useInView } from 'react-intersection-observer' import { gql, useQuery } from '@apollo/client'
import Conversion from '../atoms/Price/Conversion'
import PriceUnit from '../atoms/Price/PriceUnit'
import Tooltip from '../atoms/Tooltip'
interface MarketStatsResponse { const getTotalPoolsValues = gql`
datasets: { query PoolsData {
pools: number poolFactories {
exchanges: number totalValueLocked
none: number totalOceanLiquidity
total: number finalizedPoolCount
} }
owners: number }
ocean: number `
datatoken: number
}
const refreshInterval = 60000 // 60 sec.
export default function MarketStats(): ReactElement { export default function MarketStats(): ReactElement {
const [ref, inView] = useInView() const [totalValueLocked, setTotalValueLocked] = useState<string>()
const [stats, setStats] = useState<MarketStatsResponse>() const [totalOceanLiquidity, setTotalOceanLiquidity] = useState<string>()
const [poolCount, setPoolCount] = useState<number>()
const { data } = useQuery(getTotalPoolsValues)
useEffect(() => { useEffect(() => {
const source = axios.CancelToken.source() if (!data) return
async function getStats() { setTotalValueLocked(data.poolFactories[0].totalValueLocked)
try { setTotalOceanLiquidity(data.poolFactories[0].totalOceanLiquidity)
const response = await axios('https://market-stats.oceanprotocol.com', { setPoolCount(data.poolFactories[0].finalizedPoolCount)
cancelToken: source.token }, [data])
})
if (!response || response.status !== 200) return
setStats(response.data)
} catch (error) {
if (axios.isCancel(error)) {
Logger.log(error.message)
} else {
Logger.error(error.message)
}
}
}
// Update periodically when in viewport
const interval = setInterval(getStats, refreshInterval)
if (!inView) {
clearInterval(interval)
}
getStats()
return () => {
clearInterval(interval)
source.cancel()
}
}, [inView])
return ( return (
<div className={styles.stats} ref={ref}> <div className={styles.stats}>
Total of <strong>{stats?.datasets.total}</strong> data sets & unique <Conversion price={`${totalValueLocked}`} hideApproximateSymbol />{' '}
datatokens published by <strong>{stats?.owners}</strong> accounts. <abbr title="Total Value Locked">TVL</abbr> across{' '}
<br /> <strong>{poolCount}</strong> data set pools that contain{' '}
<PriceUnit <PriceUnit price={totalOceanLiquidity} small className={styles.total} />,
price={`${stats?.ocean}`} plus datatokens for each pool.
small <Tooltip
className={styles.total} className={styles.info}
conversion content="Counted on-chain from our pool factory. Does not filter out data sets in "
/>{' '} reference="list-purgatory"
and{' '} link="https://github.com/oceanprotocol/list-purgatory"
<PriceUnit />
price={`${stats?.datatoken}`}
symbol="datatokens"
small
className={styles.total}
/>{' '}
in <strong>{stats?.datasets.pools}</strong> data set pools.
<br />
<strong>{stats?.datasets.none}</strong> data sets have no price set yet.
</div> </div>
) )
} }

View File

@ -7,6 +7,18 @@ import contractAddresses from '@oceanprotocol/contracts/artifacts/address.json'
const refreshInterval = 5000 // 5 sec. const refreshInterval = 5000 // 5 sec.
export function getDevelopmentConfig(): Partial<ConfigHelperConfig> {
return {
factoryAddress: contractAddresses.development?.DTFactory,
poolFactoryAddress: contractAddresses.development?.BFactory,
fixedRateExchangeAddress: contractAddresses.development?.FixedRateExchange,
metadataContractAddress: contractAddresses.development?.Metadata,
oceanTokenAddress: contractAddresses.development?.Ocean,
// There is no subgraph in barge so we hardcode the Rinkeby one for now
subgraphUri: 'https://subgraph.rinkeby.oceanprotocol.com'
}
}
export function NetworkMonitor(): ReactElement { export function NetworkMonitor(): ReactElement {
const { const {
connect, connect,
@ -28,12 +40,7 @@ export function NetworkMonitor(): ReactElement {
// add local dev values // add local dev values
...(chainId === '8996' && { ...(chainId === '8996' && {
factoryAddress: contractAddresses.development?.DTFactory, ...getDevelopmentConfig()
poolFactoryAddress: contractAddresses.development?.BFactory,
fixedRateExchangeAddress:
contractAddresses.development?.FixedRateExchange,
metadataContractAddress: contractAddresses.development?.Metadata,
oceanTokenAddress: contractAddresses.development?.Ocean
}) })
} }

View File

@ -2,7 +2,7 @@ import React, { ReactElement } from 'react'
import { OceanProvider } from '@oceanprotocol/react' import { OceanProvider } from '@oceanprotocol/react'
import { ConfigHelper, Config } from '@oceanprotocol/lib' import { ConfigHelper, Config } from '@oceanprotocol/lib'
import { web3ModalOpts } from '../utils/wallet' import { web3ModalOpts } from '../utils/wallet'
import { NetworkMonitor } from './NetworkMonitor' import { getDevelopmentConfig, NetworkMonitor } from './NetworkMonitor'
import appConfig from '../../app.config' import appConfig from '../../app.config'
import { import {
ConfigHelperNetworkName, ConfigHelperNetworkName,
@ -10,6 +10,7 @@ import {
} from '@oceanprotocol/lib/dist/node/utils/ConfigHelper' } from '@oceanprotocol/lib/dist/node/utils/ConfigHelper'
import { UserPreferencesProvider } from '../providers/UserPreferences' import { UserPreferencesProvider } from '../providers/UserPreferences'
import PricesProvider from '../providers/Prices' import PricesProvider from '../providers/Prices'
import ApolloClientProvider from '../providers/ApolloClientProvider'
export function getOceanConfig( export function getOceanConfig(
network: ConfigHelperNetworkName | ConfigHelperNetworkId network: ConfigHelperNetworkName | ConfigHelperNetworkId
@ -26,16 +27,26 @@ export default function wrapRootElement({
element: ReactElement element: ReactElement
}): ReactElement { }): ReactElement {
const { network } = appConfig const { network } = appConfig
const oceanInitialConfig = getOceanConfig(network) const oceanInitialConfig = {
...getOceanConfig(network),
// add local dev values
...(network === 'development' && {
...getDevelopmentConfig()
})
}
return ( return (
<OceanProvider <OceanProvider
initialConfig={oceanInitialConfig} initialConfig={oceanInitialConfig}
web3ModalOpts={web3ModalOpts} web3ModalOpts={web3ModalOpts}
> >
<ApolloClientProvider>
<UserPreferencesProvider> <UserPreferencesProvider>
<NetworkMonitor /> <NetworkMonitor />
<PricesProvider>{element}</PricesProvider> <PricesProvider>{element}</PricesProvider>
</UserPreferencesProvider> </UserPreferencesProvider>
</ApolloClientProvider>
</OceanProvider> </OceanProvider>
) )
} }

View File

@ -0,0 +1,53 @@
import {
ApolloClient,
ApolloProvider,
HttpLink,
InMemoryCache,
NormalizedCacheObject
} from '@apollo/client'
import { Logger } from '@oceanprotocol/lib'
import { ConfigHelperConfig } from '@oceanprotocol/lib/dist/node/utils/ConfigHelper'
import { useOcean } from '@oceanprotocol/react'
import fetch from 'cross-fetch'
import React, { useState, useEffect, ReactNode, ReactElement } from 'react'
function createClient(subgraphUri: string) {
const client = new ApolloClient({
link: new HttpLink({
uri: `${subgraphUri}/subgraphs/name/oceanprotocol/ocean-subgraph`,
fetch
}),
cache: new InMemoryCache()
})
return client
}
export default function ApolloClientProvider({
children
}: {
children: ReactNode
}): ReactElement {
const { config } = useOcean()
const [client, setClient] = useState<ApolloClient<NormalizedCacheObject>>()
useEffect(() => {
if (!(config as ConfigHelperConfig)?.subgraphUri) {
Logger.error(
'No subgraphUri defined, preventing ApolloProvider from initialization.'
)
return
}
const newClient = createClient((config as ConfigHelperConfig).subgraphUri)
setClient(newClient)
}, [config])
return client ? (
<ApolloProvider client={client}>{children}</ApolloProvider>
) : (
<></>
)
}
export { ApolloClientProvider }