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

Fix USD value #466

Open
wants to merge 8 commits 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
2 changes: 1 addition & 1 deletion .env.development
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ VITE_DOMAIN_URL=https://testnet-app.basilisk.cloud
VITE_INDEXER_URL=https://basilisk-rococo-explorer.play.hydration.cloud/graphql
VITE_GRAFANA_URL=https://grafana-api.play.hydration.cloud/api/ds/query
VITE_GRAFANA_DSN=5
VITE_USD_PEGGED_ASSET_NAME=USDT
VITE_USD_PEGGED_ASSET_NAME=KSM
VITE_USD_PEGGED_ASSET_ID=19
VITE_FF_XCM_ENABLED=true
VITE_ENV=rococo
Expand Down
2 changes: 1 addition & 1 deletion .env.production
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ VITE_DOMAIN_URL=https://app.basilisk.cloud
VITE_INDEXER_URL=https://basilisk-explorer.play.hydration.cloud/graphql
VITE_GRAFANA_URL=https://grafana-api.play.hydration.cloud/api/ds/query
VITE_GRAFANA_DSN=5
VITE_USD_PEGGED_ASSET_NAME=USDT
VITE_USD_PEGGED_ASSET_NAME=KSM
VITE_USD_PEGGED_ASSET_ID=14
VITE_FF_XCM_ENABLED=true
VITE_ENV=production
Expand Down
2 changes: 1 addition & 1 deletion .env.rococo
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ VITE_DOMAIN_URL=https://rococo-app.basilisk.cloud
VITE_INDEXER_URL=https://basilisk-rococo-explorer.play.hydration.cloud/graphql
VITE_GRAFANA_URL=https://grafana-api.play.hydration.cloud/api/ds/query
VITE_GRAFANA_DSN=5
VITE_USD_PEGGED_ASSET_NAME=USDT
VITE_USD_PEGGED_ASSET_NAME=KSM
VITE_USD_PEGGED_ASSET_ID=19
VITE_FF_XCM_ENABLED=false
VITE_ENV=rococo
Expand Down
16 changes: 9 additions & 7 deletions src/api/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useAssetMeta } from "./assetMeta"
import { useAssetDetails, useAssetDetailsList } from "./assetDetails"
import { getAssetLogo } from "components/AssetIcon/AssetIcon"
import { u32 } from "@polkadot/types"
import { Maybe, useQueryReduce, useQuerySelect } from "utils/helpers"
import { Maybe, useQueryReduce } from "utils/helpers"
import { TradeRouter } from "@galacticcouncil/sdk"
import { useApiPromise } from "utils/api"
import { useQuery } from "@tanstack/react-query"
Expand All @@ -24,13 +24,15 @@ export const useAsset = (id: Maybe<u32 | string>) => {
}

export const useUsdPeggedAsset = () => {
return useQuerySelect(useAssetDetailsList(), (data) =>
data.find(
(asset) =>
asset.symbol.toLowerCase() ===
import.meta.env.VITE_USD_PEGGED_ASSET_NAME.toLowerCase(),
),
const assets = useAssetDetailsList()

const usdId = assets.data?.find(
(asset) =>
asset.symbol.toLowerCase() ===
import.meta.env.VITE_USD_PEGGED_ASSET_NAME.toLowerCase(),
)

return usdId?.id ?? ""
}

export const useTradeAssets = () => {
Expand Down
3 changes: 2 additions & 1 deletion src/api/assetDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const useAssetDetailsList = (
assetType: ["Token"],
},
) => {
const { api } = useApiPromise()
const { api, isLoaded } = useApiPromise()

const normalizedIds = ids?.filter(isNotNil).map(normalizeId)

Expand All @@ -41,6 +41,7 @@ export const useAssetDetailsList = (
filter.assetType.includes(asset.assetType),
)
},
enabled: !!isLoaded,
})
}

Expand Down
83 changes: 78 additions & 5 deletions src/api/spotPrice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,24 @@ import { useQueries, useQuery } from "@tanstack/react-query"
import { QUERY_KEYS } from "utils/queryKeys"
import { u32 } from "@polkadot/types"
import { TradeRouter } from "@galacticcouncil/sdk"
import { BN_1, BN_10, BN_NAN } from "utils/constants"
import { BN_1, BN_NAN } from "utils/constants"
import BN from "bignumber.js"
import { useApiPromise } from "utils/api"
import { Maybe } from "utils/helpers"
import { useUsdPeggedAsset } from "./asset"

