Skip to content

Commit

Permalink
Merge branch '167-show-usd-value-for-tokens-in-swap-page-and-lp-page'…
Browse files Browse the repository at this point in the history
… into staging
  • Loading branch information
vnaysngh-mudrex committed Feb 19, 2024
2 parents 751c8fd + 0b6fad0 commit 93ad83e
Show file tree
Hide file tree
Showing 13 changed files with 436 additions and 86 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
8 changes: 4 additions & 4 deletions src/components/CurrencyInputPanel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ interface CurrencyInputPanelProps {
pair?: Pair | null
hideInput?: boolean
otherCurrency?: Currency | null
fiatValue?: { data?: number; isLoading: boolean }
fiatValue?: number
id: string
showCommonBases?: boolean
showCurrencyAmount?: boolean
Expand Down Expand Up @@ -310,9 +310,9 @@ export default function CurrencyInputPanel({
</ThemedText.DeprecatedBody>
</RowFixed>
)}
{/* <LoadingOpacityContainer $loading={loading}>
{fiatValue && <FiatValue fiatValue={fiatValue} />}
</LoadingOpacityContainer> */}
<LoadingOpacityContainer $loading={loading}>
{fiatValue === 0 ? 'N/A' : fiatValue && <FiatValue fiatValue={fiatValue} />}
</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
80 changes: 61 additions & 19 deletions src/pages/AddLiquidity/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ import { BigNumberish, cairo, Call, CallData, hash, num } from 'starknet'
import JSBI from 'jsbi'
import { toI32 } from 'utils/toI32'
import { useApprovalCall } from 'hooks/useApproveCall'
import { useQuery } from 'react-query'
import { jediSwapClient } from 'apollo/client'
import { TOKENS_DATA } from 'apollo/queries'
import { isAddressValidForStarknet } from 'utils/addresses'

const DEFAULT_ADD_IN_RANGE_SLIPPAGE_TOLERANCE = new Percent(50, 10_000)

Expand Down Expand Up @@ -210,6 +214,61 @@ function AddLiquidity() {
outOfRange ? ZERO_PERCENT : DEFAULT_ADD_IN_RANGE_SLIPPAGE_TOLERANCE
)

const separatedFiatValueofLiquidity = useQuery({
queryKey: ['fiat_value', position?.amount0, position?.amount1],
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]]
const isToken0InputAmount =
isAddressValidForStarknet(position?.amount0.currency.address) ===
isAddressValidForStarknet(price0.token.tokenAddress)
const price0_one_day = price0?.period?.one_day?.close
const price1_one_day = price1?.period?.one_day?.close
return {
token0usdPrice: isToken0InputAmount ? price0_one_day : price1_one_day,
token1usdPrice: isToken0InputAmount ? price1_one_day : price0_one_day,
}
}
}

return { token0usdPrice: undefined, token1usdPrice: undefined }
} catch (e) {
console.log(e)
return { token0usdPrice: null, token1usdPrice: null }
}
},
})

const { token0usdPrice, token1usdPrice } = useMemo(() => {
if (!separatedFiatValueofLiquidity.data) return { token0usdPrice: undefined, token1usdPrice: undefined }

const token0usdPrice = separatedFiatValueofLiquidity.data.token0usdPrice
? Number(separatedFiatValueofLiquidity.data.token0usdPrice) * Number(position?.amount0.toSignificant())
: undefined
const token1usdPrice = separatedFiatValueofLiquidity.data.token1usdPrice
? Number(separatedFiatValueofLiquidity.data.token1usdPrice) * Number(position?.amount1.toSignificant())
: undefined

const isLiquidityToken0PositionToken0 =
position?.amount0.currency.address === (parsedAmounts.CURRENCY_A?.currency as any).address
return {
token0usdPrice: isLiquidityToken0PositionToken0 ? token0usdPrice : token1usdPrice,
token1usdPrice: isLiquidityToken0PositionToken0 ? token1usdPrice : token0usdPrice,
}
}, [separatedFiatValueofLiquidity])

useEffect(() => {
if (txData) console.log(txData, 'txData')
}, [txData])
Expand Down Expand Up @@ -512,23 +571,6 @@ function AddLiquidity() {
</AutoColumn>
)

const usdcValueCurrencyA = usdcValues[Field.CURRENCY_A]
const usdcValueCurrencyB = usdcValues[Field.CURRENCY_B]
const currencyAFiat = useMemo(
() => ({
data: usdcValueCurrencyA ? parseFloat(usdcValueCurrencyA.toSignificant()) : undefined,
isLoading: false,
}),
[usdcValueCurrencyA]
)
const currencyBFiat = useMemo(
() => ({
data: usdcValueCurrencyB ? parseFloat(usdcValueCurrencyB.toSignificant()) : undefined,
isLoading: false,
}),
[usdcValueCurrencyB]
)

// const owner = useSingleCallResult(tokenId ? positionManager : null, 'ownerOf', [tokenId]).result?.[0]
// const ownsNFT =
// addressesAreEquivalent(owner, account) || addressesAreEquivalent(existingPositionDetails?.operator, account)
Expand Down Expand Up @@ -832,7 +874,7 @@ function AddLiquidity() {
showMaxButton={!atMaxAmounts[Field.CURRENCY_A]}
currency={currencies[Field.CURRENCY_A] ?? null}
id="add-liquidity-input-tokena"
fiatValue={currencyAFiat}
fiatValue={token0usdPrice}
showCommonBases
locked={depositADisabled}
/>
Expand All @@ -844,7 +886,7 @@ function AddLiquidity() {
onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '')
}}
showMaxButton={!atMaxAmounts[Field.CURRENCY_B]}
fiatValue={currencyBFiat}
fiatValue={token1usdPrice}
currency={currencies[Field.CURRENCY_B] ?? null}
id="add-liquidity-input-tokenb"
showCommonBases
Expand Down
Loading

0 comments on commit 93ad83e

Please sign in to comment.