Skip to content

Commit

Permalink
graphql setup, usd queries integrated to swap and position page
Browse files Browse the repository at this point in the history
  • Loading branch information
vnaysngh-mudrex committed Feb 17, 2024
1 parent 78657c1 commit 92d3954
Show file tree
Hide file tree
Showing 11 changed files with 410 additions and 64 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@
"@web3-react/walletconnect-v2": "^8.5.1",
"ajv": "^8.11.0",
"ajv-formats": "^2.1.1",
"apollo-cache-inmemory": "^1.6.6",
"apollo-link-http": "^1.5.17",
"array.prototype.flat": "^1.2.4",
"array.prototype.flatmap": "^1.2.4",
"cids": "^1.0.0",
Expand Down Expand Up @@ -263,6 +265,7 @@
"qs": "^6.9.4",
"rc-slider": "^10.0.1",
"react": "^18.2.0",
"react-apollo": "^3.1.5",
"react-dom": "^18.2.0",
"react-feather": "^2.0.8",
"react-helmet": "^6.1.0",
Expand Down
35 changes: 35 additions & 0 deletions src/apollo/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ApolloClient } from '@apollo/client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { getApiUrl } from 'constants/tokens'

export const jediSwapClient = new ApolloClient({
link: new HttpLink({
uri: getApiUrl(),
headers: {
// 'm-color': 'blue',
},
}),
cache: new InMemoryCache({
dataIdFromObject: (object) => {
switch (object.__typename) {
case 'TokenDayData': {
return `${object.tokenAddress}${object.datetime}`
}
case 'FactoryDayData': {
return `${object.id}${object.dayId}`
}
case 'Token': {
return `${object.tokenAddress}${object.name}`
}
case 'Pool': {
return `${object.poolAddress}${object.datetime}`
}
default: {
return object.id || object._id
}
}
},
}),
shouldBatch: true,
})
32 changes: 32 additions & 0 deletions src/apollo/queries.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import gql from 'graphql-tag'

const TokenFields = `
fragment TokenFields on Token {
tokenAddress
name
symbol
derivedETH
volume
volumeUSD
untrackedVolumeUSD
totalValueLocked
totalValueLockedUSD
txCount
feesUSD
}
`

export const TOKENS_DATA = ({ tokenIds = [] }) => {
const tokenString = `[${tokenIds.map((token) => `"${token}"`).join(',')}]`

let queryString = `
${TokenFields}
query tokensData {
tokensData(first: 500, where: {tokenAddressIn: ${tokenString}, periodIn: "one_day"}) {
token{...TokenFields}
period
}
}
`
return gql(queryString)
}
42 changes: 6 additions & 36 deletions src/components/CurrencyInputPanel/FiatValue.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,57 +16,27 @@ const FiatLoadingBubble = styled(LoadingBubble)`
height: 1rem;
`