export const useSpotPrice = (
assetA: Maybe<u32 | string>,
assetB: Maybe<u32 | string>,
) => {
const { tradeRouter } = useApiPromise()
const { tradeRouter, isLoaded } = useApiPromise()
const tokenIn = assetA?.toString() ?? ""
const tokenOut = assetB?.toString() ?? ""

return useQuery(
QUERY_KEYS.spotPrice(tokenIn, tokenOut),
getSpotPrice(tradeRouter, tokenIn, tokenOut),
{ enabled: !!tokenIn && !!tokenOut },
{ enabled: !!tokenIn && !!tokenOut && isLoaded },
)
}

Expand Down Expand Up @@ -50,9 +51,9 @@ export const getSpotPrice =
// error replies are valid in case token has no spot price
let spotPrice = BN_NAN
try {
const res = await tradeRouter.getBestSpotPrice(tokenIn, tokenOut)
const res = await tradeRouter.getBestSpotPrice(tokenOut, tokenIn)
if (res) {
spotPrice = res.amount.div(BN_10.pow(res.decimals))
spotPrice = BN_1.shiftedBy(res.decimals).div(res.amount)
}
} catch (e) {}

Expand All @@ -64,3 +65,75 @@ export type SpotPrice = {
tokenOut: string
spotPrice: BN
}

const STABLECOIN_SYMBOL = "kusama"

export const useCoingeckoKsmPrice = () => {
return useQuery(QUERY_KEYS.coingeckoUsd, getCoingeckoSpotPrice, {
enabled: true,
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
retry: false,
staleTime: 1000 * 60 * 60 * 24, // 24h
})
}

export const getCoingeckoSpotPrice = async () => {
const res = await fetch(
`https://api.coingecko.com/api/v3/simple/price?ids=${STABLECOIN_SYMBOL.toLowerCase()}&vs_currencies=usd`,
)
const json = await res.json()
return json[STABLECOIN_SYMBOL.toLowerCase()].usd as number
}

export const useUsdSpotPrices = (ids: Maybe<u32 | string>[]) => {
const { tradeRouter } = useApiPromise()
const usdId = useUsdPeggedAsset()
const coingecko = useCoingeckoKsmPrice()

const ksmSpotPrice = coingecko.data

const assets = ids
.filter((a): a is u32 | string => !!a)
.map((a) => a.toString())

return useQueries({
queries: assets.map((tokenIn) => ({
queryKey: QUERY_KEYS.spotPriceUsd(tokenIn, usdId),
queryFn: async () => {
const data = await getSpotPrice(tradeRouter, tokenIn, usdId)()
const usdSpotPrice = data.spotPrice.times(ksmSpotPrice ?? 1)

return {
...data,
spotPrice: usdSpotPrice,
}
},
enabled: !!tokenIn && !!usdId && !!ksmSpotPrice,
})),
})
}

export const useUsdSpotPrice = (id: Maybe<u32 | string>) => {
const { isLoaded, tradeRouter } = useApiPromise()
const usdId = useUsdPeggedAsset()
const coingecko = useCoingeckoKsmPrice()

const tokenIn = id?.toString() ?? ""
const ksmSpotPrice = coingecko.data

return useQuery(
QUERY_KEYS.spotPriceUsd(tokenIn, usdId),
async () => {
const data = await getSpotPrice(tradeRouter, tokenIn, usdId)()
const usdSpotPrice = data.spotPrice.times(ksmSpotPrice ?? 1)

return {
...data,
spotPrice: usdSpotPrice,
}
},
{ enabled: !!tokenIn && !!usdId && !!ksmSpotPrice && isLoaded },
)
}
7 changes: 3 additions & 4 deletions src/components/AssetSelect/AssetSelectInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import { SSelectAssetButton } from "./AssetSelectInput.styled"
import { u32 } from "@polkadot/types"
import BigNumber from "bignumber.js"
import { getFloatingPointAmount } from "utils/balance"
import { useAsset, useUsdPeggedAsset } from "api/asset"
import { useSpotPrice } from "api/spotPrice"
import { useAsset } from "api/asset"
import { useUsdSpotPrice } from "api/spotPrice"
import { Maybe } from "utils/helpers"
import { TokenInputContainer, TokenInputMaxButton } from "./TokenInput"

