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

feat: Goldsky Dropdown #286

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
43 changes: 43 additions & 0 deletions src/apollo/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,49 @@ export const healthClient = new ApolloClient({
cache: new InMemoryCache(),
})

export const blockClientGoldSky = new ApolloClient({
uri: 'https://api.goldsky.com/api/public/project_cl7gjtydo00g30hx10fzo6f8z/subgraphs/ethereum-blocks/prod/gn',
cache: new InMemoryCache(),
queryDeduplication: true,
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
},
})

export const clientGoldSky = new ApolloClient({
uri: 'https://uniswap-eth.goldsky.com',
cache: new InMemoryCache({
typePolicies: {
Token: {
// Singleton types that have no identifying field can use an empty
// array for their keyFields.
keyFields: false,
},
Pool: {
// Singleton types that have no identifying field can use an empty
// array for their keyFields.
keyFields: false,
},
},
}),
queryDeduplication: true,
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
},
})

export const blockClient = new ApolloClient({
uri: 'https://api.thegraph.com/subgraphs/name/blocklytics/ethereum-blocks',
cache: new InMemoryCache(),
Expand Down
2 changes: 2 additions & 0 deletions src/components/Header/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import NetworkDropdown from 'components/Menu/NetworkDropdown'
import { useActiveNetworkVersion } from 'state/application/hooks'
import { networkPrefix } from 'utils/networkPrefix'
import { AutoColumn } from 'components/Column'
import DataSourceDropdown from 'components/Menu/DataSouceDropdown'

const HeaderFrame = styled.div`
display: grid;
Expand Down Expand Up @@ -182,6 +183,7 @@ export default function Header() {
</HeaderLinks>
</HeaderRow>
<HeaderControls>
<DataSourceDropdown />
<NetworkDropdown />
<SearchSmall />
<Menu />
Expand Down
100 changes: 100 additions & 0 deletions src/components/Menu/DataSouceDropdown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { RowFixed } from 'components/Row'
import useTheme from 'hooks/useTheme'
import React, { useState, useRef } from 'react'
import { ChevronDown } from 'react-feather'
import { useAlternateL1DataSource } from 'state/application/hooks'
import styled from 'styled-components'
import { useOnClickOutside } from 'hooks/useOnClickOutside'
import { AutoColumn } from 'components/Column'
import { TYPE } from 'theme'

const Container = styled.div`
position: relative;
z-index: 40;
`

const Wrapper = styled.div`
border-radius: 12px;
background-color: ${({ theme }) => theme.bg1};
padding: 6px 8px;
margin-right: 12px;

:hover {
cursor: pointer;
opacity: 0.7;
}
`

const DataSourceOption = styled.div`
cursor: pointer;
:hover {
opacity: 0.7;
}
`

const LogoWrapper = styled.img`
width: 20px;
height: 20px;
`

const FlyOut = styled.div`
background-color: ${({ theme }) => theme.bg1};
position: absolute;
top: 40px;
left: 0;
border-radius: 12px;
padding: 16px;
width: 270px;
`

const GRAPH_LOGO_ADDRESS =
'https://w7.pngwing.com/pngs/338/918/png-transparent-the-graph-grt-coin-cryptocoin-exchange-coins-crypto-blockchain-cryptocurrency-logo-glyph-icon.png'
const GOLDKSY_LOGO_ADDRESS =
'https://res.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco,dpr_1/ro3dajnkee1js9y98j64'

export default function DataSourceDropdown() {
const theme = useTheme()

const [isAlternate, setIsAlternate] = useAlternateL1DataSource()

const [showMenu, setShowMenu] = useState(false)

const node = useRef<HTMLDivElement>(null)
useOnClickOutside(node, () => setShowMenu(false))

return (
<Container ref={node}>
<Wrapper onClick={() => setShowMenu(!showMenu)}>
<RowFixed>
<LogoWrapper
src={isAlternate ? GOLDKSY_LOGO_ADDRESS : GRAPH_LOGO_ADDRESS}
style={{ borderRadius: '4px', overflow: 'hidden' }}
/>
<TYPE.main fontSize="14px" color={theme.white} ml="8px" mt="-2px" mr="2px" style={{ whiteSpace: 'nowrap' }}>
{isAlternate ? 'Goldsky' : 'Subgraph'}
</TYPE.main>
<ChevronDown size="20px" />
</RowFixed>
</Wrapper>
{showMenu && (
<FlyOut>
<AutoColumn gap="16px">
<TYPE.main color={theme.text3} fontWeight={600} fontSize="16px">
Select data source
</TYPE.main>
<DataSourceOption>
<TYPE.main color={theme.white} onClick={() => setIsAlternate(true)} style={{ cursor: 'pointer' }}>
Goldsky
</TYPE.main>
</DataSourceOption>
<DataSourceOption>
<TYPE.main color={theme.white} onClick={() => setIsAlternate(false)} style={{ cursor: 'pointer' }}>
Subgraph
</TYPE.main>
</DataSourceOption>
</AutoColumn>
</FlyOut>
)}
</Container>
)
}
52 changes: 28 additions & 24 deletions src/data/protocol/derived.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,35 +105,39 @@ export function useDerivedProtocolTVLHistory() {
if (!addresses) {
return
}

const accum: { [key: number]: ChartDayData } = {}

// fetch all data for each pool
const data = await addresses
.slice(0, POOL_COUNT_FOR_AGGREGATE) // @TODO: must be replaced with aggregate with subgraph data fixed.
.reduce(async (accumP: Promise<{ [key: number]: ChartDayData }>, address) => {
const accum = await accumP
if (POOL_HIDE[currentNetwork.id].includes(address)) {
return accum
}
const { data } = await fetchPoolChartData(address, dataClient)
if (!data) return accum
dispatch(updatePoolChartData({ poolAddress: address, chartData: data, networkId: currentNetwork.id }))
data.map((poolDayData: PoolChartEntry) => {
const { date, totalValueLockedUSD, volumeUSD } = poolDayData
const roundedDate = date
if (!accum[roundedDate]) {
accum[roundedDate] = {
tvlUSD: 0,
date: roundedDate,
volumeUSD: 0,
}
await Promise.all(
addresses
.slice(0, POOL_COUNT_FOR_AGGREGATE) // @TODO: must be replaced with aggregate with subgraph data fixed.
.map(async (address) => {
if (POOL_HIDE[currentNetwork.id].includes(address)) {
return
}
accum[roundedDate].tvlUSD = accum[roundedDate].tvlUSD + totalValueLockedUSD
accum[roundedDate].volumeUSD = accum[roundedDate].volumeUSD + volumeUSD
const { data } = await fetchPoolChartData(address, dataClient)
if (!data) return
dispatch(updatePoolChartData({ poolAddress: address, chartData: data, networkId: currentNetwork.id }))
data.forEach((poolDayData: PoolChartEntry) => {
const { date, totalValueLockedUSD, volumeUSD } = poolDayData
const roundedDate = date
if (!accum[roundedDate]) {
accum[roundedDate] = {
tvlUSD: 0,
date: roundedDate,
volumeUSD: 0,
}
}
accum[roundedDate].tvlUSD = accum[roundedDate].tvlUSD + totalValueLockedUSD
accum[roundedDate].volumeUSD = accum[roundedDate].volumeUSD + volumeUSD
})
return
})
return accum
}, Promise.resolve({} as { [key: number]: ChartDayData }))
)

// Format as array
setChartData({ ...chartData, [currentNetwork.id]: Object.values(data) })
setChartData({ ...chartData, [currentNetwork.id]: Object.values(accum) })
}

if (!chartData) {
Expand Down
2 changes: 2 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import ListUpdater from './state/lists/updater'
import ThemeProvider, { FixedGlobalStyle, ThemedGlobalStyle } from './theme'
import { ApolloProvider } from '@apollo/client/react'
import { client } from 'apollo/client'
import ResetUpdater from 'state/global/updater'

const GOOGLE_ANALYTICS_ID: string | undefined = process.env.REACT_APP_GOOGLE_ANALYTICS_ID
if (typeof GOOGLE_ANALYTICS_ID === 'string') {
Expand Down Expand Up @@ -48,6 +49,7 @@ function Updaters() {
<TokenUpdater />
<PoolUpdater />
<ApplicationUpdater />
<ResetUpdater />
</>
)
}
Expand Down
18 changes: 11 additions & 7 deletions src/pages/Home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { notEmpty } from 'utils'
import TransactionsTable from '../../components/TransactionsTable'
import { useAllTokenData } from 'state/tokens/hooks'
import { MonoSpace } from 'components/shared'
import { useActiveNetworkVersion } from 'state/application/hooks'
import { useActiveNetworkVersion, useAlternateL1DataSource, useDataClient } from 'state/application/hooks'
import { useTransformedVolumeData } from 'hooks/chart'
import { SmallOptionButton } from 'components/Button'
import { VolumeWindow } from 'types'
Expand Down Expand Up @@ -53,6 +53,13 @@ export default function Home() {
// Hot fix to remove errors in TVL data while subgraph syncs.
const [chartData] = useProtocolChartData()

// Reset hover values when switching data sources
const [isAlternate] = useAlternateL1DataSource()
useEffect(() => {
setLiquidityHover(undefined)
setVolumeHover(undefined)
}, [isAlternate])

useEffect(() => {
setLiquidityHover(undefined)
setVolumeHover(undefined)
Expand Down Expand Up @@ -117,12 +124,9 @@ export default function Home() {

const [volumeWindow, setVolumeWindow] = useState(VolumeWindow.weekly)

const tvlValue = useMemo(() => {
if (liquidityHover) {
return formatDollarAmount(liquidityHover, 2, true)
}
return formatDollarAmount(protocolData?.tvlUSD, 2, true)
}, [liquidityHover, protocolData?.tvlUSD])
const tvlValue = liquidityHover
? formatDollarAmount(liquidityHover, 2, true)
: formatDollarAmount(protocolData?.tvlUSD, 2, true)

return (
<PageWrapper>
Expand Down
4 changes: 4 additions & 0 deletions src/state/application/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,7 @@ export const updateSubgraphStatus = createAction<{
export const updateActiveNetworkVersion = createAction<{ activeNetworkVersion: NetworkInfo }>(
'application/updateActiveNetworkVersion'
)

export const updateShouldUserAlternateL1DataSource = createAction<{ shouldUse: boolean }>(
'application/updateShouldUserAlternateL1DataSource'
)
22 changes: 20 additions & 2 deletions src/state/application/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
celoBlockClient,
bscClient,
bscBlockClient,
clientGoldSky,
blockClientGoldSky,
} from 'apollo/client'
import { NetworkInfo, SupportedNetwork } from 'constants/networks'
import { useCallback, useMemo } from 'react'
Expand All @@ -25,6 +27,7 @@ import {
removePopup,
setOpenModal,
updateActiveNetworkVersion,
updateShouldUserAlternateL1DataSource,
updateSubgraphStatus,
} from './actions'

Expand Down Expand Up @@ -113,6 +116,19 @@ export function useSubgraphStatus(): [
return [status, update]
}

// returns a function that allows adding a popup
export function useAlternateL1DataSource(): [boolean, (shouldUse: boolean) => void] {
const dispatch = useDispatch()
const shouldUse = useSelector((state: AppState) => state.application.shouldUseAlternateL1DataSource)
const update = useCallback(
(shouldUse: boolean) => {
dispatch(updateShouldUserAlternateL1DataSource({ shouldUse }))
},
[dispatch]
)
return [shouldUse, update]
}

// returns a function that allows adding a popup
export function useActiveNetworkVersion(): [NetworkInfo, (activeNetworkVersion: NetworkInfo) => void] {
const dispatch = useDispatch()
Expand All @@ -129,9 +145,10 @@ export function useActiveNetworkVersion(): [NetworkInfo, (activeNetworkVersion:
// get the apollo client related to the active network
export function useDataClient(): ApolloClient<NormalizedCacheObject> {
const [activeNetwork] = useActiveNetworkVersion()
const [isUsingAlternateL1DataSource] = useAlternateL1DataSource()
switch (activeNetwork.id) {
case SupportedNetwork.ETHEREUM:
return client
return isUsingAlternateL1DataSource ? clientGoldSky : client
case SupportedNetwork.ARBITRUM:
return arbitrumClient
case SupportedNetwork.OPTIMISM:
Expand All @@ -150,9 +167,10 @@ export function useDataClient(): ApolloClient<NormalizedCacheObject> {
// get the apollo client related to the active network for fetching blocks
export function useBlockClient(): ApolloClient<NormalizedCacheObject> {
const [activeNetwork] = useActiveNetworkVersion()
const [isUsingAlternateL1DataSource] = useAlternateL1DataSource()
switch (activeNetwork.id) {
case SupportedNetwork.ETHEREUM:
return blockClient
return isUsingAlternateL1DataSource ? blockClientGoldSky : blockClient
case SupportedNetwork.ARBITRUM:
return arbitrumBlockClient
case SupportedNetwork.OPTIMISM:
Expand Down
6 changes: 6 additions & 0 deletions src/state/application/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
ApplicationModal,
setOpenModal,
updateActiveNetworkVersion,
updateShouldUserAlternateL1DataSource,
} from './actions'
import { EthereumNetworkInfo } from '../../constants/networks'

Expand All @@ -24,6 +25,7 @@ export interface ApplicationState {
headBlock: number | undefined
}
readonly activeNetworkVersion: NetworkInfo
readonly shouldUseAlternateL1DataSource: boolean
}

const initialState: ApplicationState = {
Expand All @@ -36,6 +38,7 @@ const initialState: ApplicationState = {
headBlock: undefined,
},
activeNetworkVersion: EthereumNetworkInfo,
shouldUseAlternateL1DataSource: true,
}

export default createReducer(initialState, (builder) =>
Expand Down Expand Up @@ -78,4 +81,7 @@ export default createReducer(initialState, (builder) =>
.addCase(updateActiveNetworkVersion, (state, { payload: { activeNetworkVersion } }) => {
state.activeNetworkVersion = activeNetworkVersion
})
.addCase(updateShouldUserAlternateL1DataSource, (state, { payload: { shouldUse } }) => {
state.shouldUseAlternateL1DataSource = shouldUse
})
)
Loading