export function FiatValue({
fiatValue,
priceImpact,
}: {
fiatValue: { data?: number; isLoading: boolean }
priceImpact?: Percent
}) {
const { formatNumber, formatPercent } = useFormatter()

const priceImpactColor = useMemo(() => {
if (!priceImpact) {
return undefined
}
if (priceImpact.lessThan('0')) {
return 'success'
}
const severity = warningSeverity(priceImpact)
if (severity < 1) {
return 'neutral3'
}
if (severity < 3) {
return 'deprecated_yellow1'
}
return 'critical'
}, [priceImpact])

if (fiatValue.isLoading) {
return <FiatLoadingBubble />
}
export function FiatValue({ fiatValue, priceImpact }: { fiatValue: number; priceImpact?: Percent }) {
const { formatNumber } = useFormatter()

return (
<Row gap="sm">
<ThemedText.LabelSmall color="neutral1">
{fiatValue.data ? (
formatNumber({
input: fiatValue.data,
type: NumberType.FiatTokenPrice,
})
{fiatValue ? (
formatNumber({ input: fiatValue, type: NumberType.FiatTokenPrice })
) : (
<MouseoverTooltip text={<Trans>Not enough liquidity to show accurate USD value.</Trans>}>-</MouseoverTooltip>
)}
</ThemedText.LabelSmall>
{priceImpact && (
{/* {priceImpact && (
<ThemedText.BodySmall color={priceImpactColor}>
<MouseoverTooltip
text={<Trans>The estimated difference between the USD values of input and output amounts.</Trans>}
>
(<Trans>{formatPercent(priceImpact.multiply(-1))}</Trans>)
</MouseoverTooltip>
</ThemedText.BodySmall>
)}
)} */}
</Row>
)
}
4 changes: 2 additions & 2 deletions src/components/CurrencyInputPanel/SwapCurrencyInputPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ interface SwapCurrencyInputPanelProps {
pair?: Pair | null
hideInput?: boolean
otherCurrency?: Currency | null
fiatValue?: { data?: number; isLoading: boolean }
fiatValue?: number
priceImpact?: Percent
id: string
showCommonBases?: boolean
Expand Down Expand Up @@ -398,7 +398,7 @@ const SwapCurrencyInputPanel = forwardRef<HTMLInputElement, SwapCurrencyInputPan
<span />
)}
<LoadingOpacityContainer $loading={loading}>
{fiatValue && <FiatValue fiatValue={fiatValue} priceImpact={priceImpact} />}
{fiatValue === 0 ? 'N/A' : fiatValue && <FiatValue fiatValue={fiatValue} priceImpact={priceImpact} />}
</LoadingOpacityContainer>
</RowBetween>
</FiatRow>
Expand Down
11 changes: 11 additions & 0 deletions src/connectors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@ import { InjectedConnector } from '@starknet-react/core'

export const NETWORK_CHAIN_ID: number = parseInt(process.env.REACT_APP_CHAIN_ID ?? '5')

export const isProductionEnvironment = () => {
if (!window.location) {
return false
}
if (String(window.location) === '//') {
return false
}
const host = new URL(String(window.location))?.host || ''
return host === 'app.jediswap.xyz'
}

export const isTestnetEnvironment = () => {
if (!location) {
return false
Expand Down
8 changes: 8 additions & 0 deletions src/constants/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ChainId, Currency, NativeCurrency, Percent, Token } from '@vnaysn/jedis

// import { fortmatic, injected, portis, walletconnect, walletlink, argentX } from '../connectors'
import JSBI from 'jsbi'
import { isProductionEnvironment } from 'connectors'

export const DEFAULT_CHAIN_ID = ChainId.MAINNET
export const NONFUNGIBLE_POSITION_MANAGER_ADDRESSES = '0xC36442b4a4522E871399CD717aBDD847Ab11FE88'
Expand All @@ -17,6 +18,13 @@ export const MAX_UINT128 = BigInt(2) ** BigInt(128) - BigInt(1)
export const NATIVE_CHAIN_ID = 'NATIVE'
export const ZERO_ADDRESS_STARKNET = '0x0000000000000000000000000000000000000000000000000000000000000000'

export const getApiUrl = () => {
if (isProductionEnvironment()) {
return 'https://api.v2.goerli.jediswap.xyz/graphql'
}
return 'https://api.v2.jediswap.xyz/graphql'
}

const cachedNativeCurrency: { [chainId: string]: NativeCurrency | Token } = {}
export function nativeOnChain(chainId: ChainId): NativeCurrency | Token {
if (cachedNativeCurrency[chainId]) return cachedNativeCurrency[chainId]
Expand Down
3 changes: 2 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import RadialGradientByChainUpdater from './theme/components/RadialGradientByCha
import { goerli, mainnet, sepolia } from '@starknet-react/chains'
import { StarknetConfig, publicProvider, argent, braavos } from '@starknet-react/core'
import { StarknetProvider } from 'context/StarknetProvider'
import { jediSwapClient } from 'apollo/client'

function Updaters() {
const location = useLocation()
Expand Down Expand Up @@ -66,7 +67,7 @@ createRoot(container).render(
<HashRouter>
<LanguageProvider>
{/* <Web3Provider> */}
<ApolloProvider client={apolloClient}>
<ApolloProvider client={jediSwapClient}>
<BlockNumberProvider>
<Updaters />
<ThemeProvider>
Expand Down
64 changes: 55 additions & 9 deletions src/pages/Pool/PositionPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { LoadingRows } from './styled'
import { useContractWrite } from '@starknet-react/core'
import { cairo, Call, CallData, validateAndParseAddress } from 'starknet'
import { DEFAULT_CHAIN_ID, MAX_UINT128, NONFUNGIBLE_POOL_MANAGER_ADDRESS } from 'constants/tokens'
import TokensList from 'data/tokens-list.json'

const PositionPageButtonPrimary = styled(ButtonPrimary)`
width: 228px;
Expand Down Expand Up @@ -168,6 +169,16 @@ const NFTImage = styled.img`
z-index: 1;
`

import { CoinGeckoClient } from 'coingecko-api-v3'
import { useQuery } from 'react-query'
import { jediSwapClient } from 'apollo/client'
import { TOKENS_DATA } from 'apollo/queries'
const client = new CoinGeckoClient({
timeout: 10000,
autoRetry: true,
apiKey: 'CG-LjiMiXQR6FUgXee6s89GnnrD',
})

function CurrentPriceCard({
inverted,
pool,
Expand Down Expand Up @@ -667,14 +678,49 @@ function PositionPageContent() {
return amount0.add(amount1)
}, [price0, price1, feeValue0, feeValue1])

const fiatValueOfLiquidity: CurrencyAmount<Token> | null = useMemo(() => {
if (!price0 || !price1 || !position) {
return null
const separatedFiatValueofLiquidity = useQuery({
queryKey: [`fiat_value_0/${position?.amount0.toSignificant()}/${position?.amount0.currency.symbol}`],
queryFn: async () => {
const ids = []
if (!position?.amount0 && !position?.amount1) return
if (position?.amount0) ids.push(position?.amount0.currency.address)
if (position?.amount1) ids.push(position?.amount1.currency.address)
let result = await jediSwapClient.query({
query: TOKENS_DATA({ tokenIds: ids }),
fetchPolicy: 'cache-first',
})

try {
if (result.data) {
const tokensData = result.data.tokensData
if (tokensData) {
const [price0, price1] = [tokensData[0], tokensData[1]]
return { token0usdPrice: price1?.period?.one_day?.close, token1usdPrice: price0?.period?.one_day?.close }
}
}
} catch (e) {
console.log(e)
return { token0usdPrice: null, token1usdPrice: null }
}
},
})

const { token0usdPrice, token1usdPrice } = useMemo(() => {
if (!separatedFiatValueofLiquidity.data) return { token0usdPrice: undefined, token1usdPrice: undefined }
return {
token0usdPrice: separatedFiatValueofLiquidity.data.token0usdPrice
? separatedFiatValueofLiquidity.data.token0usdPrice * position?.amount0.toSignificant()
: undefined,
token1usdPrice: separatedFiatValueofLiquidity.data.token1usdPrice
? separatedFiatValueofLiquidity.data.token1usdPrice * position?.amount1.toSignificant()
: undefined,
}
const amount0 = price0.quote(position.amount0)
const amount1 = price1.quote(position.amount1)
return amount0.add(amount1)
}, [price0, price1, position])
}, [separatedFiatValueofLiquidity])

const fiatValueofLiquidity = useMemo(() => {
if (token0usdPrice && token1usdPrice) (Number(token0usdPrice) + Number(token1usdPrice)).toFixed(4)
return undefined
}, [token0usdPrice, token1usdPrice])

useEffect(() => {
if (callData) {
Expand Down Expand Up @@ -873,9 +919,9 @@ function PositionPageContent() {
<Label>
<Trans>Liquidity</Trans>
</Label>
{fiatValueOfLiquidity?.greaterThan(new Fraction(1, 100)) ? (
{fiatValueofLiquidity ? (
<ThemedText.DeprecatedLargeHeader fontSize="36px" fontWeight={535}>
<Trans>${fiatValueOfLiquidity.toFixed(2, { groupSeparator: ',' })}</Trans>
<Trans>${fiatValueofLiquidity}</Trans>
</ThemedText.DeprecatedLargeHeader>
) : (
<ThemedText.DeprecatedLargeHeader color={theme.neutral1} fontSize="36px" fontWeight={535}>
Expand Down
Loading

0 comments on commit 92d3954

Please sign in to comment.