Expand All @@ -32,9 +32,8 @@ export const AssetSelectInput = (props: {
disabled?: boolean
}) => {
const { t } = useTranslation()
const spotPrice = useUsdSpotPrice(props.asset)

const usd = useUsdPeggedAsset()
const spotPrice = useSpotPrice(props.asset, usd.data?.id)
const asset = useAsset(props.asset)

const aUSDValue = useMemo(() => {
Expand Down
2 changes: 1 addition & 1 deletion src/components/InvalidateOnBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const InvalidateOnBlock = (props: { children: ReactNode }) => {
const queryClient = useQueryClient()

useEffect(() => {
if (isLoaded) {
if (isLoaded && api) {
let cancel: () => void

api.rpc.chain
Expand Down
4 changes: 2 additions & 2 deletions src/components/WarningMessage/WarningMessage.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const useWarningsStore = create(
(set) => ({
warnings: {
depeg: {
visible: true,
visible: false,
},
},
setWarnings: (key, isOpen) =>
Expand All @@ -28,7 +28,7 @@ export const useWarningsStore = create(
}),
{
name: "warnings",
version: 0.1,
version: 0.2,
getStorage: () => window.sessionStorage,
},
),
Expand Down
7 changes: 3 additions & 4 deletions src/sections/assets/AssetsModalRow.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { u32 } from "@polkadot/types"
import { FC, useMemo } from "react"
import { useAsset, useUsdPeggedAsset } from "../../api/asset"
import { useAsset } from "../../api/asset"
import { useTokenBalance } from "../../api/balances"
import { useAccountStore } from "../../state/store"
import { Icon } from "../../components/Icon/Icon"
import { Text } from "../../components/Typography/Text/Text"
import { SAssetRow } from "./AssetsModalRow.styled"
import { Trans, useTranslation } from "react-i18next"
import { useSpotPrice } from "../../api/spotPrice"
import { useUsdSpotPrice } from "../../api/spotPrice"
import { BN_0 } from "../../utils/constants"
import { Maybe } from "utils/helpers"
import { DollarAssetValue } from "components/DollarAssetValue/DollarAssetValue"
Expand All @@ -26,10 +26,9 @@ export const AssetsModalRow: FC<AssetsModalRowProps> = ({
const { account } = useAccountStore()
const { t } = useTranslation()
const asset = useAsset(id)
const usd = useUsdPeggedAsset()
const balance = useTokenBalance(id, account?.address)

const spotPrice = useSpotPrice(id, usd.data?.id)
const spotPrice = useUsdSpotPrice(id)
const totalUSD = useMemo(() => {
if (balance.data && spotPrice.data) {
return balance.data.balance.times(spotPrice.data.spotPrice)
Expand Down
2 changes: 1 addition & 1 deletion src/sections/pools/PoolsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const PoolsPageData = () => {
))}
</div>
) : !!data?.length ? (
data?.map((pool) => <Pool key={pool.address} pool={pool} />)
data.map((pool) => <Pool key={pool.address} pool={pool} />)
) : (
<EmptyPoolsState />
)}
Expand Down
8 changes: 2 additions & 6 deletions src/sections/pools/PoolsPage.utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { PoolToken } from "@galacticcouncil/sdk"
import { u32 } from "@polkadot/types"
import { useUsdPeggedAsset } from "api/asset"
import { useTokensBalances } from "api/balances"
import { useAccountDepositIds, useAllDeposits } from "api/deposits"
import { usePools, usePoolShareTokens } from "api/pools"
import { useSpotPrices } from "api/spotPrice"
import { useUsdSpotPrices } from "api/spotPrice"
import BN from "bignumber.js"
import { useMemo } from "react"
import { useAccountStore } from "state/store"
Expand All @@ -28,8 +27,6 @@ export const useFilteredPools = ({ showMyPositions }: PoolsPageFilter) => {
showMyPositions ? account?.address : undefined,
)

const usd = useUsdPeggedAsset()

const poolAssetsId = pools.data?.reduce((acc, pool) => {
pool.tokens.forEach((token) => {
if (!acc.includes(token.id)) acc.push(token.id)
Expand All @@ -38,12 +35,11 @@ export const useFilteredPools = ({ showMyPositions }: PoolsPageFilter) => {
return acc
}, [] as string[])

const spotPrices = useSpotPrices(poolAssetsId ?? [], usd.data?.id)
const spotPrices = useUsdSpotPrices(poolAssetsId ?? [])

const queries = [
pools,
accountDeposits,
usd,
...allDeposits,
...spotPrices,
...userPoolBalances,
Expand Down
2 changes: 2 additions & 0 deletions src/sections/pools/header/PoolsHeader.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ export const getPoolTotal = (
new BigNumber(token.balance),
token.decimals,
)

const spotPrice = spotPrices.find((sp) => sp?.tokenIn === token.id)

const total = amount.times(spotPrice?.spotPrice ?? BN_0)

return acc.plus(total)
Expand Down
16 changes: 7 additions & 9 deletions src/sections/pools/pool/Pool.utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { PoolBase } from "@galacticcouncil/sdk"
import { useUsdPeggedAsset } from "api/asset"
import { useSpotPrice, useSpotPrices } from "api/spotPrice"
import { useUsdSpotPrice, useUsdSpotPrices } from "api/spotPrice"
import BN from "bignumber.js"
import { useMemo } from "react"
import { getFloatingPointAmount } from "utils/balance"
Expand All @@ -9,11 +8,10 @@ import { BN_0 } from "utils/constants"
export const useTotalInPool = (pool: PoolBase) => {
const [assetA, assetB] = pool.tokens

const usd = useUsdPeggedAsset()
const spotAtoAUSD = useSpotPrice(assetA.id, usd.data?.id)
const spotBtoAUSD = useSpotPrice(assetB.id, usd.data?.id)
const spotAtoAUSD = useUsdSpotPrice(assetA.id)
const spotBtoAUSD = useUsdSpotPrice(assetB.id)

const queries = [usd, spotAtoAUSD, spotBtoAUSD]
const queries = [spotAtoAUSD, spotBtoAUSD]
const isLoading = queries.some((q) => q.isLoading)

const data = useMemo(() => {
Expand All @@ -40,10 +38,10 @@ export const useTotalInPool = (pool: PoolBase) => {

export const useTotalInPools = (pools: PoolBase[]) => {
const tokens = pools.map(({ tokens }) => tokens.map(({ id }) => id)).flat()
const usd = useUsdPeggedAsset()
const spotPrices = useSpotPrices(tokens, usd.data?.id)

const queries = [usd, ...spotPrices]
const spotPrices = useUsdSpotPrices(tokens)

const queries = spotPrices
const isLoading = queries.some((q) => q.isInitialLoading)

const data = useMemo(() => {
Expand Down
11 changes: 4 additions & 7 deletions src/sections/pools/pool/details/PoolDetails.utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { getVolumeAssetTotalValue, useTradeVolumes } from "api/volume"
import { useMemo } from "react"
import { BN_0, BN_10 } from "utils/constants"
import { useSpotPrices } from "api/spotPrice"
import { useUsdPeggedAsset } from "api/asset"
import { useUsdSpotPrices } from "api/spotPrice"
import { useAssetMetaList } from "api/assetMeta"
import { isNotNil, normalizeId } from "../../../../utils/helpers"

Expand All @@ -19,9 +18,8 @@ export function usePoolDetailsTradeVolume(poolAddress: string) {
return { assets: Object.keys(sums), sums }
}, [volumes, poolAddress])

const usd = useUsdPeggedAsset()
const assets = useAssetMetaList(values?.assets ?? [])
const spotPrices = useSpotPrices(values?.assets ?? [], usd.data?.id)
const spotPrices = useUsdSpotPrices(values?.assets ?? [])

return useMemo(() => {
if (volumes.some((query) => query.isLoading) || !values) return null
Expand Down Expand Up @@ -49,7 +47,6 @@ export function usePoolDetailsTradeVolume(poolAddress: string) {

export function usePoolsDetailsTradeVolumes(poolAddresses: string[]) {
const volumes = useTradeVolumes(poolAddresses)
const usd = useUsdPeggedAsset()

const values = useMemo(() => {
return poolAddresses.map((poolAddress) => {
Expand Down Expand Up @@ -77,9 +74,9 @@ export function usePoolsDetailsTradeVolumes(poolAddresses: string[]) {
]

const assets = useAssetMetaList(allAssetsInPools)
const spotPrices = useSpotPrices(allAssetsInPools, usd.data?.id)
const spotPrices = useUsdSpotPrices(allAssetsInPools)

const queries = [...volumes, usd, assets, ...spotPrices]
const queries = [...volumes, assets, ...spotPrices]
const isLoading = queries.some((query) => query.isLoading)

const data = useMemo(() => {
Expand Down
Loading
Loading