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

Optimize stats page #2032

Open
wants to merge 5 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
16 changes: 14 additions & 2 deletions src/api/deposits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { useAccount } from "sections/web3-connect/Web3Connect.utils"
import BN from "bignumber.js"
import { BN_0 } from "utils/constants"
import { parseBalanceData, TBalance } from "./balances"
import { TAsset, TShareToken, useAssets } from "providers/assets"
import { TAsset, TBond, TShareToken, useAssets } from "providers/assets"
import { millisecondsInHour } from "date-fns/constants"
import { getAccountBalanceData } from "api/accountBalances"

Expand Down Expand Up @@ -181,7 +181,7 @@ const parseDepositData = (
export const useAccountAssets = (givenAddress?: string) => {
const { account } = useAccount()
const { api, isLoaded } = useRpcProvider()
const { getAssetWithFallback, getShareTokenByAddress, isShareToken } =
const { getAssetWithFallback, getShareTokenByAddress, isShareToken, isBond } =
useAssets()

const address = givenAddress ?? account?.address
Expand Down Expand Up @@ -305,6 +305,11 @@ export const useAccountAssets = (givenAddress?: string) => {
{ balance: TBalance; asset: TAsset }
> = new Map([])

const accountBondsMap: Map<
string,
{ balance: TBalance; asset: TBond }
> = new Map([])

const accountAssetsMap = balances.reduce<Map<string, TAccountAsset>>(
(acc, balance) => {
if (BN(balance.total).gt(0)) {
Expand All @@ -328,6 +333,12 @@ export const useAccountAssets = (givenAddress?: string) => {
balance,
asset,
})

if (isBond(asset))
accountBondsMap.set(balance.assetId, {
balance,
asset,
})
}

return acc
Expand Down Expand Up @@ -417,6 +428,7 @@ export const useAccountAssets = (givenAddress?: string) => {
accountAssetsMap,
accountShareTokensMap,
accountStableswapMap,
accountBondsMap,
isAnyPoolPositions,
}
},
Expand Down
73 changes: 72 additions & 1 deletion src/api/spotPrice.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { useQueries, useQuery } from "@tanstack/react-query"
import {
NotifyOnChangeProps,
useQueries,
useQuery,
} from "@tanstack/react-query"
import { QUERY_KEYS } from "utils/queryKeys"
import { u32 } from "@polkadot/types"
import { TradeRouter } from "@galacticcouncil/sdk"
Expand All @@ -8,6 +12,47 @@ import { Maybe } from "utils/helpers"
import { useRpcProvider } from "providers/rpcProvider"
import { A_TOKEN_UNDERLYING_ID_MAP } from "sections/lending/ui-config/aTokens"

const TRACKED_PROPS: NotifyOnChangeProps = ["data", "isLoading"]

export const useNewSpotPrice = (assetA?: string, assetB?: string) => {
const { tradeRouter, isLoaded } = useRpcProvider()
const tokenIn = assetA ?? ""
const tokenOut = assetB ?? ""

const routerInitialized = Object.keys(tradeRouter).length > 0

return useQuery(
QUERY_KEYS.newSpotPriceLive(tokenIn, tokenOut),
getNewSpotPrice(tradeRouter, tokenIn, tokenOut),
{ enabled: !!tokenIn && !!tokenOut && routerInitialized && isLoaded },
)
}

export const useNewSpotPrices = (
assetsIn: (string | undefined)[],
assetOut?: string,
noRefresh?: boolean,
) => {
const { tradeRouter, isLoaded } = useRpcProvider()

const assets = new Set(assetsIn.filter((a): a is string => !!a))

const tokenOut = assetOut ?? ""

const routerInitialized = Object.keys(tradeRouter).length > 0

return useQueries({
queries: Array.from(assets).map((tokenIn) => ({
queryKey: noRefresh
? QUERY_KEYS.newSpotPrice(tokenIn, tokenOut)
: QUERY_KEYS.newSpotPriceLive(tokenIn, tokenOut),
queryFn: getNewSpotPrice(tradeRouter, tokenIn, tokenOut),
notifyOnChangeProps: TRACKED_PROPS,
enabled: !!tokenIn && !!tokenOut && routerInitialized && isLoaded,
})),
})
}

export const useSpotPrice = (
assetA: Maybe<u32 | string>,
assetB: Maybe<u32 | string>,
Expand Down Expand Up @@ -73,6 +118,32 @@ export const getSpotPrice =
return { tokenIn, tokenOut, spotPrice }
}

export const getNewSpotPrice =
(tradeRouter: TradeRouter, tokenIn: string, tokenOut: string) => async () => {
const tokenInParam = A_TOKEN_UNDERLYING_ID_MAP[tokenIn] ?? tokenIn
const tokenOutParam = A_TOKEN_UNDERLYING_ID_MAP[tokenOut] ?? tokenOut
// X -> X would return undefined, no need for spot price in such case
if (tokenIn === tokenOut || tokenInParam === tokenOutParam)
return { tokenIn, tokenOut, spotPrice: "1" }

// error replies are valid in case token has no spot price
let spotPrice: string = "NaN"

try {
const res = await tradeRouter.getBestSpotPrice(
tokenInParam,
tokenOutParam,
)
if (res) {
spotPrice = res.amount
.shiftedBy(-res.decimals)
.decimalPlaces(10)
.toString()
}
} catch (e) {}
return { tokenIn, tokenOut, spotPrice }
}

export type SpotPrice = {
tokenIn: string
tokenOut: string
Expand Down
39 changes: 39 additions & 0 deletions src/api/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import { useRpcProvider } from "providers/rpcProvider"
import { ChartType } from "sections/stats/components/ChartsWrapper/ChartsWrapper"
import { undefinedNoop } from "utils/helpers"
import { QUERY_KEYS } from "utils/queryKeys"
import { chainsMap } from "@galacticcouncil/xcm-cfg"
import { Parachain, SubstrateApis } from "@galacticcouncil/xcm-core"
import BigNumber from "bignumber.js"
import { millisecondsInMinute } from "date-fns"
import { BN_0 } from "utils/constants"

export type StatsData = {
timestamp: string
Expand Down Expand Up @@ -159,3 +164,37 @@ const getAccountIdentity = (api: ApiPromise, address: string) => async () => {
identity: res.isSome ? res.unwrap()[0].info.display.asRaw.toUtf8() : null,
}
}

export const useTreasuryBalances = () => {
const polkadot = chainsMap.get("polkadot")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can use const { data: api } = useExternalApi("polkadot") hook instead


return useQuery(
QUERY_KEYS.treasuryBalances,
async () => {
const apiPool = SubstrateApis.getInstance()
const api = await apiPool.api((polkadot as Parachain).ws)

const balances = await Promise.all([
api.query.system.account(
"13RSNAx31mcP5H5KYf12cP5YChq6JeD8Hi64twhhxKtHqBkg",
),
api.query.system.account(
"14kovW62mmGZBRvbNT1w5J7m9SQskd5JTRTLKZLpkpjmZBJ8",
),
])

const totalBalances = balances.reduce((acc, balance) => {
const { free, reserved } = balance.data

const total = BigNumber(free.toString())
.plus(reserved.toString())
.toString()

return acc.plus(total)
}, BN_0)

return { balance: totalBalances.toString(), id: "5" }
},
{ staleTime: millisecondsInMinute },
)
}
3 changes: 2 additions & 1 deletion src/i18n/locales/en/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,7 @@
"stats.tiles.rewards.content": "TODO",
"stats.pie.rest.header.tvl": "tvl",
"stats.pie.rest.header.pol": "Treasury",
"stats.pie.rest.header.valueDisplay": "Balance",
"stats.chart.timeframe.all": "all",
"stats.chart.timeframe.month": "1m",
"stats.chart.timeframe.week": "1w",
Expand Down Expand Up @@ -820,7 +821,7 @@
"stats.pol.table.assets.header.asset": "Asset",
"stats.pol.table.assets.header.volume": "24h volume",
"stats.pol.table.assets.header.fee": "Fees (24H)",
"stats.pol.table.assets.header.pol": "Treasury",
"stats.pol.table.assets.header.pol": "Balance",
"stats.pol.chart.switcher.pol": "Treasury",
"stats.pol.chart.switcher.volume": "Volume",
"stats.omnipool.navigation.back": "Back to Stats",
Expand Down
Loading
Loading